banner



How To Create Asynchronous Web Service In Net

Synchronous communication betwixt .Internet applications and Web services makes the user look while each Spider web service processes requests and returns results. This can have a severe impact on the performance of the .NET application. Typically, a distributed .NET application requires information from multiple Web services. If the application performs the entire process of invoking the Web services synchronously, a client must wait non only until every Web service provider is contacted, but too through whatsoever connection or service delays.

Asynchronous Web services invocation solves this performance event and enhances the end user feel by increasing server efficiency. With the introduction of .Internet Framework 2.0, Microsoft has greatly enhanced the back up for asynchronous Web services invocation by introducing a new event-based programming model. This commodity examines this new feature and demonstrates how to take reward of it to create feature-rich and effective .Cyberspace applications. It also shows how to perform data binding directly with the results the Spider web service returns.

Event-Based Asynchronous Programming

Previous versions of the .NET Framework used the BeginInvoke/EndInvoke methods to invoke a Web service asynchronously. Version ii.0 adds a new way to asynchronously invoke Spider web services: an effect-based asynchronous programming model. It enables this new event programming model through the creation of properties and methods on the customer proxy form.

To follow the demonstration for implementing this model, you must beginning create a simple Web service that then tin can be invoked asynchronously from the client application. The following section walks yous through the process.

Create a Elementary Spider web Service

Open up Visual Studio 2005 and select New->Web Site from the File card. In the New Web Site dialog box, select ASP.Internet Web service from the listing of project templates, and specify the name of the Web service as AsyncWebServices.

In one case you have created the Spider web site, add together a new Spider web service file named HelloService.asmx to the project. If you open up the file and view the code, you volition find a method named HelloWorld already placed in the code-behind file of the Web service. For the purposes of this example, just apply this default sample method. Here is the code from the code-behind file of the HelloService:

using System.Web; using Arrangement.Collections; using Organisation.Web.Services; using Arrangement.Web.Services.Protocols;  [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,                    EmitConformanceClaims = truthful)] public class HelloService : System.Web.Services.WebService  {     [WebMethod]     public string HelloWorld()     {         return "Hi World";     } }        

Note: When you create a Web service through Visual Studio 2005, the code-behind file for the Web service is automatically placed in the App_Code directory, which is a new directory in ASP.Internet 2.0 that acts as a container for all the reusable classes in an ASP.Internet Web awarding.

Now that y'all've created the Web service, if you right click on it and select View in Browser, you will see the screen shown in Figure i.

Effigy 1. View Newly Created Web Service in Browser

If you lot click on the HelloWorld method, yous will see the screen shown in Figure 2.

Effigy 2. View HelloWorld Method in Browser

Clicking on the Invoke button in the Figure 2 results in the screen shown in Effigy three.

Figure 3. Invocation of HelloWorld Method

Figure 3 shows the output produced by the HelloWorld method. Now that you accept implemented and tested the Web service, you lot tin move on to the client awarding that will swallow the Web service.

Consume the Web Service Asynchronously from a Windows Forms Application

In this department, you lot create a Windows Forms application to consume the Spider web service. Create a new Visual C# Windows Forms awarding named AsyncWebServicesClient. Next, add a Web reference to the CategoriesService by selecting Project->Add Web Reference from the carte du jour. In the Add together Web Reference dialog box, enter the location of the Web service and hit Become. Then, specify the name of the Spider web reference equally HelloWorldServiceProxy, every bit shown in Figure iv.

Figure 4. Specify the Name of the Web Reference every bit HelloWorldServiceProxy

Now y'all are set to swallow the Web service. To showtime, import the Web service proxy namespace at the top of the Form1:

using AsyncWebServicesClient.HelloWorldServiceProxy;

To the grade, add a command button named btnInvokeHelloWorld and alter the click event of the command button to expect as follows:

private void btnInvokeHelloWorld_Click(object sender, EventArgs e) {     HelloService service = new HelloService();     //Hookup async result handler     service.HelloWorldCompleted += new          HelloWorldCompletedEventHandler(this.HelloWorldCompleted);     service.HelloWorldAsync(); }        

The above code shows the event handler HelloWorldCompleted (that is available through the proxy of the Web service) being hooked upward to a local method named HelloWorldCompleted. The method named HelloWorldAsync provides a way to asynchronously invoke the HelloWorld method.

The new <MethodName>Async provides a seamless way to asynchronously consume the Web service from a customer application. For case, if you lot have a Web service method named GetCategories and y'all want to leverage the asynchronous invocation framework, yous need to do ii things:

  • Create an event handler for the GetCategoriesCompleted method and hook it up to a local method that can process the results returned by the Web service.
  • Invoke the Web service method by calling the GetCategoriesAsync() method through the Spider web service proxy.

The local HelloWorldCompleted method is divers equally follows:

void HelloWorldCompleted(object sender,                          HelloWorldCompletedEventArgs args) {     //Display the return value     MessageBox.Bear witness(args.Result); }        

After the Spider web service has finished its execution and returned the results, the .Internet Framework will automatically invoke the above HelloWorldCompleted method. As you can run across, this method takes two arguments: an object of type "object" and a "HelloWorldCompletedEventArgs" object. You can capture the results returned by the Web service past using the Result holding of the HelloWorldCompletedEventArgs object (as shown in the above code). In this case, the output the Web service returns is displayed in a message box.

Implement Data Binding with a Web Service

Apart from the new Web service asynchronous invocation framework, .Cyberspace Framework ii.0 likewise introduces a new characteristic through which you can perform data binding, with the results returned from the Web service in a seamless mode. This section demonstrates this feature with a practical example. Information technology begins by creating the Web service.

Implementation of the Web service

To start, add a new Spider web service to the AsyncWebServices projection by correct-clicking on the project and selecting Add New Item from the context menu. In the Add together New Item dialog box, select Web service from the list of templates and name the Spider web service CategoriesService.asmx. Modify the code-behind of the CategoriesService.asmx file to expect as follows:

using System; using Organisation.Spider web; using Organisation.Collections; using Arrangement.Web.Services; using Organization.Web.Services.Protocols; using System.Data; using Organization.Data.SqlClient; using Organization.Diagnostics;  [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,                    EmitConformanceClaims = true)] public form CategoriesService : System.Web.Services.WebService { [WebMethod]     public DataSet GetCategories()     {         try         {             using (SqlConnection conn = new SqlConnection())             {                 string connectionString =                     System.Configuration.ConfigurationManager.                 ConnectionStrings["northwindConnectionString"].                 ConnectionString;                 conn.ConnectionString = connectionString;                 SqlCommand control = new SqlCommand                     ("Select * from Categories", conn);                 control.CommandType = CommandType.Text;                 SqlDataAdapter adapter = new                     SqlDataAdapter(command);                 DataSet categories = new DataSet("Categories");                 adapter.Fill(categories);                 return categories;             }         }         catch (Exception ex)         {             EventLog.WriteEntry("Application", ex.Message);             throw ex;         }     }  }        

Line-by-Line Code Breakdown

The above code get-go encloses the SqlConnection object within the scope of a using cake. Then, it retrieves the connexion string from the ConnectionStrings section of the web.config file:

string connectionString = System.Configuration.ConfigurationManager.     ConnectionStrings["northwindConnectionString"].     ConnectionString;        

The lawmaking stores the connection string directly nether the root <configuration> element in the web.config as follows:

<connectionStrings>     <add name="northwindConnectionString"          connectionString="server=localhost;uid=sa;pwd=thiru;                            database=northwind"/> </connectionStrings>        

Then, information technology sets the retrieved connection string to the ConnectionString property of the SqlConnection object. Later that, the code creates an instance of the SqlCommand object, passing to its constructor the SQL argument to exist executed and the SqlConnection object as arguments. Then, it sets the CommandType belongings of the SqlCommand object to CommandType.Text to indicate that it wants to execute a SQL statement through the SqlCommand object:

SqlCommand control = new SqlCommand("Select * from Categories", conn); control.CommandType = CommandType.Text;        

Next, information technology creates an instance of the SqlDataAdapter and passes in the SqlCommand object to its constructor:

SqlDataAdapter adapter = new SqlDataAdapter(control);

After that, the code creates a DataSet object so supplies the DataSet object as an statement to the Fill method of the SqlDataAdapter object:

DataSet categories = new DataSet("Categories"); adapter.Fill(categories);        

Finally, it returns the DataSet object back to the caller using the render statement:

return categories;

Now that you accept seen the implementation of the Spider web service, take a look at the client application that will consume the Web service.

Consume the Spider web Service from the Client

Open the previously created AsyncWebServicesClient project from Visual Studio 2005. Add together a Web reference to the CategoriesService by selecting Projection->Add Spider web Reference from the menu. In the Add Spider web Reference dialog box, enter the location of the Spider web service and specify the name of the Web reference as CategoriesServiceProxy. Once the Web reference is created, yous can import the namespace of the proxy using the following line:

using AsyncWebServicesClient.CategoriesServiceProxy;

Next, open Form1 and drag and driblet a DataGrid control onto the Form designer. Add some other control button named btnInvokeCategories to the form and modify the code in the Click upshot to look like the following:

private void btnInvokeCategories_Click(object sender, EventArgs e) {     CategoriesService service = new CategoriesService();     service.GetCategoriesCompleted += new         GetCategoriesCompletedEventHandler         (this.GetCategoriesCompleted);     service.GetCategoriesAsync(); }        

The implementation of the GetCategoriesCompleted method is as follows:

void GetCategoriesCompleted(object sender,                             GetCategoriesCompletedEventArgs args) {     //Bind returned results to the UI information grid     dataGrid1.DataSource = args.Effect; }        

As you can come across, the DataSet returned from the Spider web service is directly bound to a DataGrid command and displayed on the course. If you run the form and click on the Invoke Categories Service button, you lot will see the output shown in Figure five.

Figure 5. Run the Form and Click on the Invoke Categories Service Button

As Figure 5 shows, the categories data that the Web service returns is directly data leap to the DataGrid control.

Increment Developer Productivity, Enhance User Experience

The new asynchronous invocation framework that .NET Framework 2.0 introduced is an extremely useful feature that can get a long way toward increasing developer productivity. You can leverage the framework to increase the responsiveness of a .NET application, which greatly enhances the user experience every bit well.

This tutorial provided a thorough word of the asynchronous Web service invocation features of .Internet Framework 2.0 and provided examples. It likewise showed how to perform data binding with the results returned from a Spider web service. Although the application yous created was simple in functionality, it should provide a solid foundation for understanding how to easily implement the asynchronous Web service invocation feature in your .Internet applications.

Download the Code

To download the accompanying source code for the demo, click hither.

Most the Author

Thiru Thangarathinam has six years of feel in architecting, designing, developing, and implementing applications using object-oriented application development methodologies. He too possesses a thorough agreement of the software life cycle (design, development, and testing). He holds several certifications, including MCAD for .NET, MCSD, and MCP. Thiru is an expert with ASP.Net, .Cyberspace Framework, Visual C# .NET, Visual Basic .Internet, ADO.NET, XML Spider web services, and .NET Remoting. Thiru also has authored numerous books and articles. Contact him at [email protected]

How To Create Asynchronous Web Service In Net,

Source: https://www.developer.com/microsoft/dotnet/asynchronous-web-services-invocation-in-net-framework-2-0/

Posted by: matneyjoher1999.blogspot.com

0 Response to "How To Create Asynchronous Web Service In Net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel