Flex Communication with ASP.NET WebService

No.of Views2262
Bookmarked0 times
Downloads 
Votes0
By  ninethsense   On  16 Feb 2010 00:02:57
Tag : Web Service , How to
Flex Communication with ASP.NET WebService
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, I tried to explain how to use an ordinary ASP.NET WebService to use with Adobe Flex. I used the flex tag <mx:WebService> to make this work. Basic knowledge in Flex is important to understand this article.

Remember that WebService is just an option. There are many other options like HTTPService, Flex Remoting, etc.

Image Loading

 

Background

I would like to point you to my earlier codegain article Flex HTTPService with ASP.NET where I demonstrated the use of flex tag <mx:HTTPService> to interact with an ordinary ASP.NET application.

Development Tools I Used

  • C# on Visual Studio 2008 with .NET Framework 3.5
  • Adobe Flex Builder 3.0
  • SQL Server 2008 sample database

What Attached Source Code Does

* ASP.NET WebService has two methods:

  •  GetEmployees() - To get records from webservice
  • SaveEmployee() - To save records to database via webservice

* Flex MXML file:

  • A DataGrid - To show records from WebService
  • A data entry box - To save records to database via WebService

What I Expect You to Get from this Article

* How to do database operations with Flex and ASP.NET
* How to interact with an ASP.NET WebService from Flex

  • How to get data from a WebService
  • How to send data to a WebService
  • How to send parameters when calling a webservice method

What to Remember When you Create an ASP.NET Webservice to Use with Flex?
* Nothing. You just create an ordinary ASP.NET WebService just like you did in the past.

Using the Code

Sql Script
For demonstration purposes, I created a sample database test and a sample table tblEmployee with the below schema. You will need this if you try to execute the attached sample.

CREATE TABLE [dbo].[tblEmployee]([EmpId] [nchar](50) NULL,[EmpName] [nchar](50) NULL,[EmpEmail] [nchar](50) NULL) ON [PRIMARY]

ASP.NET WebService

As I said, the WebService is just an ordinary ASP.NET WebService project with just two Web methods, one for getting records from database and the other one to save a new record.

Warning: Note that I created these files just for demonstration purposes and did not follow any standards either in ASP.NET WebService or Flex MXML file.

public class Service : WebService
{
SqlConnection con = new SqlConnection
("Data Source=localhost;Initial Catalog=test;User id=;Password=");
// Method to get all records from database[WebMethod]
public List<Employee> GetEmployees()
{
// Method does not follow any coding standards. This is just for demo purposes.var emplist = new List<Employee>();
Employee emp;
var da = new SqlDataAdapter("SELECT EmpId,
EmpName, EmpEmail from tblEmployee", con);
var dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
emp = new Employee
{
EmpId = dr["EmpId"].ToString(),
EmpName = dr["EmpName"].ToString(),
EmpEmail = dr["EmpEmail"].ToString()
};
emplist.Add(emp);
}      

return emplist;
}

// Method to save a record[WebMethod]
public void SaveEmployee(string empId, string empName, string empEmail)
{
// Method does not follow any coding standards. This is just for demo purposes.var cmd = new SqlCommand("INSERT INTO tblEmployee
(EmpId, EmpName, EmpEmail) VALUES(@empid, @empname, @empemail)",con);
cmd.Parameters.Add(new SqlParameter("@empid", empId));
cmd.Parameters.Add(new SqlParameter("@empname", empName));
cmd.Parameters.Add(new SqlParameter("@empemail", empEmail));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}   
}

// Employee Classpublic class Employee
{
public string EmpId = string.Empty;
public string EmpName = string.Empty;
public string EmpEmail = string.Empty;
}

Flex MXML

First, you need to add <mx:WebService> tag to your Flex application mxml file. Here is what I have now:

<mx:WebService id="ws" wsdl="http://localhost/TestWebService/Service.asmx?WSDL"
fault="fault(event)"><mx:operationname="GetEmployees"
resultFormat="object"
result="GetEmployees(event)"
/><mx:operationname="SaveEmployee"
resultFormat="object"
result="SaveEmployee(event)"
/></mx:WebService>

Note the call of webservice with URL: http://localhost/TestWebService/Service.asmx?WSDL.

You can see that I defined two operations:

1. GetEmployees and
2. SaveEmployee

which are defined in our ASP.NET WebService as well. When you invoke the required webservice call, the corresponding result event handler works and you will get the data sent by WebService in that attached event method. Here the attached event handler methods are GetEmployees(event) and SaveEmployee(event).

Remember that you can call a webservice dynamically also without using these tags. Also there are asynchronous token methods which I believe are out of scope of this article.Next I added a DataGrid to show the records we get from WebService. Also I used a Form to do data entry for adding new records.<mx:Panel>, <mx:HBox> etc. are used to get a good appearance for the application. These have nothing to do with our webservice calls.

How Stuff Works

In the <mx:Applicaiton> tag, I used creationComplete="init()" so that init()method will be called when the Flex application is loaded. Inside the init(), I called our webservice method ws.GetEmployees().

Once the ws.GetEmployees() method is called, the attached result handler gets invoked if the call is a success. Keep in mind, there is a common fault handler attached which will get triggered when there is an error associated with webservice.

The attached result handler of ws.GetEmployees() is:

private function GetEmployees(event:ResultEvent):void {
// Databind data from webservice to datagriddatagrid.dataProvider = event.result;
}

In this method, we bind the incoming data to our datagrid to show records.

Next is how we save records. I used three <mx:TextInput> boxes and one <mx:Button> for the data entry of a new record. An event handler AddRecord(event) is attached which triggers the click event.

<mx:Form x="608" y="74" width="100%" height="100%" borderStyle="solid"><mx:FormItem label="EmpId"><mx:TextInput width="106" id="txtEmpId"/></mx:FormItem><mx:FormItem label="EmpName"><mx:TextInput width="106" id="txtEmpName"/></mx:FormItem><mx:FormItem label="EmpEmail"><mx:TextInput width="106" id="txtEmpEmail"/></mx:FormItem><mx:FormItem width="156" horizontalAlign="right"><mx:Button label="Add" id="btnAdd" click="AddRecord(event)"/></mx:FormItem></mx:Form>

When the user clicks this button, the corresponding method will be triggered.

private function AddRecord(event:MouseEvent):void {
// Save a record using a WebService methodws.SaveEmployee(txtEmpId.text, txtEmpName.text, txtEmpEmail.text); //}

This method calls the WebService method ws.SaveEmployee() with the parameters which we get from the data entry form. As we know, again the result handler of this WebService method will be triggered which is:

private function SaveEmployee(event:ResultEvent):void {
// To Refresh DataGrid;ws.GetEmployees();
Alert.show("Saved Successfully");
}

In this event, we call the WebService ws.GetEmployees() again to refresh the DataGrid so that it displays new record also. Since there is an Alert.show() call, you will be notified instantly "Saved Successfully" once the data is saved. 

That's all, enjoy the cool concepts

Sample Project Source

Download source files -3 kb

Download xml source files -1 kb

 
Sign Up to vote for this article
 
About Author
 
ninethsense
Occupation-
Company-
Member Type-Junior
Location-Not Provided
Joined date-21 Jul 2009
Home Page-http://blog.ninethsense.com/
Blog Page-http://blog.ninethsense.com/
 
 
Other popularSectionarticles
    Another article of our series that talks about accessing URL shortening services programmatically. This article is talking about is.gd shortening service, how you can use it, and how to access it via your C#/VB.NET application.
    Published Date : 30/Aug/2010
    This is the first article of our series that talks about accessing URL shortening services programmatically. Here we introduce new concepts like the REST API. We also have a brief discussion of URL shortening services APIs and how you can access them. In addition, we are going to talk about .NET support for the REST API and tools and techniques available that would help us during our journey through the API. A working example built using C# and WinForms is available at the end of this a
    Published Date : 29/Aug/2010
    10 Rules to justify a true Web service
    Published Date : 16/Feb/2010
    Using the OneWay Web Service Attribute
    Published Date : 15/Feb/2010
    Access web service WSDL file in dynamically in client side using C#
    Published Date : 15/Feb/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top