Passing XML Between Flex and .NET Web Services
When you have a Flex project (or other types of projects) that consume .NET web services, it can make life much easier to pass XML to the service(s), instead of multiple string, ints, or other primative objects. Use XML to represent your object. It is much easier to process XML returned to Flex by a .NET web service than the other way around, because Flex converts many SOAP objects to ArrayCollections under-the-hood, and developers can access them natively or they can use E4X to parse the XML. It just depends on what works best for your development scenario.
.NET does not convert XML to a workable Object or DataSet under-the-hood (as far as I know), but it is easy to run the conversion pro grammatically, and you can be off and running with a workable DataSet or XMLDocument pretty quickly.
The project is an Event Scheduling Application:
The following is an example of how to achieve this.
First the Flex/ActionScript code:
After the user has entered the event data into the appropriate form fields, and they click the save button, the event handler for the save creates an XML representation of the event to pass to the .NET web service. (Notice the binding symbols for the values captured from startDate_df and endDate_df, name_ti, and description_ta which are the form fields depicted above).
{
//vars used to manage and manipulate xml to be sent to .NET web service
var eventXML:XML;
var eventXMLDoc:XMLDocument = new XMLDocument();
eventXML =
<startdate>{startDate_df.selectedDate.toUTCString()}</startdate>
<enddate>{endDate_df.selectedDate.toUTCString()}</enddate>
<starttime>{startDate_df.selectedDate.toUTCString()}</starttime>
<endtime>{endDate_df.selectedDate.toUTCString()}</endtime>
<name>{name_ti.text}</name>
<description>{description_ta.text}</description>
</calendarevent>
Now the code creates an instance of the WebService class and loads the WSDL for the web service.
eventXMLDoc.parseXML(eventXML);
//create a web service instance(or better yet use your Service Locator)
var dotNetWebService:WebService = new WebService();
//make sure you can communicate with the server
try
{
dotNetWebService.loadWSDL("http://localhost/yourServer/foo.asmx?WSDL");
//now that the web service object is set up we call the method that will create
//the calendar event on the windows server, show the busy cursor while processing
CursorManager.setBusyCursor();
//use an asynchronus token to add a responder for the web service ResultEvent
var token:AsyncToken = dotNetWebService.CreateCalenderEvent(eventXML);
token.addResponder(new ItemResponder(onCreateCalendarEventResult,onFault));
}
//catch the error and perform the neccessary error handling
catch(error:Error)
{
trace(error.message);
//log error to database, etc.
}
}
After the web service call has completed we remove the busy cursor and alert the user to the success of the operation.
private function onCreateCalendarEventResult(event:ResultEvent,responder:Object):void
{
//remove the busy cursor
CursorManager.removeBusyCursor();
var alert:Alert = Alert.show("Event Successfully Created","Added");
}
If something went wrong during the call to the web service, e.g. and exception was thrown by the C# code on the server, this fault handler removes the busy cursor and alerts the user to tell them that a fault occurred.
private function onFault(fault:FaultEvent):void
{
//remove the busy cursor CursorManager.removeBusyCurosr();
//log error and alert user that their event was not saved
trace(fault.fault.faultString);
var alert:Alert = Alert.show("The server encountered an error while saving your request","Fault")
}
Using C# to write our web service we can leverage the XMLDataSet, and DataSet classes to manipulate the calendar event data and save it to the Calendar database.
The C# is pretty straight forward- convert a string to an XMLDataSet and load a DataSet with the contents or “rows” of the XMLDataSet. Once that is completed, call a stored procedure (or write the SQL in-line) to save the event to the database using the familiar DataSet access syntax to extract the values needed for the insertion.
public void CreateCalendarEvent(string eventXML)
{
try
{
//sql connection and commands
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["FOO"].ConnectionString);
SqlCommand cmd = new SqlCommand("spCreateCalendarEvent",conn);
//set up the dataset that will feed the sql parameters
DataSet ds = null;
XmlDataDocument eventDataDoc = new XmlDataDocument();
//get the data into the XmlDataDocument
if (eventXML != null)
eventDataDoc.DataSet.ReadXml(new StringReader(eventXML));
ds = eventDataDoc.DataSet;
//this is the "row" that contains the event data we need to insert
//the calendar event into the database
DataRow dr = ds.Tables["CalendarEvent"].Rows[0];
//assign the parameters for the stored procedure call
cmd.Parameters.Add("@startDate", SqlDbType.DateTime);
cmd.Parameters.Add("@endDate", SqlDbType.DateTime);
cmd.Parameters.Add("@startTime", SqlDbType.DateTime);
cmd.Parameters.Add("@endTime", SqlDbType.DateTime);
cmd.Parameters.Add("@createdByName", SqlDbType.VarChar, 50);
cmd.Parameters.Add("@createdBySID", SqlDbType.VarChar, 47);
//now set the values for these parameters, converting strings back to dates
cmd.Parameters["@startDate"].Value = DateTime.Parse(dr["startDate"].ToString());
cmd.Parameters["@endDate"].Value = DateTime.Parse(dr["endDate"].ToString());
cmd.Parameters["@startTime"].Value = DateTime.Parse(dr["startTime"].ToString());
cmd.Parameters["@endTime"].Value = DateTime.Parse(dr["endTime"].ToString());
cmd.Parameters["@createdByName"].Value = HttpContext.Current.Request.LogonUserIdentity;
cmd.Parameters["@createdBySID"].Value = HttpContext.Current.Request.LogonUserIdentity.Owner;
//now execute the stored procedure
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.Writeline(ex.message);
}
}
}
About this entry
You’re currently reading “Passing XML Between Flex and .NET Web Services,” an entry on Binary Giant
- Published:
- 03.16.08 / 10pm
- Category:
- .NET, C#, Flex, Rich Internet Applications, Web Services

No comments
Jump to comment form | comments rss [?] | trackback uri [?]