Monday, June 17, 2013

Asynchronous programming in ASP.NET 4.5

Two days back I was going through the Scott Hanselman’s video on ASP.NET 4.5 and thought to share the same with everyone. The sample program taken here is from his video and I just modified some parts to demonstrate it in a better way.

This example uses Visual studio 2012 and MVC 4 Web API and ASP.NET 4.5. Also in the example we are going to consume the Web API using WebClient class. WebClient class provides common methods for sending data and receiving data from a resource identified by URI.
In ASP.NET 4.5 Microsoft has added more methods and properties that support consuming resources using both synchronous and asynchronous manner. You can go through the WebClient supported methods and properties in MSDN http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx.

I have created a MVC Web API project with 3 different controller classes Contacts, Temperature and Location which will be consumed by the client application (ASP.NET 4.5 Web application). To do that I have created a blank ASP.NET MVC 4 Web application as below:

clip_image002
Figure 1: Create a MVC 4 project with name “WebAPITest”

clip_image004
Figure 2: Select Web API project

clip_image006
Figure 3: Create new controller by right-clicking the “Controllers” folder

clip_image007
Figure 4: Modifying the name of the Controller class and select the template as “Empty API Controller”.

Follow the above steps in creating Controller classes for Contacts, Location and Temperature. You can search for creating Web API for more information in the C# corner site www.c-sharpcorner.com. I would be just providing high level view on the Web API that will be used in this article.
Here are my Controller classes created for the article:

using System.Collections.Generic;
using System.Web.Http;
using WebAPITest.Models;
namespace WebAPITest.Controllers
{
public class ContactsController : ApiController
    {
Contact[] contacts = new Contact[]
        {
new Contact {Name="John", ContactNumber="444-978-0678"},
new Contact {Name="Mary", ContactNumber="424-968-8678"},
new Contact {Name="Raj", ContactNumber="449-968-9678"},
new Contact {Name="Ram", ContactNumber="440-938-8678"}
        };
public IEnumerable<Contact> GetAllContacts()
        {
            System.Threading.Thread.Sleep(1000);
return contacts;
        }
    }
}
using System.Web.Http;
 
namespace WebAPITest.Controllers
{
    public class LocationController : ApiController
    {
        public string GetCurrentLocation()
        {
            System.Threading.Thread.Sleep(1000);
            return "San Jose, CA";
        }
    }
}
using System.Web.Http;
 
namespace WebAPITest.Controllers
{
    public class TemperatureController : ApiController
    {
        public string GetCurrentTemperature()
        {
            System.Threading.Thread.Sleep(1000);
            return "54F";
        }
    }
}

Observe that I have intentionally added Thread.Sleep in all the methods so that the thread consuming the API has to wait for some time. This would help us to understand the asynchronous programming.
Now you can test your web application by clicking CTRL+5 and you should see the home page immediately as below:

clip_image009
Figure 5: Home page

Now you can test your API by calling controller names as below:

clip_image011
Figure 6: Append “api/{Controller Name}”

You should see at the bottom of the browser a popup that gets the response in JSON format:

clip_image013
Figure 7: JSON response

Click on open and you should see the response in JSON format and this confirms that your program is correct.

clip_image015
Figure 8: Opening response in notepad

You will find that this has executed the method public IEnumerable<Contact> GetAllContacts()in the controller class and we got the List<Contacts> as a response in JSON format. 

Similarly we can check for Location and Temperature APIs by appending api/Location, api/Temperature at the end of the home page URL.

Now create one more project of type web application and consume the APIs using WebClient class as below:

Default.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="ClientApplication.Details" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Contacts:<br />
    <asp:ListView ID ="listContacts" runat="server">
     <LayoutTemplate>
    <table runat="server" id="table1" >
      <tr runat="server" id="itemPlaceholder" ></tr>
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr id="Tr1" runat="server">
      <td id="Td1" runat="server">
        <%-- Data-bound content. --%>
        <asp:Label ID="NameLabel" runat="server" 
          Text='<%#Eval("Name") %>' />
      </td>
    </tr>
  </ItemTemplate>
 
    </asp:ListView><br />
     Temperature:<br />
        <asp:Label ID ="lbltemperature" runat="server"></asp:Label><br />
        Location:<br />
        <asp:Label ID="lblLocation" runat="server"></asp:Label><br />
        Elapsed Time:<br />
         <asp:Label ID="lblElapsed" runat="server"></asp:Label><br />
    </div>
    </form>
</body>
</html>

Code behind:
using System;
using System.Collections.Generic;
using System.Net;
 
namespace ClientApplication
{
    public class Contact
    {
        public string Name { get; set; }
        public string ContactNumber { get; set; }
    }
    public partial  class Details : System.Web.UI.Page
    {
       
        protected  void Page_Load(object sender, EventArgs e)
        {
 
            string time = DateTime.Now.ToString();
 
            var clientcontacts = new WebClient().DownloadString("http://localhost:8687/api/Contacts");
            var clientTemperature = new WebClient().DownloadString("http://localhost:8687/api/Temperature");
            var clientLocation = new WebClient().DownloadString("http://localhost:8687/api/Location");
 
 
            time = time + DateTime.Now.ToString();
           
 
            var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(clientcontacts);
            var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject(clientTemperature);
            var location = Newtonsoft.Json.JsonConvert.DeserializeObject(clientLocation);
 
            listContacts.DataSource = contacts;
            listContacts.DataBind();
 
            lblLocation.Text = location.ToString();
            lbltemperature.Text = temperature.ToString();
            lblElapsed.Text = time;
           }
    }
}

In this client web application program we are trying to consume the 3 APIs synchronously using WebClient instance. To get the time taken to complete the response for 3 API calls we have recorded the start and end time of the total request/response. Then we bind the response data to the controls in the ASPX page.

Make sure that your Web API is running first and now start your web application and you should see the UI page as below.

clip_image017
Figure 9: Client UI page

You observe that the request started at 6/17/2013 10:15:09 and ended at 10:51:12 PM. So overall time it took is 3 seconds to complete the request. In a real time projects we may need to call multiple services for performing certain business logic functionality and if the request is more I/O specific or database specific then it would be time consuming task for waiting till all the requests are completed in order.

ASP.NET 4.5 came up with support for asynchronous execution of the same so that we can consume multiple resources at one time and thus saving the response time to the user.

To do this we need to perform some changes to the client application:
-          Make your ASPX page to support Async operations by adding Async = “True”. 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="ClientApplication.Details" Async="true" %>

- Now make your page_load method to behave Async by adding “async” to the method.
protected async void Page_Load(object sender, EventArgs e)
-          Now instead of getting response as a string using the WebClient method: new WebClient().DownloadString("http://localhost:8687/api/Contacts");

Modify it to behave asynchronously by modifying the method DownloadStringTaskAsync(string address). DownloadStringTaskAsync downloads the resource as a String from the URI specified as an asynchronous operation using a task object.

clip_image019
          var clientcontacts = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Contacts");
         var clientTemperature = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Temperature");
         var clientLocation = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Location");

- Next step is to add code to ask the program to wait till all the above tasks are completed. In .NET 4.5 there is a keyword introduced called “await” which instructs the executing thread to wait till some specific Task method is completed. Here is the total code:

await Task.WhenAll(clientcontacts, clientTemperature, clientLocation);
 
The purpose of the above code is to wait till all the tasks have been completed.
clip_image020
 
You can go through MSDN to learn more about “Task” and the methods it supports.

- Immediately you would see red lines below the code for these 3 lines. This is because we are not executing the code synchronously and asking Task object to get back to us once the task is completed. So you cannot read the response directly instead you need now to specify .result to get the result of the task execution.
clip_image022
Modify the above code to as below:
          var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(clientcontacts.Result);
            var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject(clientTemperature.Result);
            var location = Newtonsoft.Json.JsonConvert.DeserializeObject(clientLocation.Result);

Now we are done with the code changes for consuming the API asynchronously using the ASP.NET 4.5 feature. Now let us run the program again.
clip_image024
Figure 10: Details page

Now you can find that the total time taken is 1 second for all the requests as all the requests have been executed in asynchronous manner and the time taken is less compared to the synchronous way of consuming the Web API.

Here is the total code for the client application:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="ClientApplication.Details" Async="true" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Contacts:<br />
    <asp:ListView ID ="listContacts" runat="server">
     <LayoutTemplate>
    <table runat="server" id="table1" >
      <tr runat="server" id="itemPlaceholder" ></tr>
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr id="Tr1" runat="server">
      <td id="Td1" runat="server">
        <%-- Data-bound content. --%>
        <asp:Label ID="NameLabel" runat="server" 
          Text='<%#Eval("Name") %>' />
      </td>
    </tr>
  </ItemTemplate>
 
    </asp:ListView><br />
     Temperature:<br />
        <asp:Label ID ="lbltemperature" runat="server"></asp:Label><br />
        Location:<br />
        <asp:Label ID="lblLocation" runat="server"></asp:Label><br />
        Elapsed Time:<br />
         <asp:Label ID="lblElapsed" runat="server"></asp:Label><br />
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
 
namespace ClientApplication
{
    public class Contact
    {
        public string Name { get; set; }
        public string ContactNumber { get; set; }
    }
    public partial  class Details : System.Web.UI.Page
    {
       
        protected async void Page_Load(object sender, EventArgs e)
        {
 
            string time = DateTime.Now.ToString();
 
            var clientcontacts = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Contacts");
            var clientTemperature = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Temperature");
            var clientLocation = new WebClient().DownloadStringTaskAsync("http://localhost:8687/api/Location");
 
            await Task.WhenAll(clientcontacts, clientTemperature, clientLocation);
 
            time = time + DateTime.Now.ToString();
           
 
            var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(clientcontacts.Result);
            var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject(clientTemperature.Result);
            var location = Newtonsoft.Json.JsonConvert.DeserializeObject(clientLocation.Result);
 
            listContacts.DataSource = contacts;
            listContacts.DataBind();
 
            lblLocation.Text = location.ToString();
            lbltemperature.Text = temperature.ToString();
            lblElapsed.Text = time;
           }
    }
}
 
Hope you liked this article!!!

No comments:

Post a Comment