Tuesday, 30 October 2012

Calling WCF Services asynchronously using async and await

In my previous post, I covered how to use async and await keywords in C# 5 to create asynchronous methods. This post is a continuation of asynchronous programming, in which I will cover how to call WCF services from a client program using async and await.

Response of an application will be slower when it includes heavy weight operations like running complex queries against database, reading a piece of data from a file, calling a service to get some data or any remote operation. When such operations are performed synchronously, the application will be halted till the operation gets over. If we assign the slower operation to a separate task, the thread will be free to perform some other operation till the operation responds.

When a WCF service is called synchronously, the thread associated with the operation is idle till the response is obtained from the server. To avoid this in earlier versions of .NET framework (4.0 or earlier), we had an option to create asynchronous methods with an associated event. Using .NET 4.5, we can create task-based proxies while adding service reference to an application. This can be done using by clicking on the Advanced button in the Add Service Reference dialog.


Add Service Reference

On the Service Reference Settings dialog, check Allow Generation of asynchronous operations and Generate task-based operations.




Please note that this feature is available in .NET framework 4.5 onwards. i. e., to be able to generate task-based asynchronous proxies, target version of the project to which we are adding the service reference should be 4.5 or above.

For example, say a WCF service contains GetAllEmployees method, which returns a collection of Employees. Following snippet shows signature of the method:
List<Employee> GetAllEmployees();

If reference of this service is added to a client application written .NET 4.5 with task-based operations enabled, then you will be able to find the following two proxies in the generated Reference.cs file for the above method:
Public EmployeeServiceReference.Employee[] GetAllEmployees() {
    return base.Channel.GetAllEmployees();
}
        
public System.Threading.Tasks.Task<EmployeeServiceReference.Employee[]> GetAllEmployeesAsync() {
    return base.Channel.GetAllEmployeesAsync();
}

First proxy is the synchronous proxy and second one is the task-based proxy. We can call the WCF service asynchronously using the second proxy.

As we discussed in the previous post, any method that returns a Task can be called using await. In a client application, the method GetAllEmployeeAsync can be called using await keyword. Following is a sample method calling the service asynchronously:
async void LoadDataFromService()
{
    EmployeeServiceClient client = new EmployeeServiceClient();
    var getEmployeesTask = client.GetAllEmployeesAsync();
    Employees = await getEmployeesTask;
}

Happy coding!

Sunday, 28 October 2012

Asynchronizing a C# method using async and await

In the business applications that we build as part of our job consist of several heavy weight operations like file manipulations, dynamically creating images, generating an excel file from a result set and the list goes on.

In such scenarios, we cannot let our application to halt till the requested operation is completed, as the operation takes a lot of time. What we can do is, assign the heavier operation to a separate task and do something that is independent of result of the operation till the operation is completed.

I have a simple console application that consists of methods performing add and divide arithmetic operations. Sleep method is called in the Divide method to make the execution slow. Code of the console application is shown below:
static void Main(string[] args)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
            
    int first = 5;
    int second = 10;

    Console.WriteLine(Add(first, second));
    Console.WriteLine(Divide(second, first));
    Console.WriteLine(Divide(second, first));

    watch.Stop();
    Console.WriteLine("Time taken: {0}",watch.ElapsedMilliseconds);
}

static int Add(int first, int second)
{
    return first + second;
}

static double Divide(int second, int first)
{
    System.Threading.Thread.Sleep(2000);
    return (double)second / first;
}

If you run the application, the value of watch.EllapsedMilliseconds would be around four seconds. This is because, we are calling the Divide method twice synchronously. The thread executing the application waits until the first method call is completed and the result is returned before proceeding to the second call.

We can reduce the time taken by this application using Task Parallel Library (TPL). We can create a Task for each of the slower operation and continue with other operations without waiting for the Tasks to finish. Following snippet shows how to create a Task and get the result once the task is finished.

var taskName = Task.Factory.StartNew<returntype>(() => MethodToCall(arguments));
//Perform other independent operations here
...
...
...
returntype variable = taskName.Result;

Let’s use this feature in the demo application. Create two tasks, one for each division call and use the result to print it on the screen. Replace the statements displaying results on the console with the following statements:
var divisionTask = Task.Factory.StartNew<double>(() => Divide(second, first));
var secondDivisionTask = Task.Factory.StartNew<double>(() => Divide(second, first));
Console.WriteLine(divisionTask.Result);
Console.WriteLine(secondDivisionTask.Result);
Run the application. Time taken now is around two seconds. So, the difference in time taken is significant. We may say that both the division tasks finish almost at the same time.

Though this approach reduced the time taken, it demands the programmer to create tasks manually and manage them. It might become quite difficult for us to manage an application that involves creating a large number of tasks. To avoid this problem, the C# language designers have added the async and await keywords. These keywords can be used in an application built using Visual Studio 2012 and targeted to .NET Framework 4.5.

A method performing a heavier or slower operation should be marked as async and the statement in that method that takes a lot of time to finish should be marked as await. The await keyword indicates that a slow operation is going to start. Once the currently running thread finds a statement marked with await, it goes to perform some other operation without waiting for the statement to complete. The await can be applied with a Task. For example, if a method call has to be marked as await, the method should return a Task.

Return type of an async method can be either void or Task. The C# compiler generates a bunch of code when an async method is compiled. It in turn uses the Task Parallel Library.

Following is the modified Main method and the Divide method using the async and await keywords:
static void Main(string[] args)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();

    int first = 5;
    int second = 10;
            
    Console.WriteLine(Add(first, second));
    var divisionTaskAsync = DivideAsync(second, first);
    var secondDivisionTaskAsync = DivideAsync(second, first);
    Console.WriteLine(divisionTaskAsync.Result);
    Console.WriteLine(secondDivisionTaskAsync.Result);
            
    watch.Stop();
    Console.WriteLine("Time taken: {0}", watch.ElapsedMilliseconds);
}

static async Task<double> DivideAsync(int second, int first)
{
    await Task.Delay(2000);
    return (double)second / first;
}

Call to Thread.Sleep is replaced with Task.Delay as the later returns a Task. I renamed the Divide method to DivideAsync just to follow the convention that is already used by the framework methods. Otherwise, it doesn’t make any difference.

Happy coding!

Saturday, 20 October 2012

How ASP.NET 4.5 Model Binding and IQueryable work behind the scenes

Model Binding is a nice new feature added to ASP.NET 4.5. Using this feature, we can bind data to controls in a type-safe way. This means, the properties of the data are known at the compile time.

If a method returning IQueryable type of collection is bound to a GridView, paging and sorting can be enabled by applying some simple configurations. There is no need of writing any extra amount of code to handle paging or sorting.

But, the question here is, how does that work? Is it a magic? The answer is very simple: dynamic nature of IQueryable. IQueryable operators can be invoked dynamically.

Following is signature the Where operator of IQueryable:
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
Second parameter of the operator is of Expression<Func> type. The difference between a Func and an Expression is Func is a delegate whereas Expression is a data structure. This means, the contents of an Expression can be parsed and inspected. This also means that, if we have every piece of information that an Expression needs, we can build it dynamically. Have a look at the inputs that the other IQueryable operators take, they all accept Expression types.

For instance, say following is the GridView used on an ASP.NET web form:
<asp:GridView runat="server" AutoGenerateColumns="false" ID="gvCustomers" 
        ItemType="WhatsNewInAspNet45.DataAccess.Customer" DataKeyNames="CustomerID" SelectMethod="GetCustomers" AllowPaging="true" PageSize="10"         AllowSorting="true">
        <Columns>
            <asp:TemplateField HeaderText="Company Name" SortExpression="CompanyName">
                <ItemTemplate>
                    <%#: Item.CompanyName %>
                </ItemTemplate>
            </asp:TemplateField>
      ...
      ...
</asp:GridView>
Following is a simple implementation of the GetCustomers method:
public IQueryable<Customer> GetCustomers()
{
    return _Context.Customers;
}
When the page containing this GridView is viewed on a browser, the user interacting with the page can sort the data based on data in a column and also can navigate through different pages of the GridView. When we click on a column of the GridView to sort the data, SortExpression of the column will be picked up and it will be used in the OrderBy operator of IQueryable to fetch data. As GetCustomers returns IQueryable type of data, we may say that, result of the following statement is used to bind data to the GridView:
GetCustomers().OrderBy(c=>c.CompanyName);

Digging a bit more, we may say that, the following LINQ query is evaluated:
_Context.Customers.OrderBy(c=>c.CompanyName);

If the SelectMethod GetCustomers uses Entity Framework or LinqToSQL, the SQL query that will be formed to hit the database because of the above LINQ query would contain an order by clause. Otherwise, if the data is fetched from a WCF Data Service, the URL formed to invoke the service would contain an order by expression.

Reason behind this behaviour is deferred execution of LINQ queries. They get executed when they are needed. We require data before it is bound to a user interface control. Till then, the query will not be parsed.

Similarly, if we navigate to any page on the GridView, Skip and Take operators are applied on the result of select method to fetch the data that should appear on the target page. If SelectMethod returns any other type of data (i.e., other than IQueryable), we need to write logic for fetching appropriate data and returning it to the target control.

Happy coding!

Tuesday, 16 October 2012

Basics: Understanding Lambda Expression

If you are following my blog, I have been writing posts on latest technologies, concepts and some of the issues that I faced with their solutions. I decided to put some posts on basic some concepts intermittently. This is the first post of the never-ending basics series.

I often hear from people that lambda expression does a magic behind the scenes which is hard to understand. I agree that it works magically, but the magic is not hard to understand. When I saw lambda expression for the first time, one of my friends told me that it is a delegate. Then I tried to understand how it is a delegate and how does it work behind the scenes.

With my understanding of creating delegates with anonymous methods, I thought that when we write a lambda expression, we are defining an anonymous method and assigning it to a delegate object without using .NET’s delegate keyword.

Keeping the above point in mind, I started writing a small Console Application to move from a delegate with a named method attached to it to lambda expression. I wrote a method that checks if a number is positive and returns a Boolean value and declared a delegate to hold methods of similar signature:
delegate bool PositiveTest(int number);
bool CheckIfPositive(int number)
{
    return number > 0;
}

Step 1: Instantiating and invoking the delegate using a defined method:
PositiveTest testDelegate = new PositiveTest(CheckIfPositive);

Step 2: Instantiating delegate using anonymous method and the delegate keyword:
PositiveTest testAnonymousDelegate = delegate(int number)
{
    return number > 0;
};

Step 3: Removing the delegate keyword and introducing =>:
PositiveTest delegateWithoutDelegateKeyword = (int number) =>
{
    return number > 0;
};

Step 4: Removing data type of the input parameter:
PositiveTest delegateWithDataTypeRemoved = number =>
{
    return number > 0;
};

Step 5: Removing curly braces and the return keyword:
PositiveTest delegateWithNoBracedNReturn = number => number > 0;

In the above listing, the amount of code written to instantiate a single cast delegate is gradually reduced. We moved from delegate accepting a defined method to delegate accepting an expression that doesn’t have types or curly braces. I hope, now you feel comfortable with lambda expression if you had any confusion earlier.

Happy coding!

Wednesday, 10 October 2012

Creating TypeScript type declaration file for an existing jQuery plugin

Microsoft recently announced a scripting language that compiles into JavaScript. It is known as TypeScript.
TypeScript is super set of JavaScript. Using TypeScript, one can write type safe client side script. If you are not familiar with TypeScript yet, you may checkout the following resources:


Any existing JavaScript library can be used with TypeScript if a type declaration file is created for the library. A type declaration file provides a TypeScript interface to interact with the library. TypeScript team has created the declaration files for jQuery and Node.js libraries.

In this post, we will create a TypeScript declaration file for jQuery-idle Timeout plugin. It is a small plugin which signs off the user if the user didn’t interact with the page for some time. Using this plugin is very easy. Following is an example of the usage:
$(document).idleTimeout({
    inactivity: 5000,
    noconfirm: 1000,
    sessionAlive: 1000,
    redirect_url: 'TimedOut.html',
    click_reset: true,
    alive_url: 'default.htm',
    showDialog: false
});

The above script sets redirects user to the page TimedOut.html if the user didn’t interact with the page for 5 seconds or more.
From the usage of the plugin, it is clearly visible that,

  • The function idleTimeout is invoked using jQuery object
  • The function idleTimeout accepts a set of options
In the source of jQuery-idleTimeout plugin, we see the following assignment statement in the beginning:
var defaults = {
            inactivity: 1200000, //20 Minutes
            noconfirm: 10000, //10 Seconds
            sessionAlive: 30000, //10 Minutes
            redirect_url: '/js_sandbox/',
            click_reset: true,
            alive_url: '/js_sandbox/',
            logout_url: '/js_sandbox/',
            showDialog: true
        }

From here, we get to know the list of configurable options. As TypeScript is strongly typed, we need to define an interface to hold the above properties. One important thing to remember here is that, the fields should be made nullable in the interface.  

The interface can be as follows:
interface JQIdleTimeoutSettings {
    inactivity?: number;
    noconfirm?: number;
    sessionAlive?: number;
    redirect_url?: string;
    click_reset?: bool;
    alive_url?: string;
    logout_url?: string;
    showDialog?: bool;
    }


The function idleTimeout is invoked using a jQuery object. In the declaration file of jQuery, an interface is defined to hold all functions which have to be invoked using jQuery objects. Name of the interface is JQuery.

We shouldn’t modify the source of jQuery’s declaration file to add the idleTimeout function. Instead, we have to define an interface extending JQuery as follows:
interface JQueryTimeout extends JQuery {
    idleTimeout(settings: JQIdleTimeoutSettings): JQueryTimeout;
}

I made the declaration file open on GitHub. You can find it here.

Using the declaration file:
To use the declaration file in a TypeScript file, a reference of the declaration file should be added. Calling the idleTimeout function in TypeScript is quite similar to that of in JavaScript code. Only difference being, we need to type cast the jQuery object to type of JQueryTimeout.
/// <reference path="jQueryIdleTimeout.d.ts" />

(<JQueryTimeout>$(document)).idleTimeout({
                inactivity: 5000,
                noconfirm: 1000,
                sessionAlive: 1000,
                redirect_url: 'TimedOut.html',
                click_reset: true,
                alive_url: 'default.htm',
                showDialog: false
});
This is because, in TypeScript, $(document) returns an object of type JQuery. The function idleTimeout is declared in the interface JQueryTimeout, which is extended from the interface JQuery.

Happy coding!

Saturday, 6 October 2012

Binding JSON data to a web page using Knockout JS

Knockout JS provides a nice way to bind data on HTML pages using JavaScript. It also helps in keeping the JavaScript code clean and separated. If you are not familiar with this library, check out the official site of Knockout JS.

In real time applications, there can be a number of scenarios in which data is obtained from a service using AJAX and the data obtained has to be displayed or updated on the page. Knockout’s observables cannot be applied directly on JSON data. The data needs some tweaks before applying it on the page.

For example, let’s assume the following JSON object is returned from the service:
var person = {
    "id": 10,
    "name": "Ravi",
    "designation": "Software Engineer"
};

To bind this data on the page using Knockout JS, a ViewModel object has to be defined with the properties that have to be made observable. Following is the ViewModel for the person class shown above:
var personVM = function () {
    var self = this;
    self.id = ko.observable();
    self.name = ko.observable();
    self.designation = ko.observable();
}

Data in the JSON object has to be mapped into a ViewModel object. The ViewModel object can be used to bind data on the page.
$(function () {
    var personVMObject = new personVM();
    personVMObject.id(person.id)
                  .name(person.name)
                  .designation(person.designation);
    ko.applyBindings(personVMObject);
});

The sample code is available on JSFiddle.

Tuesday, 2 October 2012

Injecting dependencies into SignalR hub using Unity

In one of my earlier post, I discussed on Dependency Injection with SignalR using Ninject. In this post, we will see how to do it with Unity.

We had a NuGet package available to make our work easier to work with Ninject. We don’t have such a package for Unity. The only difference is that, we need to write one more small class to make the things work.

We need to define a dependency resolver that derives from SignalR.DefaultDependencyProvider and override the methods GetService and GetServices. This implementation is shown below:

public class UnityDependencyResolver : DefaultDependencyResolver
{
        IUnityContainer container;
 
        public UnityDependencyResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container", "Containet cannot be null");
            }
            this.container = container;
        }
 
        public override object GetService(Type serviceType)
        {
            return base.GetService(serviceType) ?? container.Resolve(serviceType);
        }
 
        public override IEnumerable<object> GetServices(Type serviceType)
        {
            return base.GetServices(serviceType) ?? container.ResolveAll(serviceType);
        }
}

We have to register the requested types and target types to the container as shown below:
public static class UnityIoC
{
    public static IUnityContainer Initialize()
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<ICustomerRepository, CustomerRepository>();
        container.RegisterType<IJavaScriptMinifier, NullJavaScriptMinifier>();
        return container;
    }
}

In this case, I registered the target type for IJavaScriptMinifier as Unity fails to work without this registration. Ninject and StructureMap don’t need this type to be registered. As last step, we need to set the resolver to RouteTable.Route.MapHubs when the application starts.
public class Global : System.Web.HttpApplication
{ 
    void Application_Start(object sender, EventArgs e)
    {
        GlobalHost.DependencyResolver = new UnityDependencyResolver(UnityIoC.Initialize());
        RouteTable.Routes.MapHubs();            
    }
}

Important note: If you are using SignalR in an ASP.NET MVC project, then configure SignalR first and then ASP.NET MVC. Check SignalR wiki for more details.

Happy Coding!