Featured Posts

Adobe Flex - Filter XML Data using E4X and RegExp Have you ever you wanted to filter your data like you would using the SQL LIKE condition? Well with E4X and RegExp you too can reap the benefits of pattern matching! Here...

Readmore

Flex Assets/File Manager – ASP VBScript - Version... I recently built a JavaScript file manager but I wanted more control and better usability instead of expanding on the JavaScript version I decided to build it using Flex....

Readmore

Getting at your SQL Database using Flex and .NET Web ServicesGetting at your SQL Database using Flex and .NET Web... So you gave up on trying to figure out how you can directly connect Flex to your database like with any server side language and decided to Google the answer. Well by now...

Readmore

Adobe Flex - Filter XML Data using E4X and RegExp Have you ever you wanted to filter your data like you would using the SQL LIKE condition? Well with E4X and RegExp you too can reap the benefits of pattern matching! Here...

Readmore

Fitchett Rss

Getting at your SQL Database using Flex and .NET Web Services

Posted on : 24-03-2009 | By : Michael Fitchett | In : ActionScript, Flex, Web Service

27

diagram-flex-webservice

So you gave up on trying to figure out how you can directly connect Flex to your database like with any server side language and decided to Google the answer. Well by now you probably figured out that your building a “client” application not a server side application.

So whats the best approach in achieving what you want? I have no clue, I do however have a solution that I put together using ASP.NET C#, Web Service, some duck tape and lot of Tylenol which makes getting at and querying your data just as easy as using SQL Manager which is actually a hell of a lot easier than querying your data with any server side code.

How it works - Exactly as that diagram above. Flex sends a request with the SQL Query string to the .NET Web Service that request runs the query against the database and returns the data in XML format to the web service and then the web service returns that XML data to Flex and then you do whatever you want with that XML data.

Lets get started already! – OK first things first lets build the .NET Web Service used to communicate with your database. I’m assuming you already have a database setup and Visual Studio (Express) installed.

You can download the latest version of Visual Studio Express for free here http://www.microsoft.com/Express/

 

web-service

 

ASP.NET C# Web Service - Open up Visual Studio and create a new Web Service project.

Lets build the database connection string in the web.config file so we dont have to change it in the code should the database connection string ever change.

Edit your web.config and insert the following code inside of the <configuration> tags

<appSettings>
<add key="yourConnectionName" value="Data Source=192.168.0.1,1433;Initial Catalog=DatabaseName;User ID=username;Password='password';" />
</appSettings>

 

Now in your source code file for your web service (”App_Code\yourfilename.cs”) create the following varible to get at the connection string we just built in the web.config

//Connection Strings pulled from web.config
string dbConnString= ConfigurationSettings.AppSettings["ConnectionName"];

 

Now lets create the function that talks to your database and gets the data in XML format

[WebMethod]
public XmlDocument getDataXML(string strQuery, string strRootNode, string strItemNode)
{
// Create vars out of connection string and query string
string dbConn = dbConnString;
string dbQuery = strQuery;

// Connect to the database and run the query
SqlConnection conn = new SqlConnection(dbConn);
SqlCommand cmd = new SqlCommand(dbQuery, conn);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
ds.DataSetName = strRootNode;
da.SelectCommand = cmd;
da.Fill(ds, strItemNode);

// Return the data as XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(ds.GetXml());
return xmlDoc;
}

OK now that you have built your web service function the next step is to test it out. To do this run your project, click the “getDataXML” link, fill out the form and click the Invoke button. You should get a page with your data in XML format. If this is not the case then you most likely did something wrong (or my instructions are wrong). If you cant figure out what it is then post your problem/error as a comment on this form and I will try to help you out when I have a chance.

If it did work for you then lets move on to the next step –>

 

flex-application

 

Ok now for the fun stuff. Flex makes it really easy to communicate with your web service so easy that it makes coding even more fun and rewarding (yes its possible that I may be a nerd).

Here is the code that I use to call my web service function and return the data in XML. You may notice that I set my resultFormat to e4x this will make filtering the data a lot easier.

When filtering your data you will have several options, I find pulling the data in once using your Web Service function and using e4x to filter the data the best option because it is less stress on the server.

Sorry for the formatting still getting used to this WordPress plugin.

<mx:WebService id="yourWebServiceID" wsdl="http://www.domain.com/Service.asmx?WSDL" showBusyCursor="true">
<mx:operation name="getDataXML" resultFormat="e4x">
<mx:request>
<strQuery>
SELECT * FROM yourTable
</strQuery>
<strRootNode>root</strRootNode>
<strItemNode>item</strItemNode>
</mx:request>
</mx:operation>
</mx:WebService>

 

Lets run the Web Service to get your data once the Flex Application has finished loading.

Add the following to your <mx:Application> tag:

creationComplete="init();"

Create the following function in your script section:

//Run once Flex has loaded
private function init():void
{
      //Send Get Request to .NET Web Service
      yourWebServiceID.getDataXML.send();
}

 

Now that we have are XML data lets display it using say oh a Flex DataGrid

<mx:DataGrid width="100%" height="100%" dataProvider="{yourWebServiceID.getDataXML.lastResult.root.item}"/>

 

That’s it! Yea OK it does seem like a lot of work but trust me its really not. If you already have a good understanding of Flex this should be cake for you.

If you run into any problems, have any ideas on improving the code and making it easier please drop a comment your contact information will not be shared with anyone unless you want it to (that is if I setup this blog correctly)

I’m looking for writers to share and give back to the online community so if you would like to be a content contributor please send me an email.

You can download the sample files here: Flex Web Service Sample (592) … When I have some more time I will include all of the project files along with a working example online for you to play with. You will be able to right-click on the source app and view the actual source.

I have noticed some problems being caused by the component I have been using to display the source code on this page so if you get errors in your Flex App when copying and pasting that is why. I am in the process of switching out the component to resolve this issue.

http://www.fitchett.me/wp-content/plugins/sociofluid/images/digg_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/delicious_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/technorati_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/google_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/myspace_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/facebook_32.png http://www.fitchett.me/wp-content/plugins/sociofluid/images/twitter_32.png

Comments (27)

hello michael fitchet,

im a newbies with flex and .net…
i think this article is very helpful for a newbie like me..
i have try to follow this article one by one but i encounter a problem when i try to create the webservice in vs 2005..i cant find the web.config item at the solution explorer while im using C# languange..but the item exist when i use VB languange..im sorry if my question is so stupid..but i really need a hands here..thank you.. :cry:

hi michael…

i found the solution of the above problem..
but could you provide this article with the project file..
im sure it will help a lot of newbies..tq..

Hi ryco,

Glad you found the web.config file.

It should be in the root of the “Solution Explorer”. You may have to run the project once first for Visual Studio 2005 to create the web.config then click the Refresh icon on the “Solution Explorer” window.

Per your request I will post all of the project files for this tutorial. Probably a good idea to provide the project files for all of my current and future post.

Thanks for the response glad to see someone is using these tutorials. :smile:

hmm, so the wsdl seems to work ok, but the flex portion doesn’t return any data.

warning: unable to bind to property ‘root’ on class ‘XMLList’ (class is not an IEventDispatcher)
warning: unable to bind to property ‘item’ on class ‘XMLList’ (class is not an IEventDispatcher)

@carl

Are you trying to create an XMLList out of the Web Service data?

Carl did you find a solution to your problem, I’m having the same issue. My webservice works fine, but Flex will not return any data, I’m looking at a blank datagrid. Help or advice from anyone would be a huge help.. Thanks.

@carl

Mike thank you for taking the time to post this tutorial.. You did mention that you were going to post the project files, are you still going to do that?
@Peter

I have posted some of the project sample files for download it includes the Flex MXML file and the .NET Web Service .cs file. I will be updating it soon with all of the project files along with an online working example. If you are still running into problems please post a comment and I will try to help you resolve them or if you like you can e-mail me michael@fitchett.me

Thanks,
Michael

hello michael fitchet,

First of all i would like to say thanks for the SQL DB connection through C# webservice .
I m a very newbies in flex and dotnet webservices …i haven gone through your article but stuck during deploy the C# class in flash…
could you please help me in that..
i have successfully connected with SQl DB and flash project but now i want to merge these two project 1> the flash project and 2> dotnet project what should i suppose to do i order to acchieve that..please reply soon

thanks
AMIT

You are an astodorm you predicted exactly in the first line from morninig trying to connect flex and sql server using php java etc and finally google helped me to land in your temple :-) thanks a lot

Hi Friend from last night i am trying make it myself work but for a new bee like me it was very tought, can you post a video ….

Now i am getting xml but when i try in flex i am getting a empty grid.. why please help me

@Carl
if you removed {resultFormat=”e4x”} in the webservice operation declaration, then it should work fine

Thanks for the explanation!!
you really helped me a lot.
I just have one more problem.
In my app I want to add a WHERE to the query: SELECT * FROM table WHERE field = .
How can I put the right value in the query.

Thanks by advance

Sorry for the super long delay in my response. I have been out it. I am sure by now you have figured this out but I wanted to respond anyways in case anyone else runs into this issue.

To pass a VAR in a query wrap it using “{}” like so:
WHERE to the query: SELECT * FROM table WHERE field = {varValue}

I’m having the same problem as carl. Webservice works fine. Nothing showing up in flex. I tried
msuwrx comment about removing resultFormat=”e4x” still no go

I have run into this problem a couple times. It can quickly be debugged by doing the following:

1. The node path is incorrect. Try doing a trace to see how your data is structured and then do another trace with the node path to see if you are getting a result and not blank.

1st example:
<mx:operation name="getDataXML" resultFormat="e4x" results=" trace(yourWebServiceID.getDataXML.lastResult)"

2nd example:
<mx:operation name="getDataXML" resultFormat="e4x" results=" trace(yourWebServiceID.getDataXML.lastResult.root.item)"

Make sure that you place the trace in the results trigger under webservice | operation.

2. The data being returned contains a null value and the component that the XML data is being read into does not like null values. To quickly test to see if this is the problem have your query return 1 record.

3. You are trying to retrieve the XML data before it has been created. This is very common to get around this use the results action and have it trigger a function then have the function load your component with the data.

4. You forgot to send the request to the web service to get your XML data.

yourWebServiceID.getDataXML.send();

It is very useful

Thank You

How do I get the datagrid to refresh/reload the xml on itemClick?

Thanks!

I’m sure you have already figured this out by now but if not all you need to do is resend the request to the web service like so:

myData.getDataXML.send();

You don’t need to refresh the datagrid this is automatically done.

Think of Flex as a constantly refreshing application, in other words you don’t need to write a function for each change that is made. If that makes any sense.

same problem as Carl. wsdl seems to be working fine, but flex does not return any result after making a web service call. Could anyone get this working ?

Yea I was able to get it working, but I wrote it =).

So testing the WSDL returns data?

What’s the problem you are having in Flex does it return an error or just no data?

Hi Michael

Just trying to work through your example – using Visual Studio 2008

I am getting the following error:
Error 1 The type or namespace name ‘XmlDocument’ could not be found (are you missing a using directive or an assembly reference?)

hiii,
I have already developed flex application. till now i dint need any database connectivity. but now i need it. For connection in Flex,while starting to make the project you need to specify what technology will u use for database connectivity. But i dint specify anything at that time. So how can i do it now?
How can i specify now that my project will use .net for connectivity.

thanx.

where shall I use this method? Shall I create a new web form or do it in service.asmx.cs file which is being created by default.

[WebMethod]
02 public XmlDocument getDataXML(string strQuery, string strRootNode, string strItemNode)
03 {
04 // Create vars out of connection string and query string
05 string dbConn = dbConnString;
06 string dbQuery = strQuery;
07
08 // Connect to the database and run the query
09 SqlConnection conn = new SqlConnection(dbConn);
10 SqlCommand cmd = new SqlCommand(dbQuery, conn);
11 SqlDataAdapter da = new SqlDataAdapter();
12 DataSet ds = new DataSet();
13 ds.DataSetName = strRootNode;
14 da.SelectCommand = cmd;
15 da.Fill(ds, strItemNode);
16
17 // Return the data as XML
18 XmlDocument xmlDoc = new XmlDocument();
19 xmlDoc.LoadXml(ds.GetXml());
20 return xmlDoc;
21 }

I have already solved above problem. Now I am able to get xml data. But while using flex, I am noe getting anything. just an error that wsdl uri is not proper.

plz reply as soon as you see this post. its urgent.

I got the solution of above problem also. thanks to ur post. it was really helpful.

Write a comment

Anti-Spam Protection by WP-SpamFree

Advertise Here