Wednesday, 28 November 2012

Creating Chess Board Layout Using Pixel Manipulation in HTML5 Canvas

The canvas element in HTML5 can be used to render any graphical content. Shapes, paths, text and even images can be drawn on canvas. Canvas doesn’t support animations, but animations can be created by writing some additional JavaScript code.

Using the pixel manipulation feature of canvas, we can draw images or change colours of existing images. To manipulate pixels, we have to follow the following steps:
  • Create an image data object to draw on the canvas context
  • Loop through each pixel in the area to be drawn
  • Set RGBA values to current position inside the loop
  • Put the image on the canvas context

To draw something specific, we have to logically divide the area to be drawn and manipulate carefully. With this understanding, let’s start drawing a chess board layout.

Create a new HTML page and add a canvas element to the body.

<!DOCTYPE html>
<html xmlns="">
    <title>Chess board layout using HTML5 Canvas</title>
    <canvas id="chessLayoutCanvas" width="320" height="320" >
        Sorry, your browser doesn't support Canvas!

This is the entire HTML needed for this demo. To draw image on it, we have to write some JavaScript code. Following operations have to be performed inside the JavaScript code:
  • Obtain JavaScript object of the canvas element
  • Get the canvas context
  • Follow steps to draw image

Canvas element will be ready to operate once the entire page is loaded. So, above operations have to be performed once the page is loaded. Following script gets the canvas object and object of the 2-dimensional context:

var canvas = document.getElementById('chessLayoutCanvas');
if(!canvas || !canvas.getContext)
var context = canvas.getContext('2d');
if(!context || !context.putImageData)

To draw on the canvas, we have to get an image data object. Canvas context has a function createImageData that returns the object we need, but it is not supported on all browsers. Following snippet shows different ways of obtaining an object using which we can draw some colors on the canvas:
var chessLayoutImage, width, height;
width = canvas.width;
height = canvas.height;
if (context.createImageData) {
    chessLayoutImage = context.createImageData(width, height);
else if (context.getImageData) {
    chessLayoutImage = context.getImageData(0, 0, width, height);
else {
    chessLayoutImage = { 'width': width, 'height': height, 'data': new Array(width * height * 4) };

Now that we have the object using which we can achieve what we have to do, let’s think about the logic to draw a chess board layout.

As we all know, a chess board has alternate arrangement of white and black colors. On observing a bit, we can say that the color of last cell on a row is repeated on first cell of next row. Keeping this point in mind and calculating pixels on which we have to draw, I came up with the following logic:
var pixels =;
var isBlack=true;
for(pixelPosition = 0; pixelCount = pixels.length, pixelPosition < pixelCount ; pixelPosition+=4){
    if(pixelPosition%160==0 && !(pixelPosition%(40*4*320)==0)){
        isBlack= !isBlack;

If you observer the above code, I am drawing the black color alone. Place to be filled with white is left as by default the background is white.

After drawing the layout, a black border is drawn around the canvas to show the boundaries of the area.

Happy coding!

Saturday, 17 November 2012

Unit Testing Asynchronous methods using MSTest and XUnit

As we saw in previous posts, writing asynchronous code has become quite easy with .NET framework 4.5. To be able to write well and bug less code in any framework or language, unit tests play a vital role. Unit testing asynchronous code is a bit tricky and it is currently not supported by all unit test frameworks. In this post, we will see how to unit test an asynchronous method using MSTest and the XUnit framework.

Irrespective of the unit testing framework used, the test method written to test the asynchronous method has to follow a set of rules.
  • Test method should be marked as async
  • await keyword should be used while calling the method to be tested
  • Return type of the test method should be Task

I will be using the following asynchronous method for unit testing. It is a very simple method (I have used it in my post on Asynchronizing a C# method using async and await), that divides two numbers with a delay of 2 seconds.
public class ArithemticOperations
    public async Task<double> DivideAsync(int first, int second)
        await Task.Delay(2000);
        return (double)second / first;

Unit testing using MSTest

MSTest is the testing framework built into Visual studio. If you are familiar with it, then testing asynchronous method doesn’t require much learning. If you are not already familiar with MSTest, you may go through Unit Testing Framework portion on MSDN.

Testing an asynchronous method is much similar to testing a synchronous method. We just need to follow the rules mentioned above. Following is a test class that tests the divide method created above.
public class AsyncMethodUnitTests
    public async Task DivideAsync_Returns_RightResult()
        int first = 10, second = 20;
        double expected = 2.0;
        ArithemticOperations operations = new ArithemticOperations();
        double actual = await operations.DivideAsync(first, second);
        Assert.AreEqual(actual, expected);

Unit testing using XUnit

XUnit is created by James Newkirk and Brad Wilson. It is built to support Test Driven Development with a design goal of simplicity. You may visit the Codeplex site of XUnit to learn more about it.

Testing asynchronous code using XUnit is very straight forward. Following is a test class that tests the divide method:
public class AsyncTests
    public async Task AsyncDivide_Returns_RightResult()
        int first = 10, second = 20;
        double expected = 2;
        ArithemticOperations operations = new ArithemticOperations();
        double actual = await operations.DivideAsync(first, second);
        Assert.Equal(actual, expected);

Along with making your code run better by applying asynchronous strategies, you can unit test and even test drive them.

Happy coding!

Asynchronous controller actions in ASP.NET MVC 4

In this post, let’s continue our discussion on asynchronous programming in .NET 4.5 with ASP.NET MVC4. We will see how to create asynchronous controller actions in ASP.NET MVC 4.

 As in case of pages and handlers ASP.NET web forms, it was not easy to create asynchronous controller actions in ASP.NET MVC till MVC 3. We had to derive the controller class from AsyncController and create async and completed methods for the controller action that performs asynchronous task. This is quite a bit of work to perform.

As ASP.NET MVC 4 runs on top of .NET framework 4.5, we can use the magical async and await keywords to simplify this process. Using these keywords, we can easily create asynchronous controller actions just like we created methods in earlier posts. Following is a sample implementation of a controller action method:

public class HomeController : Controller
    public async Task<ActionResult> Index()
        DataServiceClient client = new DataServiceClient();
        var cities = await client.GetCitiesAsync();
        return View(cities);

 In the above code, we are calling a WCF service asynchronously. As a method marked as async must return a Task, the return type is modified to Task<ActionResult>.

Happy coding!

Wednesday, 14 November 2012

Asynchronous HttpHandlers in ASP.NET 4.5

HttpHandlers are responsible to handle all types of HTTP requests that an ASP.NET web server receives. Page is also an HttpHandler, as it is derived from IHttpHandler interface.

Need of creating an HttpHandler may arise when we want to have more control over the way a request is handled. There can be scenarios where we have to generate some content dynamically like a captcha image to show on a page or generate some file that the user will download. In such cases, HttpHandler is the choice we stop at.

The HttpHandler may perform operations like fetching data from a remote location (like service calls, heavy DB queries) and some I/O operations on the disc. As sever would take considerable amount of time to complete such requests, it is better to perform them asynchronously.

To create an asynchronous HttpHandler in older versions of ASP.NET, the handler class has to be derived from IHttpAsyncHandler and implement its members. In ASP.NET 4.5, this process is simplified with the abstract class HttpTaskAsyncHandler. It has an abstract method ProcessRequestAsync, returning a Task. We can use the magical async and await keywords inside this method.

Following is a sample implementation an HttpHandler derived from HttpTaskAsyncHandler:

public class AsyncHandler : HttpTaskAsyncHandler
    public override async Task ProcessRequestAsync(HttpContext context)
        //Calling a service to fetch data
        var client = new DataServiceClient();
        var getCitiesTask = client.GetCitiesAsync();

        //Setting folder path and file name
        string folderPath = context.Server.MapPath("Downloadables");
        string fileName = "cities.xlsx";

        //Asynchronously calling a method to store data obtained from service in an excel file
        await Task.Factory.StartNew(() => FillDataIntoExcel(getCitiesTask.Result, folderPath, fileName));

        //Sending the excel file to user's system
        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.WriteFile(folderPath + "\\" + fileName);

You can download the complete source code of the handler here: Download Source. The sample application also contains implementation of an asynchronous web form.

Happy coding!

Sunday, 11 November 2012

Asynchronous pages in ASP.NET 4.5

In my previous post, we discussed the importance of asynchrony in ASP.NET applications. Before that, I blogged about using asynchrony in C# 5 and calling WCF services asynchronously using features in C# 5. In this post, we will learn how to create an ASP.NET web forms page that performs some asynchronous operations.

To make a page asynchronous in earlier versions of ASP.NET, the page has to implement the interface IHttpAsyncHandler and define concrete definitions to all the methods declared in the interface. This takes considerable amount of time and effort to make the page asynchronous.

In ASP.NET 4.5, we can turn the execution of any operation asynchronous by using async and await keywords. Any new page added to an ASP.NET application is considered synchronous by default. We can change this by setting value of Async property of the Page directive to true. Once this property is set, we can use async and await keywords in any method in the code behind file.

<%@ Page Language="C#" AutoEventWireup="true" Async="true" CodeBehind="Default.aspx.cs" Inherits="Async.Default" %>

This is because, performing asynchronous operations at wrong time may lead to some dangerous conditions on the server. By setting the Async attribute of the page, we are telling the server that, the current page is a safe place to perform async operations. Following is a sample page load event handler that calls a WCF service asynchronously and binds data to a GridView:
protected async void Page_Load(object sender, EventArgs e)
    var client = new DataServiceClient();
    var gettingCities = await client.GetCitiesAsync();
    gvCities.DataSource = gettingCities;

Following are the set of steps performed when ASP.NET detects the await keyword in the above event handler:
  • Continues executing other synchronous tasks of the life cycle event
  • Once the above step is finished, the underlying synchronization context fires up an event saying that an async operation is pending
  • ASP.NET waits asynchronously till the pending task is completed and then it continues executing the rest of the statements
  • With above step, the life cycle (page load in this case) event is over. The control goes ahead to the next life cycle event

There is another way to achieve this. It is shown in the following snippet:
protected void Page_Load(object sender, EventArgs e)
    RegisterAsyncTask(new PageAsyncTask(async () =>
        var client = new DataServiceClient();
        var gettingCities = await client.GetCitiesAsync();
        gvCities.DataSource = gettingCities;

The advantage of performing async operation this way over what we did earlier is that, it registers an asynchronous handler with the page and now the execution is not dependent on the synchronization context. Execution of the statements in the PageAsyncTask passed in is not dependent on page the page life cycle event. So, ASP.NET will not wait asynchronously after executing rest of the logic in the life cycle event. It would rather continue execution with the next life cycle event handlers. Statements in the registered task are performed whenever the dependent operation is finished.

Note that, we used the async keyword with a lambda expression. It is legal in .NET 4.5, because lambda is meant to create a single cast delegate with an anonymous method. To make the method executable asynchronously, we can use async and await with lambda.

Further learning: Async in ASP.NET talk from AspConf 2012

Happy coding!

Saturday, 3 November 2012

Need of Asynchrony in ASP.NET

If you are following this blog, you might have observed that I am currently exploring asynchronous programming. Being web developers, it is important for us to understand how asynchrony will help the web applications we develop.

Let’s take an example

Say, we have a banking web application where the user wants to get the details of all the transactions he made during last two months in the form of an excel sheet. If the user would have performed some hundreds of operations during this period, the server operation will take considerable amount of time as it has to perform the following operations:
  • Fetch details of all transactions into memory
  • Create an excel file with appropriate columns
  • Write data into the excel file
  • Send it to the user across the network

Please note that this set of operations is performed in response to a single request. Technically, we can say that these four operations include the following set of heavy tasks:
  • Querying database to fetch details of hundreds of transactions
  • Creating a file on the disk
  • Writing data from an object into file
  • Sending file to the user’s system

As it is a banking application which is usually accessed by a large number of viewers, it is very important to serve them quickly. If there are hundreds of such requests, the server may respond very slowly to most of the users.

How does the server respond to a request?

In a typical ASP.NET web application, the server performs the following tasks when it gets a request:
  • Picks up a thread from CLR managed thread pool on and assigns the new request to it
  • The assigned thread performs all the tasks one by one. It works for the same request till all tasks of the request are completed
  • The thread is returned to thread pool as soon as it finishes the assigned tasks

So, the request is processed in a single-threaded model. If any task of the thread is halted for an I/O operation or a network call or any such request to complete, the corresponding thread is remains idle till the task gets required input. Waiting time of thread may be some milliseconds. Imagine a case when all threads are engaged and some of them are waiting because of heavy operations. If a new request hits the server now, it will have to wait until a thread is freed to process its request.

How can it be improved?

Performance of the web application described above will improve if the thread attached to a waiting request is used process some other request. Once the request receives response from the operation it was waiting for, processing of the request is resumed with help of a free thread from the CLR thread pool.

This can be achieved using asynchronous programming on the server side. We can use the asynchronous language features of C# or VB.NET to enhance such applications. You might have questions in your mind about the implementation of asynchrony in ASP.NET. We will discuss about them in subsequent posts.

Happy coding!