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

ASP.NET 4.5 – Control display format of Data in Model Binding

I have written few posts on ASP.NET 4.5. One of the best feature I liked that is Model Binding that is almost similar to ASP.NET MVC. This is another feature of Mode binding in ASP.NET 4.5. For better understanding and usage, you should have some knowledge on this basic feature . You can refer my earlier posts on model binding at the links below

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 1

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Now if your model is getting populated using entity framework or in any other way from the database then normally we apply some kind of formatting before displaying the data on the User Interface. Because the way data is stored in database and the way it is displayed on UI is quite different. We transform the data in a friendly, easy and some time in their Locale before displaying. Like say I have a number 100000 stored in database but we display it is 100,000 or displaying the number in specific format. So let’s take an example

I have created a class Employee as

public class Employee
{
    [Required()]
    public int Id { get; set; }
    [Required(), StringLength(30)]
    public string FirstName { get; set; }
    [Required(), StringLength(30)]
    public string Lastname { get; set; }
    [Required(), StringLength(30)]
    public DateTime DateJoined { get; set; }
    [Required(), Range(5, 1000)]
    public int Salary { get; set; }
}

Now let’s see the aspx page

    <div style="font-family:Verdana; font-size:small">
     <asp:DetailsView ID="detailsViewEmployee" runat="server" SelectMethod="GetEmployees"
       InsertMethod="InsertEmployee"  UpdateMethod="UpdateEmployee" AutoGenerateInsertButton="true"
       AutoGenerateEditButton="true" ItemType="Employee" ></asp:DetailsView>
     <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true"/>
    </div>

Here I am using details view and provided the ItemType as Employee, SelectMethod, InsertMethod and UpdateEmployee methods. The code behind of the file is as

    List<Employee> employees = new List<Employee>();
    protected void Page_Load(object sender, EventArgs e)
    {
        Employee emp = new Employee()
        {
            Id = 1001,
            FirstName = "Brij",
            Lastname = "Mishra",
            Salary = 100000,
            DateJoined = new DateTime(2012, 12, 12)
        };

        employees.Add(emp);
    }

    public IQueryable<Employee> GetEmployees()
    {
        return employees.AsQueryable();
    }
    public void InsertEmployee(Employee e)
    {
        if (ModelState.IsValid)
        {
            employees.Add(e);
        }
    }
    public void UpdateEmployee(Employee e)
    {
        // Update the employee
    }

Now let’s run the code

WithoutDIf you see the encircled area in above screenshot, one is date format and other is a number. One may want to display it in some friendly format. One way to transform the data before displaying and other is to use DisplayFormat Attribute. DisplayAttribute is applied on model so here I am going to apply it on DateJoined property of Employee class asDateJoinedhere we have added the DisplayFormat attribue and provided DataFormatString. This string is used to format the string before displaying it. Let’s add DisplayFormat attribute to salary property as

salaryHere also, We provided a different format string for number. Now let’s run it

formattedNow if you see that Date and number is properly formatted. We just required to add one attribute and provide the format string that is used to format the data.

DisplayFormat attribute provided some more very useful properties. Few of them

  • ApplyFormatInEditMode- Provide this property in attribute and set it true. It will format the data when the form will be in edit mode as well else you’ll loose the formatting in edit mode.
  • NullDisplayText- If any property is null and you want to show some default text then it is very useful. Just provide the string and it’ll be displayed if that property is null
  • ConvertEmptyStringToNull – If you want to convert empty string treated as null then set it true.

Hope you have enjoyed the post and you’ll use the power of DisplayFormat attribute in your ASP.NET 4.5 projects.

Thanks,
Brij

Join me and Learn ASP.NET 4.5 with us

Hello Friends,

You’ll be excited to know that on 23rd Feb 2013, I’ll be speaking on ASP.NET 4.5 at Mindcracker Chapter Meet event Pizza, Tea and Code. This will be demo oriented session and will take you through the examples.

To get the details of the Event and register Click Here .

If you are staying in Noida and nearby areas, come and join us and there will three developer session back to back that you will enjoy. We’ve also arranged small refreshments for you as well.

This event will be taking place Sector 63, Noida at Mind Cracker office.

Hope you all enjoy it.

Thanks,
Brij

ASP.NET 4.5 : Login using other Authentication Providers Simplified

In this Post, I am going to discuss one of the other new features of ASP.NET 4.5. That you’ll like. I’ll also try to make it simple and include step by step tutorial so that you can implement at your environment.

Now a days, you guys must have seen that almost all leading websites allow you to login with your other accounts/credentials. It may be Facebook, Gmail, Twitter, Microsoft and many other.

I like this feature very much because a user don’t need to register on every website where s/he wants to login and reduce the login credentials count drastically and make life simpler.

So Facebook, Gmail, Twitter… works as Identity provider that provides there APIs that one can integrate with there application and allow user to login with their Facebook, Twitter, Gmail… accounts. There are various ways to implement it and they work on some standard protocols so that everybody can understand their API.

Currently, most leading identity provider follow OAuth standards and OAuth provides a process for end-users to authorize third-party access.

So now let’s come to ASP.NET. ASP.NET 4.5 new template has the required code already in place that you require to write to uses the third party Identity provider. You just need to enter some required Ids and secret keys and once you provide it. It’ll start working.

So let’s first create a ASP.NET application as FILE|NEW|Web Site|ASP.NET Web Forms Site. Now if you open the solution explorer, It has created lots of files and that provides many feature already implemented, you must have seen in earlier version as well. I assume you have basic Idea about all that.

Now let’s open a file under App_Code/AuthConfig.cs. Now if you check this file has several lines of commented code. If you see that closely, then actually it adding authentication clients like Twitter, Facebook, Microsoft, Google . Now here, you need Id and secret keys for the authentication clients that you need to provide.

So I have uncommented the code for two authenticated clients Twitter and Google. And I have put my Twitter  key and secret key while Google doesn’t require any. Now as soon as,  you run the application and click on login link at right top, you ‘ll see below

Login

You can see two buttons Twitter and Google. A user can use these accounts to login. Let’s click on twitter.

Twitter Login

It took me on the above page and I entered here my Twitter account and clicked on sign in and it took me at the following page

AfterLogin

here I can change my my user name and I changed it as Brij. As soon as I click on login, I am authenticated and you can see that I am now loggedin.

LoggedinWithTwitter

Now if you click on the user name (Brij) shown in above pic right corner, It shows the following page.

twitter-ResetPwd

It allows you to set a local password. After setting your local password you won’t need to your login via Twitter  to authenticate the current website. Now if you see the last section, it shows twitter account which is used for login.

You can login with other account as well at same point of time. As, I have enabled the two authentication providers Twitter and Google, you are seeing both of these two at last section . And when I click on Google it takes me at Google login page. As soon as I put my credential and click on Sign in button. It shows me that I am logged in as using two accounts. Twitter and Google as

Loggedinwithtwoaccount
Also, you can see after login with two accounts, it shows a remove button to remove any authentication. And as soon as you’ll click on any remove button that authentication will get removed and other remove button will also be removed. Because for login, at least one authentication is required.

Now I’ll tell you, How I created Ids and secret for my local App. To create appId and secret from Twitter go to link TwitterApp .

Once you click on the following the below steps:

  1. Click on Create a New Application
  2. Put the name and description of your application.
  3. Now, put the URL of the your local application. A caveat,  you cannot put the URL generated by Visual Studio integrated server. So host your application at local IIS but twitter wont accept localhost URL as well. You need to have some URL that be hosted on some domain. So how can you mimic that scenario on your local server. I have found a interesting testing domain localtest.me . This is not localhost.me but localtest.me.
    So to set the domain, Go to IIS->Default Web Site. Right Click Default Web Site and Click on Edit Bindings. Here I added a Site Binding (localtest.me)  by Clicking on Add button. I just entered the Host Name localtest.me as

AddBinding

So my application URL for twitter was http://localtest.me/testdomain/Default.aspx.

So once you’ll put all these and save. You’ll get Key and Secret that you can use for your ASP.NET 4.5 local application.

So you have seen, How ASP.NET 4.5 simplified our life by providing inbuild mechanism for using other leading authentication providers. We as developer don’t need to worry about underlying complex logic. Just need to provide some AppIds and Secrets and Google does not require any Id and secret as well.

Hope you all have enjoyed.

Happy Learning,
Brij

FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Last week, I wrote the first part of the post Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5. In the first post , I discussed about Strongly typed data control, Model Binding, filtering data, Value Providers and about writing own Custom value provider. Please find the link of earlier post below.

http://brijbhushan.net/2012/07/01/strongly-typed-data-controls-and-modal-binding-in-asp-net-4-5-part-1/

Model Binding feature also supports editing feature. Control’s like Gridview has three properties

  • InsertMethod
  • UpdateMethod
  • DeleteMethod

you can assign a method that has been written at code behind and the method takes a single parameter with the associated type. And the value of the parameter holds the value to be updated. As say if my Control is associated with a Type say Product then the delete method could be as

public void DeleteProduct(Product p)
{
//Write the logic of deleting the passed product p
}

Now, I’ll talk about Model Validation and custom validation attribute. So let’s start.

We all have used ASP.NET validators many times for validating lot of controls and of course used the same of data controls like GridView also. But Model Binding provides another way of implementing validation.

So now you can use System.ComponentModel.DataAnnotations and apply the validation at your model level. And if your control is bound to some model that validation would be taken care. So let’s start with an example. See how can we put different Validation attribute to our class as below

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
public string Email { get; set; }
}

As I put Id as required attribute, it means it is required and if it is not provided it’ll throw an error.

DataAnnotations provides other kind of validations like Range,  StringLength etc as well. Also we can have multiple attributes as well on any property to have multiple validations on same Value as you can see above.

I have used a DetailsView and used this class as model for that DetailsView control as

<asp:DetailsView ID="detailsViewSpeaker" runat="server" SelectMethod="GetSpeakers" InsertMethod="InsertSpeaker" AutoGenerateInsertButton="true"
ItemType="Speaker"></asp:DetailsView>

You must have used ValidationSummary control earlier. Now this control has one more property called ShowModelStateErrors which need to be set as true. This will be enable the page to display all model related errors as

<asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true"/>

Now let’s run the page

You can see the above screen, all the validation errors are Mode state errors.

This is not at all, if your requirement does not get fulfilled by the in built validation attribute then you can write your own custom attribute as well. To create a custom attribute, you need to implement ValidationAttribute and override IsValid method and need to put own custom logic in this method only. lets create a custom validation attribute.

In my example, I have written custom logic for validating an email. Let’s have a look

public class MyCustomValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex regex = new Regex(MatchEmailPattern);
return regex.IsMatch(value.ToString());
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name);
}
}

We can also tweak the default validation message by overriding FormatErrorMessage as I have done above. Now Let’s use it in my model. As

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
[MyCustomValidation(ErrorMessage = "{0} field custom validation failed. Your email is not in proper format.")]
public string Email { get; set; }
}

Now Let’s run the application

As you can see, I have entered a wrong formatted email. And when clicked on Insert button, the custom validation is error is thrown.

Hope you all have enjoyed this post.

Thanks,

Brij

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 1

Recently, I took  a session on KolkataGeeks and discussed on  ASP.NET 4.5 enhancements. I mainly discussed on changes in data controls and model binding feature added in ASP.NET4.5.

I am going to write a series of post on the same feature here also. Till date, you all must have  had a look on the enhancement and new features introduced in ASP.NET 4.5. The main change in data control that now it provides intellisense support at aspx pages. You need to assign the ItemType property to model that is going to be associated with the data controls. As

Strongly Typed Data Control

These controls are also referred as Strongly Typed Data Controls.

There are also other major changes took place, in the way we provide the DataSource to the our DataControls. Here in my example, I have taken a GridView.

Earlier, we used to provide DataSource to our Data Control and then call DataBind. We used multiple Data Sources like SQLDataSource, ObjectDataSource etc. But now, you have another option which allows us to not set DataSource property and call the DataBind specifically.

There is a property got introduced named as SelectMethod. We can write our own method at server side and assign the method to this property. One thing, we need to take care that it must return the collection of objects and it should be either IEnumerable or IQueryable. Server side method could be as

public IQueryable<Product> GetProducts()
{
return dbcontext.Products.AsQueryable().OrderBy(i => i.Name);
}

And my gridview at aspx

<asp:GridView ID="gridProducts" runat="server" ItemType="AdventureWorksLTModel.Product" AutoGenerateColumns="false"
SelectMethod="GetProducts" >
<Columns>
<asp:TemplateField HeaderText="Product Name" SortExpression="Name">
<ItemTemplate>
<%#Item.Name %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="ListPrice">
<ItemTemplate>
<%#Item.ListPrice %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Color" SortExpression="Color">
<ItemTemplate>
<%#Item.Color %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Now why this method should return only IEnumerable or IQueryable . Controls like GridView provides many features like Paging, Sorting etc. As soon as you assign the method to SelectMethod property. You don’t need to write any special code for Paging, Sorting.. feature. For that it creates Linq  queries on the fly and it can be written only on the collection that implements IEnumerable or IQueryable.

That’s not it, in many cases we provide some kind of filter criteria to the users, based on user can view only filtered data.

ASP.NET4.5 provides many Value Providers that can be used and these value providers are

  • Querystring
  • Session
  • Cookie
  • Control Value
  • Form Value etc..

These value provider can be directly used to filter the data. But how?

These value providers must be passed as a parameter in the method, that is going to be assigned to Select method. Let’s if we want Query String as value provider so we can pass it as

public IQueryable<AdventureWorksLTModel.Product> GetProducts([QueryString("key")]string parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == parameter).AsQueryable().OrderBy(i => i.Name);
}

where key is the Query String parameter and it can access the value directly in the method as above.

Similarly other value providers can be used. One more example, we can have some control’s value as value provider. For that in my example, I have created a drop down and I want to use drop down’s selected value for filtering the data it can be used as

<asp:DropDownList ID="ddlColors" runat="server" SelectMethod="GetColors" AutoPostBack="true" ></asp:DropDownList>

Above one is my dropdown. And as you can see, It also has SelectMethod, I have assigned it a GetColors method and it is also written as

public IEnumerable<string> GetColors()
{
var colors = (from c in dbcontext.Products
where c.Color != null
select  c.Color).Distinct();
return colors.ToList();
}

Now my SelectMethod method for gridview is

<pre>public IQueryable<AdventureWorksLTModel.Product> GetProducts([Control]string ddlColors)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == ddlColors).AsQueryable().OrderBy(i => i.Name);
}

You can see the parameter name and it is ddlColors is Id of the dropdown.

Now this is not all. You can also create your own custom value provider. To create your very own Value provider, you need to implement IValueProvider. Here you need to implement a method GetValue which takes a key (string) as a parameter. It returns an instance of ValueProviderResult . It contains the value returned by the ValueProvider.

I created a value provider which takes a value from querystring based on it fetch some data from database and return it. As

public class MyCategoryProvider : IValueProvider
{
private HttpContextBase context;
private string value;
private int limit;
public MyCategoryProvider(HttpContextBase hcb, string val)
{
context = hcb;
value = val;
}

public bool ContainsPrefix(string prefix)
{
throw new NotImplementedException();
}

public ValueProviderResult GetValue(string key)
{
string category = context.Request.QueryString[this.value] as string;
GetPriceLimit(category);
return new ValueProviderResult(limit, limit.ToString(), System.Globalization.CultureInfo.CurrentCulture);
}
}

Now this can not be used directly. Because ValueProvider is used as an Attribute. So now, you need to create a custom attribute which returns the your Value provider.

To Create a Custom attribute you need to inhert from ValueProviderSourceAttribute which is available in namespace System.Web.ModelBinding . Here override the method GetValueProvider which returns the valueprovider. It is wrtitten as

[AttributeUsage(AttributeTargets.Parameter)]
public class CategoryAttribute : System.Web.ModelBinding.ValueProviderSourceAttribute
{
private string code;
public CategoryAttribute(string _code)
{
this.code = _code;
}

public override IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
{
return new MyCategoryProvider(modelBindingExecutionContext.HttpContext, this.code);
}
}

Now your custom value provider is ready for use. Let’s use this

public IQueryable<Product> GetProducts([Category("cat")]int parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.AsQueryable().Where(p => p.ListPrice <= parameter).OrderBy(i => i.Name);
}

So, you can see that I have used Category as a Value Provider.

Hope you all have enjoyed the post. I’ll discuss more on Validation and other things in my next post.

Cheers,
Brij

Explore and Learn ASP.NET 4.5

I have written few posts on ASP.NET 4.5 and Visual Studio 11 that . All the post featured as Article of the day at Microsoft official website http://www.asp.net/community. I mainly focused Web development.

If you want to learn about new version of ASP.NET 4.5 and Visual Studio 11(Now Visual Studio 2012).

This post is part 1 of 2 series on Strongly Typed data controls and Model Binding in ASP.NET 4.5. In this post, I discussed about Strongly typed data control, Model Binding, filtering data, Value Providers and about writing own Custom value provider.

This is second and last of on the series of Strongly Typed data controls and Model Binding in ASP.NET. In this post I discussed the editing feature and custom validation attributes.

In this article, we discussed the support of Unobtrusive validation in ASP.NET 4.5. This reduces the rendered page size dramatically. Instead using  java-script function and other client side libraries. It uses HTML5 data-* attributes for all these validation.

In this post, we discussed the Request Validation enhancement made in ASP.NET 4.5. There are several times nowadays, we require to allow the user to script tag as Input. This is the backbone of many blog site. But if proper validation is in place then “A potentially dangerous request..”. Now ASP.NET 4.5 allows to partial unvalidated request to be submitted.I also discussed Lazy/Differed validation..

In this post, I discussed the enhance made in .NET 4.5 and ASP.NET 4.5 which allows you to write Asynchronous modules in very simple steps in the way you write the synchronous way. Asynchronous modules can be come a boon at certain situations for your Application performance..

As in Asynchronous HTTPModules, Asynchronous  HTTPHandlers can be written very easily with the version ASP.NET 4.5. It also can be a boos t for application performance..

This is one of the best things I like in Visual Studio 11. Page Inspector is integrated with VS 11 and provides the capabilities of web development tools and apart from this directly navigates you to the corresponding aspx/ascx/master… files also.

Hope you all will have fun while learning ASP.NET 4.5

Cheers,
Brij

Asynchronous HTTPHandlers with ASP.NET 4.5

In my last post, I discussed about writing Asynchronous HTTPModule with ASP.NET 4.5. You can check the link Below.
Writing asynchronous HTTP Module in ASP.NET 4.5

In last post, I also briefly discussed about the enhancement made in .NET 4.0 and .NET 4.5, that made our life very easy to write asynchronous code. And in ASP.NET 4.5, we can use these features easily.

I also discussed, why at certain situations Asynchronous HTTPModules are important. In the same way, Asynchronous HTTPHandlers can play a vital role in site performance. The working of Asynchronous Handler can be shown as

Asynchronous HTTPHandler

Asynchronous HTTPHandler

As we know if we need to create a normal custom HTTPHandler. We need to implement IHTTPHandler interface and if we want to create a custom Asynchronous HTTPHandler, we need to implement IHttpAsyncHandler.

In this post, I will be discussing, How we can write Asynchronous HTTPHandlers with the help of new features introduced in .NET 4.5 framework.

In the example, I’ll create an asynchronous HTTPHandler with the help of asp.net 4.5 that downloads rss feed.

To create Asynchronous HTTPHandler in asp.net 4.5, we need to implement the method ProcessRequestAsync of new abstract class HttpTaskAsyncHandler that got newly introduced.

For that I created a class library named AsyncHandlerLibrary , which has a Handler class CustomAsyncHandler which implements HttpTaskAsyncHandler.

So the class CustomAsyncHandler  will be as

   public class CustomAsyncHandler : HttpTaskAsyncHandler
    {

        public override async Task ProcessRequestAsync(HttpContext context)
        {
            string url = context.Request.QueryString["rssfeedURL"];
            if (string.IsNullOrWhiteSpace(url))
            {
                context.Response.Write("Rss feed URL is not provided");
            }
            WebClient webClient = new WebClient();

            //It starts downloading the rss asynchronously and the asp,net thread become free
            //and become available in threadpool
            //once the the it load the rssfeed loading completes it get assigned to another ASP.NET thread from the threadpool
            var rssfeed = await
                webClient.DownloadStringTaskAsync(url);

            // Writing the rss on the screen
            context.Response.Write(rssfeed);
        }

        public override bool IsReusable
        {
            get { return true; }
        }

        public override void ProcessRequest(HttpContext context)
        {
            throw new Exception("The ProcessRequest method has no implementation.");
        }

    }

Now if you see the above code, I have implemented ProcessRequestAsync , in which I read the rss url from query string. And asynchronously downloaded the rss feed and later wrote it in response.

Now you can see, with help of new keywords async keyword and await operator of .NET 4.5, it is extremely easy to write asynchronous code. It also got ensured that same can be used in asp.net with the introduction of new APIs.

Now build the project and add the reference in your web application. Also add this in your web.config file as

 <system.webServer>
  <handlers>
     <add name="myHandler" verb="*" path="*.rss"  type="AsyncHandlerLibrary.CustomAsyncHandler"/>
  </handlers>
</system.webServer>

Now you need to run you application with the url with query string say as http://brijbhushan.net/feed/. And in a while the rss feed would be downloaded as

Now you can seen it has never been so easy to write Asynchronous HTTPHandler. Now enjoy coding with ASP.NET 4.5

Hope you all have enjoyed the above post.

Writing asynchronous HTTP Module in ASP.NET 4.5

Today again, I am going to discuss , one of the new features that got enhanced in ASP.NET 4.5. And It is Asynchronous HTTP Module . And it’s going to be very useful if used meticulously.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?

As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.

Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing

ASP.NET Request Processing : HTTPPipeline and HTTPHandler


Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).

During the entire processing, same thread is engaged in serving  the same request and cannot be used by any another request till request processing completes.  During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless.  In this kind of scenarios the throughput goes down rapidly.

In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make  HTTPModules as asynchronous  that can increase the through put a lot.  In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as

Working of an asynchronous HTTPModule

In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got  released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.
In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.

These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.

And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.

In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.

So to create a Custom HTTPModule, Create a class library project. And create a class  say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule would contains the methods discussed below.

We need to implement two methods Init and Dispose that are part of IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used WriteAsync of FileStream

private async Task WriteLogmessages(object sender, EventArgs e)
{
	HttpApplication app = (HttpApplication)sender;
        DateTime time = DateTime.Now;

        string line = String.Format(
        "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
        time, time,
        app.Request.UserHostAddress,
        app.Request.Url);
        using (_file = new FileStream(
            HttpContext.Current.Server.MapPath(
              "~/App_Data/RequestLog.txt"),
            FileMode.OpenOrCreate, FileAccess.Write,
            FileShare.Write, 1024, true))
        {
            line = line + "  ," + threaddetails;
            byte[] output = Encoding.ASCII.GetBytes(line);

            _file.Seek(_position, SeekOrigin.Begin);
            _position += output.Length;
            await _file.WriteAsync(output, 0, output.Length);
        }

}

Here you can see the await key word, what it means..

As per msdn “An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.

And Init method would be like

public void Init(HttpApplication context)
{
        // It wraps the Task-based method
        EventHandlerTaskAsyncHelper asyncHelper =
           new EventHandlerTaskAsyncHelper(WriteLogmessages);

        //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
        //as Begin and End methods for Asynchronous HTTP modules
        context.AddOnPostAuthorizeRequestAsync(
        asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}

So apart from above these methods, we need to implement the dispose method.

Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as

<system.webServer>
<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as mentioned path in the code.

Hope you all have liked this new feature.