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.



Monday, 24 December 2012

 Click Here to Download JQueryImageOverlay.zip

Image overlay means give text caption to image. Using Image overlay we can provide more details regarding image on mouse hover of image. This overlay is common in modern websites. We are using JQuery Image Overlay Plugin. This is a javascript file which you found online as well as we place this javascript in our example so you can download that from our given asp.net example.

There are many options and advance settings provided by Overlay Plugin javascript "jquery.ImageOverlay.js". You can set without any options for simple purpose. There are options like border color, overlay origin, overlay color, and overlay text color, overlay speed, overlay speed out etc.

By setting this option you made you custom overlay, like border cover , text color , different In and Out overlay animation etc..
You can also use JQuery MetaData Plugin "jquery.metadata.js" to display meta data information in overlay.

Here is example for this.
In this example we take several images to display various uses of Image overlay with Asp.Net.

Wednesday, 19 December 2012

You can bind list of strings to gird view and display very uniform manner in a very easy way. List may be a generic list of strings. Generic List class is available in "System.Collections.Generic" namespace. We are using "DataSource" property of Grid view to set data source and "DataBind" method to bind data.

Here is example for this.

Thursday, 13 December 2012

There are many situations where you want to list of stored procedures from your database and it's useful details like , SP created date , modify date etc.. using sql query.
There is simple way to get these information using sql query.
We are using "sys.procedures" system table to get list and details.
Here is the sql script.

Friday, 7 December 2012

There are many situations where you want to list of tables and it's useful details like , table created date , modify date etc.. using sql query. There is simple way to get these informations using sql query.
We are using "sys.tables" system table to get list and details.
Here is the sql script.

SQL Query :
select * from sys.tables

Output : 

(To view original image , click on image)










This is the very useful SQL Server Scripts.

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