Exploring ASP.NET FriendlyURLs – Guest Post on South Asia TechNet Blog

Recently, I write a post on ASP.NET new feature FriendlyURLs on South Asia Technet Blog.

Being an ASP.NET developer, you must have worked on ASP.NET Web Forms and ASP.NET MVC. One of the things in MVC, most of us like that is pretty and elegant URL. But this is not in the case of using ASP.NET web forms.

 These URLs include crappy extensions like aspx. Many developers have written their custom URL writer or used some third party libraries to achieve it. And here we either end up paying some extra bucks for the third party library or writing custom URL writer which is itself painful task.. Read more

 

Writing Asynchronous Web Pages with ASP.NET- Part 3

This is third post in the series of Writing Asynchronous Web Pages with ASP.NET. In first post, We discussed briefly about various asynchronous patterns and wrote an asynchronous web Page using APM model. In second part, we used Event-based asynchronous pattern (EAP) and discussed it with a example. Please find the links of my earlier post below.

  1. Writing Asynchronous Web Pages with ASP.NET- Part 1
  2. Writing Asynchronous Web Pages with ASP.NET- Part 2

 

In this post, we are going to use another pattern. .NET 4.0 introduced Task Parallel Library (TPL), which simplified the way to write asynchronous code. Let’s briefly understand the TPL. It provides a method (as naming convention method name ends with async) which returns a Task (or Task<TResult>) .

Task represents an asynchronous operation which contains the Result once completes. After getting the task, we can do some other activity and can keep checking the status of the Task. Once it completes, read the result from the Task.

We can provide an asynchronous method in our class that provides an async method that returns a task as

public class MyCustomClass
{
    public Task<int> ReadAsync(byte[] buffer, int offeset, int count);
}

Task actually internally uses Thread Pool and a thread is allocated to the task using thread pool to complete the task but all this complexity is hidden from the user and .NET itself lays down the required infrastructure for this.

Now, scores of classes in .NET libraries supports this pattern and we can make use of that.

.NET4.5 made our life much easier by introducing to keywords async and await which allows us to write the asynchronous code in a synchronous way. All the other required basic activities like context switching etc are taken care by the .NET framework for us. These keywords are provided over Task Parallel Library  that got introduced in .NET 4.0. Writing asynchronous activities with these keywords are highly optimized, performance oriented and make best use of TPL.

Now let’s use this pattern and write another asynchronous page. So in this examples, I am using a WCF service that returns a list of Employees and that is getting displayed on the web page. So our Page_Load method could look like

protected async void Page_Load(object sender, EventArgs e)
{
    WcfService.Service1Client client = new Service1Client();

    var customers = await client.GetEmployeesAsync();
    gdCustomers.DataSource = customers;
    gdCustomers.DataBind();
}

So as we see here that my service supports the TPL, async and await keywords based asynchronous pattern.

In page life cycle, when Page_load gets fired, ASP.NET finds it async and when it reaches to await, it releases the current thread and a new thread is picked from the thread pool to continue the activity and the call the web service took place asynchronously. Once the data returns from service, the same UI thread is assigned to execute further.
But there is better way to use async and await in web page. This has an issue as well and execute the code in synchronous mode . As we know our page life cycle has a set of events that gets fired in a predefined order and next event will be fired only when the last event completes. So if we use the above way of async Page_Load, this event will be fired during page life cycle event once it reaches to async, current thread gets free and a another thread got assigned to complete the task asynchronously, but the ASP.NET cannot execute the next event in life cycle because Page_Load has not been completed yet. And underlying synchronization context waits till the asynchronous activity completes. Then only the next event of page lifecycle will be fired which makes the whole process in synchronous mode only.

So to avoid it, there is a better is available. So the new way uses ASP.NET method RegisterAsyncTask which takes PageAsyncTask as a parameter. So let’s write the code then we’ll discuss that How does it work?

protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(async () =>
            {
                using (Service1Client client = new Service1Client())
                {

                    var customers = await client.GetEmployeesAsync();
                    gdCustomers.DataSource = customers;
                    gdCustomers.DataBind();
                }
            }));
        }

Here, we have register a delegate using method RegisterAsyncTask at Page_Load. It does not fire the event while running the Page_Load event. Here it just register an event and tell the ASP.NET to execute it. Now as we have already marked page as async, ASP.NET itself decides the best time to execute it asynchronously and Page Life cycle events gets fired as usual without waiting for the async task to complete. This is very useful in the scenarios where we want to run multiple asynchronous tasks. Multiple tasks can run parallel if required. So now we have given the liberty to ASP.NET to execute this task asynchronously rather than waiting for the async task to get it completed then fire the next page life cycle events.

Hope you have enjoyed the post.

Cheers,
Brij

Writing Asynchronous Web Pages with ASP.NET- Part 2

This is the second part in the series of Writing Asynchronous web pages in ASP.NET. In my last post, we discussed about various programming model for writing asynchronous code and wrote a asynchronous page using Asynchronous Programming model(APM). The link of part-1 of the series is given below

Writing Asynchronous Web Pages with ASP.NET- Part 1

In this post we’ll use another approach that is Event-based asynchronous pattern(EAP).

What is Event-based asynchronous Pattern (EAP)?

This model provides another way to write asynchronous code. In this pattern, it provides one void method (as a naming convention method name ends with async) and one or more events to notify the caller that there is a change in status. It means we don’t need to keep checking the status of the task, an event will be raised once the task will be completed. This asynchronous task runs in the background and simplest one, uses BackgroundWorker class to implement.

Any class that provides the capability to call its method asynchronously (using EAP model), provides a method that ends with async (naming convention) and an event that notifies when the task completes. It can provide more events to provide the status of the thread. We should follow these rules in our class if we want to write our own custom asynchronous methods that uses EAP Model.

So let’s create a class that uses this pattern

public class MyCustomClass
{
    public void ReadCharCountAsync(byte[] buffee, int offset, int count);
    public event ReadCompletedEventHandler ReadCompleted;
}

public delegate void ReadCompletedEventHandler(object sender, ReadCompletedEventArgs readCompletedEventArgs);

public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{
    public int Result { get; }
}

We can see here that my class has one async method and one event handler. Then we defined the event handler and event arguments which contains the result of the method.

In this post, I’ll be using a .NET class WebClient that provides a method that can consumed asynchronously using EAP model. In this example, I am just downloading a page from the given URL and showing it on the screen. There could be many other scenarios.

I have created a webpage and put Async=”true” in the page directive in aspx file. This tells the page that this will be executed asynchronously. So let’s see the code behind

public partial class AsyncEAP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            WebClient client = new WebClient();
            Uri uri = new Uri("http://www.google.com/");

            // Specify that the DownloadStringCallback method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
            client.DownloadStringAsync(uri);
        }

        void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                renderedItem.InnerHtml = e.Result;
            }
        }
    }

So if we see the above code then we see that in Page_Load method after creating the instance of WebClient, I have subscribed the completed event and then called the DownloadStringAsync method. DownloadStringCallback method gets called once the download completes. Here I just checked if there is an error while executing and if there is no error then accessed the result. Here there is no way to find the status of the task but sure that once the method completes its processing, the completed event handler will be fired.

There are many other classes that provides the async feature using this model and we can use that. In my next post, We’ll use Task based asynchrony and see how can we leverage that in our ASP.NET pages.

Cheers,
Brij

Writing Asynchronous Web Pages with ASP.NET- Part 1

Asynchronous programming is not new but recently getting precedence over synchronous model. As user experience is now our top priority, we provide our considerable amount of effort to provide user a seamless experience. Asynchrony is one way to achieve it. I am going to write a series of posts on this topic.

Normally in our day to day programming,  web pages that we write, executes synchronously. But having lot of data on a single page mar the performance of web page. Even sometimes, we have lot sections in our page that can be loaded independently and parallely. Keeping it in mind, Microsoft introduces new way of writing asynchronous programming (Task based asynchronous pattern) with .NET 4.0 and further simplified it using async and await keyword in .NET 4.5. Currently, There are three pattern are available for writing asynchronous code

1.    Asynchronous Programming Model (APM)
2.    Event based Asynchronous Pattern (EAP)
3.    Task based asynchronous Pattern (TAP).

Asynchronous web pages can be written since ASP.NET 2.0 but it does not got much attention. Now it’s time to take advantage of this feature with available asynchronous models. In this post, We’ll use Asynchronous Programming Model (APM) to write the asynchronous web page. First let us just briefly discuss about asynchronous programming model (APM).

Asynchronous Programming Model (APM)

This asynchronous programming model is introduced with .NET 1.0 and it is also called IAsyncResult pattern. Here there are two methods are required, one starts with Begin keyword and another starts with End keyword so the name could be BeginOperationName and EndOperationName (This is just a naming convention). And once the BeginOperationName method is called, the thread is released and the task gets executed asynchronously, in the meantime and the released thread can pick some another task and EndOperationName method is called once the asynchronous task completes. BeginOperationName returns the type IAsyncResult. It can be pictorially shown as

APM ModelThere are few classes like FileStream (available under namespace System.IO.FileStream) exposes multiple type of Read methods like synchronous calls, it has Read() and for APM pattern it has BeginRead and EndRead as well. We can ourselves implement the same methods if we want to provide the similar feature to the class users.

Now let’s write our asynchronous web page using APM model. First, to make a page asynchronous, we need to set async=”true” in the page directive.

So in this web page, we are going to fetch the data from database and then bind it a GridView. So the code behind looks like

    public partial class AsynchronoususingAPM : System.Web.UI.Page
    {
        private SqlConnection sqlConnection;
        private SqlCommand command;
        private SqlDataReader sqlDataReader;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AddOnPreRenderCompleteAsync(
                    new BeginEventHandler(BeginDataLoad),
                    new EndEventHandler(EndDataLoad)
                );
            }
        }

        IAsyncResult BeginDataLoad(object sender, EventArgs e, AsyncCallback asyncCallback, object state)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["AdventureWorksLT2008R2ConnectionString"].ConnectionString;
            sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();
            command = new SqlCommand("SELECT Top 20 Title, FirstName, LastName, EmailAddress, Phone FROM SalesLT.Customer", sqlConnection);
            return command.BeginExecuteReader(asyncCallback, state);
        }

        void EndDataLoad(IAsyncResult asyncResult)
        {
            sqlDataReader = command.EndExecuteReader(asyncResult);
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            gdCustomers.DataSource = sqlDataReader;
            gdCustomers.DataBind();
        }

        public override void Dispose()
        {
            if (sqlConnection != null)
                sqlConnection.Close();
            base.Dispose();
        }
   }

So here, if we see we have written to methods BeginDataLoad and EndDataLoad and binding that data Page_PreRenderComplete. So when we run this page, it looks likeAsyncPageLet’s discuss how it flows. When a user makes a request for this page, a thread is assigned to it from the thread pool. When the request reaches where it requires to fetch the data from the database, a database query is launched and current thread gets free and available to thread pool. When this query gets executed and the data comes to ASP.NET, ADO.NET requests a thread from thread pool and a thread is assigned to it from the thread pool which completes the request. It means while our database query was executing and the transporting the data from database to asp.net server, there was no thread involved and earlier executing thread was available to take another request.

Hope you guys have enjoyed this post. In the next post, We’ll write the asynchronous page using the next programming model.

Cheers,
Brij

How to download a file forcefully instead of rendering on Browser

Being a web developer, you must have worked one or more times on providing feature for downloading a file. If not, you’ll work in near future. Anyways let’s discuss a scenario.

Normally, we see that when we click on a link of the file to download that link opens up in the browser. Actually when we click on the link, request is sent to web server, and server returns the content to the client. Based on the file name extension, browser decides the type of content and accordingly, if browser has a capability to load the file on browser that it shows it in the browser. If browser is not able to display on the browser the shows the download file dialog box to save it. You may see different behavior in different browser because some browser may able to show it on browser and other may show the download dialog box. But you can save it via browser save as option if it is rendered on browser.

But How to forcefully show the save as dialog to the user?

As we already discussed that when we click the on any link then based on the browser capability the browser shows the dialog box or open it in the browser itself. But to show the save as dialog every time (for every type of file) we need to to tell browser that this is an attachment. For this we need to add a Content-Disposition Header in the response. This should be as

Response.AddHeader(“content-disposition”, “attachment;filename=somefile.ext”)

You can write the code to download the file many ways. But if you want to download it using the browser’s download dialog box then we need to add Content-Disposition Header. We can write the code for downloading a file as
filedownloadOnce you add the Content-Disposition header, the file will always be downloaded. As the behavior of browsers varies as Firefox shows a save as dialog, Internet Explorer (v11) prompts at the bottom side of browser, while Google chrome downloads it without prompting but in any case file will be downloaded.

Thanks for reading the post.

Cheers,
Brij

WebGrease : A fantastic tool for Web Optimization

In this post, We are going to talk a library that you guys must have seen in latest version of ASP.NET (4.5) and ASP.NET MVC (4.0). So first let’s first understand,

What is WebGrease?

WebGrease is a suit of tools that helps is optimizing the static files (like JavaScript, CSS) in a web application. This tool is developed by a performance team in MSN division of Microsoft . Actually It is evolution of the AJAX min library that we are already using.  This team continuously works on the optimization of their web sites. So the current capabilities of WebGrease are

Continue reading

IIS7 and Higher : system.webServer element ApplicationHost.config vs Web.config

Hi All,

This is another post on Authentication for ASP.NET applications. In one of my last posts, I talked about setting up authentication mode as Windows in web.config and Enabling/Disabling windows authentication at IIS. You can access that post from the below link.

Looking into Windows authentication at Web.config and at IIS
Continue reading

Looking into Windows authentication at Web.config and at IIS

Hello All,

I have seen many confusion around setting authentication mode as windows in web.config and enabling  Windows authentication at IIS.

First thing that there is no relation between setting authentication mode as windows at web.config and enabling/disabling (Integrated)Windows Authentication at IIS.

Continue reading

Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

Working with EventViewer using C#

There are several phases of a Application . It does not end with developing the application and deploying it on production servers. Other most important part, any problem surfaces after the deployment, how quickly the problem can be be resolved and according to severity of the issue (if required) a patch can be deployed on production. Apart from this, we also want to get notified on all the issues occurred on production and accordingly analyze and take care in future releases. We can also log other details that could be useful to check the status of Application.

Continue reading