Specializations

Wednesday, August 27, 2014

4-wheeler Ownership Transfer in Bangalore, Karnatka

4-wheeler Ownership Transfer in Bangalore, Karnatka

Hello everybody,
Recently, I got opportunity to interact with Regional Transport Office (RTO) for my car’s ownership transfer. My friends suggested to take help of an agent and get it done but I wasn’t in mood to pay kickbacks, hence I chose to do it my self. I faced bit of difficulty but I overpowered it with patience and persistence. The purpose of writing this blog is to ensure that others are benefitted out of my experience and eventually avoid paying any kickbacks  or bribe to the agents.
In my case, my vehicle was registered under Kormangala, RTO and I’ve to get it registered in Indiranagar RTO.  The ownership transfer process is listed below:
At original RTO, Kormangala:
  1. Get Clearance Certificate and Hypothecation (If the vehicle is on Loan) Cancelled from original RTO. In my case it was Koramangala. You need to produce the following documents.
    1. NOC letter issued from the owner.
    2. Form No. 35 in duplicate(hypothecation cancellation)
    3. Original RC Book.
    4. Self Addressed Clothed Envelope with 12 rs. ticket affixed on it for Local Speed Post.http://www.indiapost.gov.in/netscape/speedpost.html
  2. Next take all the documents to a verifier clerk in office and get it verified. Once verified you have to pay a fee of 100 rs for hypothecation cancellation and attach the chalan with the form. Finally you submit the application.
  3. After 1 week, you will receive the clearance certificate along with your RC book modified.
  4. Next you have to contact the new RTO office where the vehicle has to be registered.
At New RTO, IndiraNagar:
  1. Have following documents ready before you reach to RTO office.
      1. Form no CMV 29 in duplicate.
      2. Form no. CMV 30. If vehicle is covered under Hypothecation/HPA/Lease.
      3. Consent of financier. Original
      4. Registration Certificate(RC) Book. Original.
      5. Valid insurance. Photocopy
      6. Emission Certificate. Photocopy
      7. Address proof ( Ration Card, Voter ID). If you don’t have either of these, get an affidavit for address proof. You’ll find public notary in RTO premise who would endorse your affidavit at a nominal fee.
      8. PAN card . If there is no PAN number form no 61 in case of agriculturists and form no. 60 in case of others.
      9. Clearance Certificate issued by previous registering authority. Original
      10. Two passport size photographs of the transferee.
      11. Self Addressed Clothed Envelope with 12 rs. ticket affixed on it for Local Speed Post.
  2. Next take all the documents to a verifier clerk in office and get it verified. After documents are verified the clerk will redirect you to the next counter where you have to raise the Chalan.
  3. Go to next counter and have chalan raised by entering the details of your RC book in the system.
  4. Got to bill payment counter and pay the amount and obtain the chalan.
  5. Now submit all the documents along with the chalan to verifier clerk once again. Once verifier is done with the verification, he/she will redirect you to form submission counter. You submit all the forms and document and obtain an acknowldegement receipt.  After 1 week, you should receive RC book/Smart card with your name and address in it.
Reference:

Sunday, August 10, 2014

how can we get duration using c#.net

 private int GetDuration(DateTime startDate, DateTime endDate)
        {
            try
            {
                return (int)Math.Round((endDate - startDate).TotalMilliseconds);
            }
            catch (Exception ex)
            {
                ex.ErrorLogger();
                return 0;
            }
        }

How to get CPU Usage and memory Utilization

Use performace Counter for this.


CPU Usage
Prepare PerformanceCounter object.


  Cpuperf.CategoryName = "Processor";
                Cpuperf.CounterName = "% Processor Time";
                Cpuperf.InstanceName = "_Total";
                float first = Cpuperf.NextValue();
 float second= Cpuperf.NextValue();

Note: first value is always 0. So better to take zecond nect value. then it will return the exact value for this.



Memory Utilization:

 PerformanceCounter ramCounterAvailable = new PerformanceCounter("Memory", "Available Bytes");
                PerformanceCounter ramCounterCommitted = new PerformanceCounter("Memory", "Committed Bytes");
                PerformanceCounter ramCounterComitLimit = new PerformanceCounter("Memory", "Commit Limit");
MemoryAvailable = ramCounterAvailable.NextValue();
                MemoryCommitted = ramCounterCommitted.NextValue();
                MemoryComitLimit = ramCounterComitLimit.NextValue();
                var total = MemoryAvailable + MemoryCommitted;
                var MemoryAvailablePercentage = MemoryAvailable / total * 100;
                var MemoryUtilizationPercentage = MemoryCommitted / total * 100;
                second = Cpuperf.NextValue();
                var MemoryUtilizationvalue = (int)Math.Round(MemoryUtilizationPercentage);


Example:
  public void GetCpuAndMemory()
        {
            float second = 0;
            try
            {
PerformanceCounter Cpuperf=new PerformanceCounter();
                PerformanceCounter ramCounterAvailable = new PerformanceCounter("Memory", "Available Bytes");
                PerformanceCounter ramCounterCommitted = new PerformanceCounter("Memory", "Committed Bytes");
                PerformanceCounter ramCounterComitLimit = new PerformanceCounter("Memory", "Commit Limit");

                //Cpuperf = new PerformanceCounter();
                Cpuperf.CategoryName = "Processor";
                Cpuperf.CounterName = "% Processor Time";
                Cpuperf.InstanceName = "_Total";
                float first = Cpuperf.NextValue();
                ramCounterAvailable.NextValue();
                ramCounterCommitted.NextValue();
                ramCounterComitLimit.NextValue();
                var MemoryAvailable = ramCounterAvailable.NextValue();
                var MemoryCommitted = ramCounterCommitted.NextValue();
                var MemoryComitLimit = ramCounterComitLimit.NextValue();
                System.Threading.Thread.Sleep(500);
                MemoryAvailable = ramCounterAvailable.NextValue();
                MemoryCommitted = ramCounterCommitted.NextValue();
                MemoryComitLimit = ramCounterComitLimit.NextValue();
                var total = MemoryAvailable + MemoryCommitted;
                var MemoryAvailablePercentage = MemoryAvailable / total * 100;
                var MemoryUtilizationPercentage = MemoryCommitted / total * 100;
                second = Cpuperf.NextValue();
                var finalCPUusageValue = (int)Math.Round(second);
                var MemoryUtilizationvalue = (int)Math.Round(MemoryUtilizationPercentage);
            }
         
            catch (Exception ex)
            {
             
            }
        }

Friday, May 9, 2014

How to close iframe using javascript + C# script registery

<html>


<head>

<script language="javascript">

function myclose1()
{
window.close();

}


function myclose2()
{
parent.window.close();

}



function myclose3()
{
top.window.close();

}



function myclose4()
{
parent.parentClose();

}

function parentClose()
{
window.close();
}





function myclose1()
{
window.close();

}


</script>

</head>
<body>

<input type="button" value="Close" onclick="myclose1();"/>
<br/>
<input type="button" value="Close" onclick="myclose2();"/>
<br/>
<input type="button" value="Close" onclick="myclose3();"/>
<br/>
<input type="button" value="Close" onclick="myclose4();"/>
<br/>
<input type="button" value="Close" onclick="myclose5();"/>
<br/>
<a href="javascript: window.parent.closeIframe()">Close</a>
<br/>
<a href="window.parent.document.getElementById('theIframe').parentNode.removeChild(window.parent.document.getElementById('theIframe'))">Close</a>
</body>
</html>


C#.net

 string JsScriptValue = "top.window.close();";
           
                 
                ScriptManager.RegisterStartupScript(this, GetType(), "YourUniqueScriptKey", JsScriptValue, true);

Thursday, May 8, 2014

Data table to Excel file using C#.net


     
Data table to Excel file using C#.net

Note: before doing this verify your refernces for  "Microsoft.Office.Interop.Excel.dll".
1) you have to find the Microsoft.Office.Interop.Excel.dll file
2) Microsoft.Office.Interop.Excel.dll refer in your project (or) put this dll in your bin folder
3) Add this below name spacess in your class file.
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

4) Dont open your excel file when you are using to modify through code. Before running this close that excel file. 
5) If file is not exists it will take care to create new file.

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14

static void Main(string[] args)
        {
            string conString = "server =PRASADPA1 ;User ID=XXXX; Password=XXXXX; database=dbName";
            SqlConnection sqlCon = new SqlConnection(conString);
            sqlCon.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter da1 = new SqlDataAdapter("Exec TestSP", sqlCon);
         
            da1.Fill(ds);

            SqlDataAdapter da = new SqlDataAdapter("SELECT * from PecerTestTable", sqlCon);
            System.Data.DataTable dtMainSQLData = new System.Data.DataTable();
            da.Fill(dtMainSQLData);
           // ExportToExcel(dtMainSQLData, @"c:\test456.xls");

            DataColumnCollection dcCollection = dtMainSQLData.Columns;
            // Export Data into EXCEL Sheet
            Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new
            Microsoft.Office.Interop.Excel.ApplicationClass();
            ExcelApp.Application.Workbooks.Add(Type.Missing);


            // ExcelApp.Cells.CopyFromRecordset(objRS);
            for (int i = 1; i < dtMainSQLData.Rows.Count + 2; i++)
            {
                for (int j = 1; j < dtMainSQLData.Columns.Count + 1; j++)
                {
                    if (i == 1)
                    {
                        ExcelApp.Cells[i, j] = dcCollection[j - 1].ToString();
                    }
                    else
                        ExcelApp.Cells[i, j] = dtMainSQLData.Rows[i - 2][j - 1].ToString();
                }
            }

            ExcelApp.ActiveWorkbook.SaveCopyAs(@"C:\test1b.xls");

         
            foreach (System.Data.DataTable dt in ds.Tables)
            {
                AddWorksheetToExcelWorkbook(@"C:\test1b.xls",dt.TableName, dt);
            }
         
        }
        private static void AddWorksheetToExcelWorkbook(string fullFilename, string worksheetName, System.Data.DataTable dtMainSQLData)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = null;
            Workbook xlWorkbook = null;
            Sheets xlSheets = null;
            Worksheet xlNewSheet = null;

            try
            {
                xlApp = new Microsoft.Office.Interop.Excel.Application();

                if (xlApp == null)
                    return;

                // Uncomment the line below if you want to see what's happening in Excel
                // xlApp.Visible = true;

                xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                        false, XlPlatform.xlWindows, "",
                        true, false, 0, true, false, false);

                xlSheets = xlWorkbook.Sheets as Sheets;

                // The first argument below inserts the new worksheet as the first one
                xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
                xlNewSheet.Name = worksheetName;
                DataColumnCollection dcCollection = dtMainSQLData.Columns;
                for (int i = 1; i < dtMainSQLData.Rows.Count + 2; i++)
                {
                    for (int j = 1; j < dtMainSQLData.Columns.Count + 1; j++)
                    {
                        if (i == 1)
                        {
                            xlNewSheet.Cells[i, j] = dcCollection[j - 1].ToString();
                        }
                        else
                            xlNewSheet.Cells[i, j] = dtMainSQLData.Rows[i - 2][j - 1].ToString();
                    }
                }
             

                xlWorkbook.Save();
                xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
                xlApp.Quit();
            }
            finally
            {
                Marshal.ReleaseComObject(xlNewSheet);
                Marshal.ReleaseComObject(xlSheets);
                Marshal.ReleaseComObject(xlWorkbook);
                Marshal.ReleaseComObject(xlApp);
                xlApp = null;
            }
        }

Tuesday, March 4, 2014

ASP.NET MVC and KnockoutJS

In our Getting Started with KnockoutJS in ASP.NET MVC article, we started off with the intention of weaning web client devs away from hacking up the DOM and using client side ViewModels with Knockout as much as possible. We got some good questions regarding the article of which the main ones are:
1. Why do we have to get the empty View using the Get Action method and then do a second HTTP Get using AJAX after Document load to get the actual data? We’ll see one of the ways to avoid the second Get.
2. Why are we using jQuery’s $(element).on(…) to assign click handlers instead of having the click handler functions in the ViewModel itself. Well we can, so we’ll see how to do so.
3. Why did we disable AntiForgeryToken? Do we really need to make our code ‘insecure’ to use JavaScript based clients? Nope, we don’t have to make our code ‘insecure’, we’ll see how we can put the AntiForgeryToken back and use it to validate input.
Finally we’ll see how we can avoid manual mapping between the Server side ViewModel and Client Side ViewModel.
We start off with the code from the first article so you can download the code or fork the code on GithubThis article has been written by Sumit Maitra and I. 

Avoid doing a second AJAX GET to get Data as JSON

On way to send data to Client as JSON from the server is to serialize the Data as a JSON string, stick it in a ViewModel property and bind it to an HTML element (like a Hidden Field) or use Razor syntax to include the data in a Hidden field directly.
We’ll use the second technique today.

Changes in LookupsController

We update the Index action method to pass the list of Lookups into the ViewResult.
public ActionResult Index()
{
    return View(db.Lookups.ToList());
}
Just to ensure that we are not calling old code by mistake, we’ll comment out the GetIndex Action method too.

Updating the Index View

We put back the Model declaration on top of the View and add the Hidden Input variable that will save the JSON serialized Model.
@model IEnumerable<KnockoutSamples.Models.Lookup><title>Index</title>
<h2>Index</h2>
<input type="hidden" id="serverJSON"
value="@Newtonsoft.Json.JsonConvert.SerializeObject(Model)" />
<!-- rest of the markup -->
If you went through the first article carefully, you’ll realize this works because all Razor syntax is evaluated on the server when generating final HTML markup that’s sent back to the Browser. So here the @Newtonsoft.Json.JsonConvert.SerializeObject will be evaluated on the server for the data that we passed into the View(…) function in the Index Action method. So value of the hidden field will essentially end up with a long JSON string.

Updating the JavaScript to use the Hidden Field as the Data Source

We update the $(document).ready function to retrieve the data object from the Hidden Field instead of a AJAX call to the server. I’ve kept the code that we remove as commented and highlighted in gray. The code to convert the JSON string to JS object is highlighted in Yellow. Note the rest of the code remains the same.
$(document).ready(function () {
 //$.ajax({
//    type: "GET",
//    url: "/Lookups/GetIndex",
//}).done(function (data) {

var data = JSON.parse($("#serverJSON").val());$(data).each(function (index, element) {
  var mappedItem =
  {
   Id: ko.observable(element.Id),
   Key: ko.observable(element.Key),
   Value: ko.observable(element.Value),
   Mode: ko.observable("display")
  };
  viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
 //}).error(function (ex) {
//    alert("Error");
//});

//… Rest of the code
}
With that we are all done, if we run the application now, we’ll see the three default items come up in the Index.
If you run F12 dev tools, you’ll see that there is only one AJAX Get that’s made by Visual Studio’s browser link tech by the injected SignalR code.
knockout-ajax-get-server-side

Handling Edit, Update, Delete in ViewModel functions rather than external Event handlers

There were some protestations on why were we using jQuery ‘On’ function to attach Click event handlers for Edit, Delete etc. and it was suggested that we add the functions to the View Model and be done with it.
To Use KO View Model functions, we need to declare two more functions in the ViewModel. As you can see below, we’ve added two functions Edit and Update. KO automatically passes the data in current context, so we don’t have to extract it using ko.dataFor. The rest of the implementation is copied over from the older event handler.
$(data).each(function (index, element) {
var mappedItem =
{
  Id: ko.observable(element.Id),
  Key: ko.observable(element.Key),
  Value: ko.observable(element.Value),
  Mode: ko.observable("display"),
  Edit: function (current) {
   //var current = ko.dataFor(this);
   current.Mode("edit");
  },
  Update: function (current) {
   //var current = ko.dataFor(this);
   saveData(current);
   current.Mode("display");
  }
};
viewModel.lookupCollection.push(mappedItem);
});

Binding the Button Click handlers

We now have functions to handle the events but we need to assign them to the respective button’s click events. Since the new methods are a part of the View Model, we’ll use KO’s click binding in the markup.
The Edit Button:
<button class="btn btn-success kout-edit" data-bind="click: Edit">Edit</button>
The Update Button:
<button class="btn btn-success kout-update" data-bind="click: Update">Update</button>
If you run the app now, things will work as before. Pretty neat and doesn’t seem to be a troublemaker, so let’s keep it as is and go ahead!

Getting the Anti Forgery token back

We have covered what Anti Forgery tokens are and how they help prevent CSRF attacks here. We also saw how to use it in Web API services. So lets see how we can continue using it in our KO based app.
1. First we restore the AntiForgeryToken Razor syntax in the Index.cshtml. We add the following at the top of the page just below the @model declaration.
@Html.AntiForgeryToken()
This simply adds a Hidden field to the final HTML page.
2. Next we enable the Token Verification on the Controller method, so we uncomment the highlighted line below in the LookupsController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Lookup lookup)
{
if (ModelState.IsValid)
{
  db.Entry(lookup).State = EntityState.Modified;
  db.SaveChanges();
  return Json(lookup.Id);
}
return View(lookup);
}
3. If we try submitting now, we’ll get the AntiForgeryToken validation failed error. So finally, we update the saveData function in the knockout.samples.js. We make three simple changes:
a. Add the __RequestVerificationToken to the JS object that we are submitting on Save. The property name is so because that’s what MVC looks for in the submitted form and that also happens to be the name of the hidden field in which it is stored.
b. Change contentType to from-url-encoded
c. And finally since we are sending a url-encoded form, so we no longer JSON.stringify submitData and send the JavaScript object instead
function saveData(currentData) {
var postUrl = "";
var submitData = {
  Id: currentData.Id(),
  Key: currentData.Key(),
  Value: currentData.Value(),
  __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val()
};
if (currentData.Id && currentData.Id() > 0) {
  postUrl = "/Lookups/Edit";
}
else {
  postUrl = "/Lookups/Create";
}
$.ajax({
  type: "POST",
  contentType: "application/x-www-form-urlencoded",
  url: postUrl,
  data: submitData
}).done(function (id) {
  currentData.Id(id);
}).error(function (ex) {
  alert("ERROR Saving");
})
}
Okay, that’s three different questions solved and a different perspective towards using KO achieved.

Conclusion

Today we revisited some of the questions that rose in our previous article and explored some alternate techniques when using Knockout JS and ASP.NET MVC. We also saw how we could secure our application using the AntiForgery Token that we had ignored previously. In the next part of the series, we’ll step it up and learn more techniques using Knockout JS in near production scenarios.

Global.asax

Exploring the Global.asax file in ASP.NET
 
Have you ever felt the need of writing logic at the application level; precisely a location or a file where you could handle events or errors at the application level? Well if yes, then enter the Global.asax. Using this file, you can define event handlers with application-wide or session-wide scope. In this article, we will explore the application and session level events exposed in the Global.asax file and how we can utilize these events in our applications.
The Global.asax, also known as the ASP.NET application file, is located in the root directory of an ASP.NET application. This file contains code that is executed in response to application-level and session-level events raised by ASP.NET or by HTTP modules. You can also define ‘objects’ with application-wide or session-wide scope in the Global.asax file. These events and objects declared in the Global.asax are applied to all resources in that web application.
Note 1: The Global.asax is an optional file. Use it only when there is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected. External users cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET. You can deploy this file as an assembly in the \bin directory of an ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets invoked on each request and the second set which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization request.
Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.
Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
 
C#
 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error in: " + Request.Url.ToString() +
                          ". Error Message:" + objErr.Message.ToString();
       
    }
VB.NET
Sub Application_Error(ByVal sender As ObjectByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs       
        Dim objErr As Exception = Server.GetLastError().GetBaseException()
        Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:"& objErr.Message.ToString()
       
    End Sub
Here we make use of the Application_Error() method to capture the error using the Server.GetLastError().
Conclusion:
In this article, we learnt that Global.asax is a file used to declare application-level events and objects.The file is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End, and so on. I would encourage you to explore the methods corresponding to the events and analyze the best possible methods to use them in your application, if needed.
I hope you liked the article and I thank you for viewing it.

HTTP Handler

HTTP Handlers and HTTP Modules Overview

.NET Framework 4
36 out of 44 rated this helpful Rate this topic
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
This topic contains:
Typical uses for custom HTTP handlers include the following:
  • RSS feeds   To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
  • Image server   If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.
Typical uses for HTTP modules include the following:
  • Security   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
  • Statistics and logging   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
  • Custom headers or footers   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
HTTP handler and module features include the following:
  • The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
  • The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
  • Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
  • Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change. For more information, see Moving an ASP.NET Application from IIS 6.0 to IIS 7.0.
  • Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.
  • In IIS 7.0, the request pipeline is integrated with the Web server request pipeline. HTTP modules can be used for any request to the Web server, not just ASP.NET requests.

HTTP Handlers

An ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page handler.
The ASP.NET page handler is only one type of handler. ASP.NET includes several other built-in handlers such as the Web service handler for .asmx files.

Built-in HTTP Handlers in ASP.NET

ASP.NET maps HTTP requests to HTTP handlers based on a file name extension. Each HTTP handler can process individual HTTP URLs or groups of URL extensions in an application. ASP.NET includes several built-in HTTP handlers, as listed in the following table.
Handler
Description
ASP.NET page handler (*.aspx)
The default HTTP handler for all ASP.NET pages.
Web service handler (*.asmx)
The default HTTP handler for Web service pages created as .asmx files in ASP.NET.
Generic Web handler (*.ashx)
The default HTTP handler for all Web handlers that do not have a UI and that include the@ WebHandler directive.
Trace handler (trace.axd)
A handler that displays current page trace information. For details, see How to: View ASP.NET Trace Information with the Trace Viewer.

Creating a Custom HTTP Handler

To create a custom HTTP handler, you create a class that implements the IHttpHandler interface to create a synchronous handler. Alternatively, you can implement IHttpAsyncHandler to create an asynchronous handler. Both handler interfaces require that you implement the IsReusable property and the ProcessRequest method. TheIsReusable property specifies whether the IHttpHandlerFactory object (the object that actually calls the appropriate handler) can put the handler in a pool and reuse it to increase performance. If the handler cannot be pooled, the factory must create a new instance of the handler every time that the handler is needed.
The ProcessRequest method is responsible for processing individual HTTP requests. In this method, you write the code that produces the output for the handler.
HTTP handlers have access to the application context. This includes the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequestmethod of the appropriate handler. The code that you write in the handler's ProcessRequest method creates a response, which is sent back to the requesting browser.

Mapping a File Name Extension

When you create a class file as your HTTP handler, the handler can respond to any file name extension that is not already mapped in IIS and in ASP.NET. For example, if you are creating an HTTP handler for generating an RSS feed, you can map your handler to the .rss file name extension. In order for ASP.NET to know which handler to use for your custom file name extension, in IIS you must map the extension to ASP.NET. Then in the application, you must map the extension to the custom handler.
By default, ASP.NET maps the file name extension .ashx to an HTTP handler. If you add the @ WebHandlerdirective to a class file, ASP.NET automatically maps the .ashx file name extension to the default HTTP handler. This is similar to the way ASP.NET maps the .aspx file name extension to the ASP.NET page handler when the @ Pagedirective is used. Therefore, if you create an HTTP handler class that has the file name extension .ashx, the handler is automatically registered with IIS and ASP.NET.
If you want to create a custom file name extension for a handler, you must explicitly register the extension with IIS and ASP.NET. The advantage of not using the .ashx file name extension is that the handler is then reusable for different extension mappings. For example, in one application the custom handler might respond to requests that end in .rss. In another application, it might respond to requests that end in .feed. As another example, the handler might be mapped to both file name extensions in the same application, but might create different responses based on the extension.
The process for registering a handler's custom file name extension is different in IIS 7.0 and in earlier versions of IIS. For more information, see How to: Register HTTP Handlers and How to: Configure an HTTP Handler Extension in IIS.

Asynchronous and Synchronous HTTP Handlers

An HTTP handler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.
Asynchronous HTTP handlers enable you to start an external process, such as a method call to a remote server. The handler can then continue processing without waiting for the external process to finish. While an asynchronous HTTP handler is processing, ASP.NET puts the thread that would ordinarily be used for the external process back into the thread pool until the handler receives a callback from the external process. This can prevent thread blocking and can improve performance because only a limited number of threads can execute at the same time. If many users request synchronous HTTP handlers that rely on external processes, the operating system can run out of threads, because many threads are blocked and are waiting for an external process.
When you create an asynchronous handler, you must implement the IHttpAsyncHandler interface. You must also implement the BeginProcessRequest method in order to initiate an asynchronous call that processes individual HTTP requests. In addition, you must implement the EndProcessRequest method to run cleanup code when the process ends.

Custom IHttpHandlerFactory Classes

The IHttpHandlerFactory class receives requests and is responsible for forwarding a request to the appropriate HTTP handler. You can create a custom HTTP handler factory by creating a class that implements theIHttpHandlerFactory interface. A custom handler factory can give you finer control over how HTTP requests are processed by creating different handlers based on run-time conditions. For example, with a custom HTTP handler factory, you can instantiate one HTTP handler for a file type if the HTTP request method is PUT, and another if the method is GET.
To register a custom extension for a handler factory, follow the steps for registering a custom extension for a handler. For an example of creating and registering a handler factory, see Walkthrough: Creating and Registering HTTP Handler Factories.

HTTP Modules

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the request pipeline and have access to life-cycle events throughout the request. HTTP modules therefore let you examine incoming requests and take action based on the request. They also let you examine the outgoing response and modify it.
In IIS 6.0, the ASP.NET request pipeline is separate from the Web server request pipeline. In IIS 7.0, the ASP.NET request pipeline and the Web server request pipeline can be integrated into a common request pipeline. In IIS 7.0, this is referred to as Integrated mode. The unified pipeline has several benefits for ASP.NET developers. For example, it lets managed-code modules receive pipeline notifications for all requests, even if the requests are not for ASP.NET resources. However, if you want, you can run IIS 7.0 in Classic mode, which emulates ASP.NET running in IIS 6.0. For more information, see ASP.NET Application Life Cycle Overview for IIS 7.0.
ASP.NET HTTP modules are like ISAPI filters because they are invoked for all requests. However, they are written in managed code and are fully integrated with the life cycle of an ASP.NET application. You can put custom module source code in the App_Code folder of your application, or you can put compiled custom modules as assemblies in the Bin folder of an application.
ASP.NET uses modules to implement various application features, which includes forms authentication, caching, session state, and client script services. In each case, when those services are enabled, the module is called as part of a request and performs tasks that are outside the scope of any single page request. Modules can consume application events and can raise events that can be handled in the Global.asax file. For more information about application events, see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0 and ASP.NET Application Life Cycle Overview for IIS 7.0.
NoteNote
HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

How HTTP Modules Work

Modules must be registered to receive notifications from the request pipeline. The most common way to register an HTTP module is in the application's Web.config file. In IIS 7.0, the unified request pipeline also enables you to register a module in other ways, which includes through IIS Manager and through the Appcmd.exe command-line tool. For more information, see Configuring Handler Mappings in IIS 7.0 and Start Appcmd.exe.
When ASP.NET creates an instance of the HttpApplication class that represents your application, instances of any modules that have been registered are created. When a module is created, its Init method is called and the module initializes itself. For more information, see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0 and ASP.NET ASP.NET Application Life Cycle Overview for IIS 7.0.
In a module's Init method, you can subscribe to various application events such as BeginRequest or EndRequest by binding the events to methods in the module.
NoteNote
For modules that operate in the IIS 7.0 integrated pipeline, you should register event handlers in the Initmethod.
When application events are raised, the appropriate method in your module is called. The method can perform whatever logic is required, such as checking authentication or logging request information. During event handling, the module has access to the Context property of the current request. This enables you to redirect the request to an alternative page, modify the request, or perform any other request manipulation. For example, if the module checks authentication, the module might redirect to a login or error page if the credentials are not correct. Otherwise, when the module's event handler has finished running, ASP.NET calls the next process in the pipeline. This might be another module or might be the appropriate HTTP handler (such as an .aspx file) for the request.

HTTP Modules versus Global.asax Files

You can implement much of the functionality of a module in the application's Global.asax file, which enables you to respond to application events. However, modules have an advantage over the Global.asax file because they are encapsulated and can be created one time and used in many different applications. By adding them to the global assembly cache and registering them in the Machine.config file, you can reuse them across applications. For more information, see Global Assembly Cache.
NoteNote
In IIS 7.0, the integrated pipeline enables managed modules to subscribe to pipeline notifications for all requests, not just requests for ASP.NET resources. Event handlers in the Global.asax file are invoked only for notifications during requests for resources in the application. Custom modules in Integrated mode can be explicitly scoped to receive event notifications only for requests to the application. Otherwise, custom modules receive event notification for all requests to the application. If the precondition attribute of theadd element of the modules section is set to "managedHandler", the module is scoped to the application.
The advantage of using the Global.asax file is that you can handle other registered events such as Session_Startand Session_End. In addition, the Global.asax file enables you to instantiate global objects that are available throughout the application.
You should use a module whenever you must create code that depends on application events, and when the following conditions are true:
  • You want to re-use the module in other applications.
  • You want to avoid putting complex code in the Global.asax file.
  • The module applies to all requests in the pipeline (IIS 7.0 Integrated mode only).
You should add code in the Global.asax file whenever you must create code that depends on application events and you do not have to reuse it across applications. You can also use the Global.asax file when you have to subscribe to events that are not available to modules, such as Session_Start.

Creating an HTTP Module

The general process for writing an HTTP module is as follows:
For information about how to move a module from an application that is running in IIS 6.0 or earlier versions to an application that runs on in IIS 7.0, see Moving an ASP.NET Application from IIS 6.0 to IIS 7.0.

QuickStarts

How to and Walkthrough Topics


Implementing HTTPHandler and HTTPModule in ASP.NET

By 27 Feb 2012

Introduction

This article aims at understanding the role of HTTPHandler and HTTPModule in ASP.NET applications. We will try to work on a basic example to see how these can be implemented.

Background

ASP.NET handles all the HTTP requests coming from the user and generates the appropriate response for it. ASP.NET framework knows how to process different kind of requests based on extension, for example, It can handle request for .aspx.ascx and .txt files, etc. When it receives any request, it checks the extension to see if it can handle that request and performs some predefined steps to serve that request.
Now as a developer, we might want to have some of our own functionality plugged in. We might want to handle some new kind of requests or perhaps we want to handle an existing request ourselves to have more control on the generated response, for example, we may want to decide how the request for .jpg or .gif files will be handled. Here, we will need an HTTPHandler to have our functionality in place.
There are also some scenarios where we are ok with the way ASP.NET is handling the requests but we want to perform some additional tasks on each request, i.e., we want to have our tasks execute along with the predefined steps ASP.NET is taking on each request. If we want to do this, we can have HTTPModule in place to achieve that.
So from the above discussion, it is clear that HTTPHandlers are used by ASP.NET to handle the specific requests based on extensions. HTTPModule, on the other hand, is used if we want to have our own functionality working along with the default ASP.NET functionality. There is one Handler for a specific request but there could be N number of modules for that.

Using the Code

Let us try to understand these two concepts by writing a small application for each. What we will do is we will try to have a mechanism where we can process the web pages with extension like .bspx and .cspx. Although this is a very unrealistic scenario, a similar concept is used to have search engine friendly URLs so perhaps it's not that realistic either.
Note: The HTTPHandler example here is just for demonstration purpose, I am not recommending the use ofHTTPHandlers for something that I am about to do now. HTTPHandlers should ideally be used to customize the handling of existing MIME types and not for serving search engine friendly URLs or non standard URLs.

Implementing the HTTPHandler

So with our problem definition, let us try to see how we can handle the request for .cspx pages usingHTTPHandlers. First we need to have the handler class with us, so let us create the handler class.
public class CspxHandler :IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {

    }
}
The class should have a method ProcessRequest and a property called IsReusable. The property tells whether this handler can be reused or not and the method will be called whenever a request for that type comes. But wait, Where have we defined the type of request where this handler should be invoked? This can be defined either in IIS, if we have a handler common to all the sites running on that server or we can configure it in web.config file, if the handler is specific for a website. Let's do that in web.config file for now.
<httpHandlers>
    <add verb="*" path="*.cspx" type="CspxHandler"/>
</httpHandlers>
Here we registered our handler to specify that if any request for .cspx file comes, it should be forwarded to our handler.
Now, since we don't have any "real" files with .cspx extension, what we will do is we will handle the request for.cspx and in turn push the user to the corresponding .aspx file.
public class CspxHandler :IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.RawUrl.Contains(".cspx"))
        {
            string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");
            context.Server.Transfer(newUrl);
        }
    }
}
Whenever a request for .cspx file comes, we will handle it in our handler and show the corresponding .aspx file instead. Let's see how it works.
Note: I have also changed the startup page name to Default.cspx but there is no page like that. I want my handler to handle that and show me the actual default page.
Important: I reiterate, This example is just for illustration. This is not how HTTPHandlers should be used at all. HTTPHandlers should ideally be used to customize the handling of existing MIME types.
Well the pages seems to be working fine and the user will see .cspx URL for his request. But there is one problem. The way we wrote our handler is not good to handle the postback. If I add a button on any of these pages and do a postback, the original URLs will be visible. So it is not a good solution to the problem but it sure demonstrated the way Handlers can be used.

Implementing the HTTPModule

How do we solve the problem we just saw. Well, our application needed URL rewriting and HTTPHandlers are a bad solution for that and should never be used for that. So perhaps the guys using this technique to have search friendly URLs should rethink their strategy. SO how can we solve this problem really.
Let us look at the requirement again, All we needed was to show the user URLs which are different than the real URLs and process the real URLs internally. So we don't need custom handlers, we are ok with the way ASP.NET engine is handling these requests but we need custom activities to be done during the processing phase. So it looks like we can solve it using HTTPModule.
So let's go ahead and write an HttpModule that will:
  1. Check for file extension on request.
  2. If it finds a .bspx extension it changes it to .aspx (or find real URLS if we are implementing search friendly URLs)
  3. It will pass the request to the default handler, since the page is still aspx.
  4. Once the response is generated, it will write back the original .bspx URL to users browser.
public class MyBModule : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        context.EndRequest += new EventHandler(context_EndRequest);
        context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
    }

    void context_AuthorizeRequest(object sender, EventArgs e)
    {
        //We change uri for invoking correct handler
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
        {
            string url = context.Request.RawUrl.Replace(".bspx", ".aspx");
            context.RewritePath(url);
        }
    }

    void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        //We set back the original url on browser
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Items["originalUrl"] != null)
        {
            context.RewritePath((string)context.Items["originalUrl"]);
        }
    }

    void context_EndRequest(object sender, EventArgs e)
    {
        //We processed the request
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        //We received a request, so we save the original URL here
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
        {
            context.Items["originalUrl"] = context.Request.RawUrl;
        }
    }
}
Also we need to register our module so that it can be invoked, we will do that in our web.config file.
<httpModules>
    <add name="MyBModule" type="MyBModule" />
</httpModules>
And now let's run the application:
So here we solved the problem of URL reverting back to the original on postback. This is also the ideal way of doing that.

Points of Interest

In this article, we saw how we can implement a basic HTTPHandler and HTTPModule. We saw each of their roles in page processing frameworks. We worked on an example that tried to solve the URL rewriting first the wrong way by using HTTPHandler (but we understood how to write HTTPhandler) and then the right way of doing URL rewriting using HTTPModule (we got to understand that too.
The emphasis of this article was solely on understanding how we can have HTTPHandlers and HTTPModulesworking. The example is a little unrealistic and perhaps a little misleading too but since I made that point really clear, it shouldn't be a problem.
Before wrapping up, there is one last thing that we should know about handlers. It is also possible to handle the request asynchronously. ASP.NET provides a mechanism for creating asynchronous handler and then increases the performance of a web page (implements the IHttpAsyncHandler do that).