Andrew Stopford's Weblog

poobah

Sponsors

News

Articles

Family

Old Blogs

Flex and .NET web services pt2

Following my last piece on Flex and .NET web services I will show how to use datasets and Flex. Some folks have reported issues when working with datasets and Flex. Macromedia's Mike Downey reports that Flash has no support for datasets but you must instead use object arrays.

In  keeping with the previous article lets translate Mikes C# code into VB.NET

Imports System
Imports System.Web.Services


Public
Class Employee
    Public name As String
    Public department As Integer
End Class


<WebServiceAttribute(Namespace:="http://services.r.us/", Description:="Access the Employee database")> _
Public Class Employees

    <WebMethodAttribute(Description:="Get a list of employees")> _
    Public Function getEmployees() As Employee()
        Dim employees As Employee() = New Employee(1){}
        employees(0) = New Employee()
        employees(0).name = "Bob"
        employees(0).department = 123
        employees(1) = New Employee()
        employees(1).name = "Mary"
        employees(1).department = 456
        Return employees
    End Function
End Class

If we run this code we get

<?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfEmployee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns=http://tempuri.org/Test/Service1>
- <Employee>
  <name>Bob</name>
  <department>123</department>
</Employee>
- <Employee>
  <name>Mary</name>
  <department>456</department>
</Employee>
</ArrayOfEmployee>

Note that the serialized object array structure is a much simpler model than a serialized dataset (this means less issues with aggregating our SOAP packet). However note that they have been some reports of multi dimension arrays not serializing correctly, this could lead to data loss or corruption in your SOAP packets. Lets try our own example, here we will query the SQL Server pubs database and convert the dataset to an object array.

Public Class TitleInfo
        Public strTitleName As String
    End Class


    <WebMethod()> _
    Public Function GetTitleData() As TitleInfo()

        Try
            'create dataset
            Dim dsTitleData As New DataSet

            'create connection
            Dim objCon As SqlConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
            'create data adapter
            Dim cmdSQL As SqlDataAdapter = New SqlDataAdapter("select top 5 title from titles", objCon)
            'fill dataset using data adapter
            cmdSQL.Fill(dsTitleData, "titles")

            'create object array, using row count as upper dim
            Dim objTitles As TitleInfo() = New TitleInfo(dsTitleData.Tables(0).Rows.Count - 1) {}

            'loop through dataset to add data to object array
            Dim intRsCount As Int16
            For intRsCount = 0 To dsTitleData.Tables(0).Rows.Count - 1
                objTitles(intRsCount) = New TitleInfo
                objTitles(intRsCount).strTitleName = dsTitleData.Tables(0).Rows(intRsCount)("title")
            Next

            'return object array
            Return objTitles

        Catch exp As Exception
            Throw
        End Try

    End Function

This function does a simlar job to the code Mike showed, it connects to the database, obtains the data and creates the dataset. We then loop through the dataset to populate the object array and return the object array. I have not included any error checking (other than the Try-Catch) to keep the code simple, you would normally want to add error checking (for example our array depends on a row count to get its size). The resulting SOAP packet is as follows.

  <?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfTitleInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns=http://tempuri.org/Test/Service1>
- <TitleInfo>
  <strTitleName>But Is It User Friendly?</strTitleName>
  </TitleInfo>
- <TitleInfo>
  <strTitleName>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</strTitleName>
  </TitleInfo>
- <TitleInfo>
  <strTitleName>Cooking with Computers: Surreptitious Balance Sheets</strTitleName>
  </TitleInfo>
- <TitleInfo>
  <strTitleName>Emotional Security: A New Algorithm</strTitleName>
  </TitleInfo>
- <TitleInfo>
  <strTitleName>Fifty Years in Buckingham Palace Kitchens</strTitleName>
  </TitleInfo>
  </ArrayOfTitleInfo>

To get at this data in Flex we can now get at the data using a standard web service call

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.macromedia.com/2003/mxml" width="600" height="450">
 <mx:WebService id="TestApp" wsdl="
http://localhost/test/test.asmx?WSDL" showBusyCursor="true" fault="alert(event.fault.faultstring)">
   <mx:operation name="GetTitleData">

   </mx:operation>
</mx:WebService>
<mx:VBox>
<mx:Button click="TestApp.GetTitleData.send()"></mx:Button>
    <mx:DataGrid dataProvider="{TestApp.GetTitleData.result}" widthFlex="1">
        <mx:columns>
            <mx:Array>
                <mx:DataGridColumn columnName="strTitleName" headerText="Title Name"/>        
            </mx:Array>
        </mx:columns>
    </mx:DataGrid>
</mx:VBox>
</mx:Application>

Here we populate a datagrid from the strTitleName field in our object array when the button event fires. Nore that the datagrid provider points to our web service function (GetTitleData) and the columnname points to the strTitleName field (if you have more fields in your object  array you could add more fields in your datagrid etc).

Comments

TrackBack said:

# April 5, 2004 7:31 AM

TrackBack said:

# June 10, 2004 1:41 PM

bodrul haque said:

Great article.
# July 6, 2004 9:55 AM

Melchior said:

Please,
Wow I return more than one datatable from de dataset
# July 14, 2004 4:41 PM

dfghdfgh said:

dfghdfgh

# July 4, 2006 6:59 PM

Perica said:

   [WebMethod]

   public Northwind.CategoriesDataTable CategoriesDataSet()

   {

       Northwind.CategoriesDataTable tbl = new Northwind.CategoriesDataTable();

       NorthwindTableAdapters.CategoriesTableAdapter ad = new NorthwindTableAdapters.CategoriesTableAdapter();

       ad.Fill(tbl);

       return tbl;

   }

....

<mx:DataGrid id="tbl" dataProvider="{ws.CategoriesDataSet.lastResult.diffgram.DocumentElement.Categories}">

           <mx:columns>

               <mx:DataGridColumn headerText="Column 1" dataField="CategoryID"/>

               <mx:DataGridColumn headerText="Column 2" dataField="CategoryName"/>

               <mx:DataGridColumn headerText="Column 3" dataField="Description"/>

           </mx:columns>

       </mx:DataGrid>

# July 4, 2006 7:00 PM

henry said:

can flex objects have customized ways to be serialized? if yes, how to do?

# August 11, 2006 3:36 AM

aditya said:

I think instead of using TestApp.GetTitleData.result it should be TestApp.GetTitleData.lastResult

# September 6, 2006 9:42 PM

fabian said:

Hi.. I have de same sample and not work, I recive the error:

HTTP Response Error

Error #2032: Error de secuencia

Some Idea ?

thx, great article

# September 23, 2006 2:27 PM

... said:

Nice site you have!

# February 22, 2007 3:39 PM

... said:

Lavoro eccellente! ..ringraziamenti per le informazioni..realmente lo apprezzo: D

# February 24, 2007 1:18 PM

... said:

luogo interessante, soddisfare interessante, buon!

# March 5, 2007 12:18 AM

... said:

E evidente che il luogo e stato fatto dalla persona che realmente conosce il mestiere!

# March 13, 2007 5:52 AM

... said:

Nice site. Thanks.

# March 15, 2007 3:51 PM

... said:

Lo trovo piuttosto impressionante. Lavoro grande fatto..)

# March 17, 2007 10:34 AM

... said:

Stupore! ho una sensibilit molto buona circa il vostro luogo!!!!

# March 19, 2007 1:42 AM

Erik Pettersson said:

Another way is to use SnoozeNet and throw the DataSet over to Flex/Flash in XML form and let snoozenet handle the conversion to proper objects on the client side.

Url: http://develop.itmaskinen.se/labs/snoozenet/

# April 11, 2007 8:18 AM

Rinaldi said:

Very nice this article and the site as well. Thank you.

# June 20, 2007 6:59 PM

Diwakar Chittora said:

can anyone let me know how to send the xml from client to the server which is using vb.net.

# July 11, 2007 1:11 PM