Tuesday 29 January 2013

This Image shows how an HTTP request flows through the Web API pipeline, and how the HTTP response arrive back. It has also shows extensibility points, where we can add custom code or even replace the default behavior entirely.

This Image is used by web developers who want to understand the Web API pipeline. You can download that image from below link. This image is available in PDF file.

For printing purpose it's size is 24"X30". There are two version of that image one is full color and other is a gray-scale version.

Image : 
Lifecycle of an HTTP message in ASP.NET Web API


Click To Download full color Image.
Click To Download gray scale Image.

Source : http://www.microsoft.com

Friday 25 January 2013

Click to Download C# Example StronglyTypedDataControlsInCSharp.zip
Click to Download VB.NET StronglyTypedDataControlsInVBNET.zip


Strongly Typed Data Controls features newly introduce in vNext series. New ItemType Property for controls who has "template" Concept like Repeater, Grid, Form View etc.. Strongly typed data-controls is a small, but very good feature that makes work with data bound expressions easier and cleaner.

ASP.NET Web Forms introduced the concept of  "templates" starting with the very first release. Templates allow you to customize (or override) the markup of server controls, and are typically used with data binding expressions.

When using data binding within a template we used late bound expressions to bind to the data. For example, we are using the Eval() helper method for binding data. the "customer_id" and "customer_name" properties from a list of objects data bound to a repeater control like this :

        <asp:Repeater runat="server" ID="Repeater1">
            <ItemTemplate>
                ID : <%# Eval("customer_id") %>
                <br />
                Name : <%# Eval("customer_name") %>
                <br />
                <hr>
                <br />
            </ItemTemplate>
        </asp:Repeater>
      
In .Net 4.5 there is new strongly-typed data templates in that new "ItemType" property introduce on data controls. With the help of this property we declare that what type of data is going to be bound to data control.

Where you set "ItemType" property to object at that time there are two new typed variables to be generated in the scope of the data bound template. These variables are "Item" and "BindItem".

We can use these variables in data binding expressions and get Intellisense and compile time checking support.

IntelliSense Display : 

Strongly Typed Data Controls IntelliSense Display
(To view original image , click on image)



If we make any mistake while typing the field name we will receive error message from IntelliSense engine.

IntelliSense Error :
Strongly Typed Data Controls IntelliSense Display
(To view original image , click on image)



Here is example for this.

Saturday 19 January 2013

Click to Download C# Example CachingFileDependencyInCSharp.zip
Click to Download VB.NET Example CachingFileDependencyInVBNet.zip


Before .Net 4.0 we are using System.Web.Caching.Cache object. Now in .Net 4.0 introduce same system.web.caching functionality in System.Runtime.Caching.dll everything was rebuilt into the new namespace of System.Runtime.Caching.

The reason for this is that the System.Web.Caching.Cache object was so useful that other application developers like Windows Forms, Windows Presentation Foundation apps, and more were need to bring the System.Web namespace into their projects to make use of this cache object. So, to remove this dependency this was all extracted out and extended with the System.Runtime.Caching namespace.

As an ASP.NET developer, we can still use of the System.Web.Caching.Cache object just as we did in all the earlier versions of ASP.NET. It isn’t going away. However, it is important to note that as the .NET Framework evolves, the .NET team will be making its investments into the System.Runtime.Caching namespace rather than System.Web.Caching.

This means that over time, we will most likely see additional enhancements in the System.Runtime.Caching version that changes does not appear in the System.Web.Caching namespace as you might expect.  it does not also mean that we need to move everything over to the new System.Runtime.Caching namespace to make sure we are following the strategic path of Microsoft, because the two caches are managed together under the covers.

Here is example for this.

Wednesday 9 January 2013

Click to Download C# Example ImplementHttpContextCurrentItemsInCSharp.zip
Click to Download VB.NET Example ImplementHttpContextCurrentItemsInVBNet.zip


ASP.NET’s best kept secrets is The Items collection of HttpContext. This is an IDictionary key/value collection of objects that’s shared and access across the life of a single HttpRequest. This short term storage because it stores data in single HttpRequest.

There are some reasons why we should need this type of storage.
  • Communicate between two instances of the same UserControl on the same page : This situations occurs when you have one and and put one user control two times on different section of page and display same content. At that time we get data from database when first control load and after that we preserve this data in HttpContext.Current.Items and when second control load it will check that data is exist in Items if yes then directly get data from that and we avoid unnecessary database trip. Another scenario , You develop user control which display advertise and you put two instances of that control on same page and you want to display unique advertise at that time HttpContext very helpful.

  • Store the results of expensive calls that might happen twice or more on a page: If we have multiple User Controls on same page and each display a data from a large, more expensive database retrieval, those UserControls can retrieve the necessary data from HttpContext.Items. The database is hit only once.
  • Share content between IHttpModules and IHttpHandlers: If we write a custom IHttpModule, we can store context about the user for use later in a page.

The Items collection store objects, like many of the collections. When you retrieved those stored objects you need to cast those objects back to their specific type.

Before you implement any caching mechanism you need to analyze your requirement. If you put caching unnecessary it will put burden on your server.
Do not cache just because it is good; cache because it makes sense.

Here is example for this.
This example checks the Items collection of the current HttpContext to see whether the data is already there. If it is not then data is retrieved from the database and store in the Items collection. Subsequent calls to this function within the same HttpRequest receive the already cached object.
 In this example we create one user control name "WebUserControl_WithHttpContext.ascx". This control has one method "GetExpensiveCount". This method return cont string which may come for very expensive database call. In this method when data retrieve from database it will store in HTTPContext item collection when in single HttpRequest again this method called at that time it will check that if data is exist in cache it will give from that cache so we avoid one unnecessary Database call. We need to specify one key for retrieve specific data.

ASPX Code (ImplementHTTPContext.aspx) :

<%@ Register src="WebUserControl_WithHttpContext.ascx" tagname="WebUserControl_WithHttpContext" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr style="height:50px">
                <td>
                    Header: <br />
                    <uc1:WebUserControl_WithHttpContext ID="WebUserControl_WithHttpContext_Header" 
                        runat="server"></uc1:WebUserControl_WithHttpContext>
                </td>
            </tr>
            <tr style="height:300px">
                <td>
                    Content
                </td>
            </tr>
            <tr style="height:50px">
                <td>
                    Footer : <br />
                    <uc1:WebUserControl_WithHttpContext ID="WebUserControl_WithHttpContext2_Footer" runat="server"></uc1:WebUserControl_WithHttpContext>
                    
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


User Control .ascx Code ("WebUserControl_WithHttpContext.ascx"):

Expensive Count : <asp:Label runat="server" ID="lblCount"></asp:Label>

C#. Net  Example("WebUserControl_WithHttpContext.ascx.cs") :

    protected void Page_Load(object sender, EventArgs e)
    {
        lblCount.Text = GetExpensiveCount("count").ToString();
    }

    public string GetExpensiveCount(string KeyID)
    {
        string strRef = string.Empty;
        string key = "count_data" + KeyID;
        object obj = HttpContext.Current.Items[key];
        int intCount = 0;
        if (obj != null)
        {   
            //Get from cache
            intCount = (int)obj;
            strRef = "From cache , ";
        }
        else
        {
            //Call Database query and get result and store
            intCount = 20;
            HttpContext.Current.Items[key] = intCount;
            strRef = "From Database , ";
        }
        return strRef + intCount.ToString();
    }


VB.Net Examples ("WebUserControl_WithHttpContext.ascx.vb") :

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblCount.Text = GetExpensiveCount("count").ToString()
    End Sub

    Public Function GetExpensiveCount(ByVal KeyID As String) As String
        Dim strRef As String = String.Empty
        Dim key As String = "count_data" & KeyID
        Dim obj As Object = HttpContext.Current.Items(key)
        Dim intCount As Integer = 0
        If obj IsNot Nothing Then
            'Get from cache
            intCount = CInt(obj)
            strRef = "From cache , "
        Else
            'Call Database query and get result and store
            intCount = 20
            HttpContext.Current.Items(key) = intCount
            strRef = "From Database , "
        End If
        Return strRef & intCount.ToString()
    End Function

Output : 

Short Term Storage in Asp.net


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.


Tuesday 1 January 2013

Click to Download C# Example ImplementHttpHandlersInCSharp.zip
Click to Download VB.NET Example ImplementHTTPHandlersInVBNET.zip

HttpHandlers is different from HttpModules. HttpHandlers positions in the request-processing pipeline is different from HttpModules. Using HttpHandlers we can map to a specific file extension.

Handlers are the final stop for incoming HTTP requests and the point in the request processing pipeline that is responsible for serving the requested content or data like. HTML , ASPX page, plain text, or an image.

Using HttpHandlers we can handle dynamic file download request.
HttpHandler using an ".ashx" file extension that allows to get started quickly and requires no server configuration.

You can add generic HttpHandler by simply select the Generic Handler file type from the Add New Item dialog in your project. Here below sample screen shot display. You may change the extension of file but this will require additional configuration in your deployment server. With ".ashx" extension you do not require any additional configuration.
When you add generic http handler in your application or project class stab is automatically added in ".ashx" file.

This class stub implements the IHttpHandler interface, which need you to implement the Process Request method and IsReusable property.

  • In ProcessRequest method you use to actually process the incoming HTTP request. By default, the class stub changes the content type to plain and then writes the “Hello World” string to the output stream.
  •  The IsReusable property lets ASP.NET know whether incoming HTTP requests can reuse the sample instance of this HttpHandler.

The handler generated automatically in you added file is ready to run right away. You can run this ".ashx" file in browser and see the result. This result depends on various factors like...
  • Browser type and version
  • Applications loaded on the system that may map to the MIME type
  • Operating system and service pack level

Based on these factors, you might see the text returned in the browser, you might see Notepad open and display the text, or you might receive the Open/Save/Cancel prompt from IE.

Here is example for this.
In this example we get images from "ImageHandler.ashx" file base on query string and display images directly in "<img>" tag. For that we added on "ImageHandler.ashx" file in our project and set content type "image/jpeg" in "ProcessRequest" method and depending on query string variable "id" value we can get image.

ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            HTTP Handler class Impliment in Img tag
        </h1>
        <h1>Id : 1</h1>
        <img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />

        <h1>Id : 2</h1>
        <img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />

    </div>
    </form>
</body>
</html>

C# Examples (ImageHandler.ashx File) :

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;

public class ImageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        context.Response.ContentType = "image/jpeg";
        if (context.Request.QueryString["id"] == "1")
        {
            context.Response.WriteFile("bamboo.jpg");
        }
        else
        {
            context.Response.WriteFile("palmtree.jpg");
        }
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

VB.Net Examples :
 
<%@ WebHandler Language="VB" Class="ImageHandler" %>

Imports System
Imports System.Web

Public Class ImageHandler : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World")
        
        context.Response.ContentType = "image/jpeg"
        If context.Request.QueryString("id") = "1" Then
            context.Response.WriteFile("bamboo.jpg")
        Else
            context.Response.WriteFile("palmtree.jpg")
        End If
        
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Output (Add new Generic Handler ".ashx" File): 

Add new Generic Handler ".ashx" File
(To view original image , click on image)


Output (Get Image from "ImageHandler.ashx" file) : 

Implement Generic HTTPHandler
(To view original image , click on image)


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.