Archive for the ‘ASP.NET’ Category

ASP.NET WEB API – What and Why

Hi Friends,

Microsoft has introduced a helpful framework with ASP.NET MVC4 called WEB API for building the http based services.

In this article we will cover following points about this new framework


WHAT Web API is an api which helps in creating the http based client and server endpoints on top of the framework.

The Client side http based programming model has been built in to the and the server side http based programming model has been built in to the WCF.

The First version of WCF did not support the Http based services.
It strongly supported the traditional Soap based service endpoints which really lack in the many other features in http like caching , compression etc.

With the release of the .NET Framework 3.5 in November 2007, Microsoft released the feature to create the simple http based endpoints but it was again more embedded in the WCF.

So Microsoft WCF team has decided to come up with the framework which is completely used for the http based services ,
As ASP.NET team is more engage in the web / http  work , routing , html Microsoft has decided to merge this framework with the ASP.Net
and introduced WEB API with the ASP.NET MVC 4 release.


If we are implementing an application whether html 5 or mobile , they need services for accessing data or to artifact the system.
In the modern programming land scape services should be created by keeping wide range of clients in mind.

Most of the applications are accessing data as JSON using HTTP based services which is going to be a trend than accessing data from traditional Soap services.


This article is the summary of the video by Jon Flander on the pluralsight website.

please refer for details of web api.



Ganesh Divekar


ASP.NET – Call Synchronous Method Asynchronously using C# ,.net (Fire and forget pattern)


Hi Friends,

Many times we come across a situation when we need to call a method asynchronously and don’t want to wait till it completes its execution.


Call Method Asynchronously
  1. class Program
  2.     {
  3.         public delegate void AsyncMethodCaller(int Application_Type_Id);
  5.         public static void AsynchronousMethod(int Application_Type_Id)
  6.         {
  7.             Console.WriteLine("My Application_Id is {0}",Application_Type_Id);
  9.         }
  10.         static void Main()
  11.         {        
  12.            AsyncMethodCaller caller = new AsyncMethodCaller(AsynchronousMethod);
  13.            IAsyncResult result = caller.BeginInvoke(1, null, null);
  14.            Console.Read();
  16.         }
  18.     }


For Example In the above code, if I want to call AsynchronousMethod() and not wait for it to finish executing? In fact, to make things interesting, what if I didn’t care when it is finished?

Let’s say, I just wanted to call AsynchronousMethod() without waiting for any of the function calls to complete. Basically, doing something called Fire and Forget. You call the function, you don’t wait for it, and you just forget about it.

Note :

* BeginInvoke() is the line of code that executes the AsynchronousMethod() function. However, the control is returned to the caller right away, without waiting for AsynchronousMethod() to complete.

* The code above does not know when a call to AsynchronousMethod() completes.

* BeginInvoke() is used instead of Invoke(). For now, don’t worry about the parameters this function takes; I will cover that in more detail later.


How .NET works in background to make this Possible?

Once you ask the framework to call something asynchronously, it needs a thread to do the work. It can not be the current thread, because that would make the invocation synchronous (blocking). Instead, the runtime queues a request to execute the function on a thread from the .NET Thread Pool. You don’t really need to code anything for it, all of it happens in the background. But, just because it is all transparent doesn’t mean you should care about it. There are a few things to remember:

* AsynchronousMethod() is executed on a separate thread, a thread that belongs to the .NET Thread Pool.

* A .NET Thread Pool contains threads in it , and each time AsynchronousMethod() is called, it is going to be executed on one of these threads. You can’t control which one.

* The Thread Pool has its limits! Once all the threads are used, an async method invocation is queued until one of the threads from the pool is freed. This is called Thread Pool Starvation, and normally when it comes to that, performance is compromised.



Hope this Helps!!!!!!Smile

Categories: ASP.NET

ASP.NET–What is ISAPI ?/What is CGI?/ Advantage Of ISAPI Over CGI

January 24, 2012 3 comments

Hi Geeks ,

In this article we will see the Advantage of ISAPI (Internet Server Application Provide Interface) over CGI(Common Gateway Interface).

* What is ISAPI?

It is an API developed to provide the application developers with a powerful way to extend the functionality of IIS.

ISAPI consists of two components:

Extensions and Filters:

These are the only two types of applications that can be developed using ISAPI. Both Filters and Extensions must be compiled into DLL files which are then registered with IIS to be run on the web server.

Extensions                                                                                                                              An ISAPI server extension is a DLL that can be loaded and called by an HTTP server. Internet server extensions, also known as Internet server applications (ISAs), are used to enhance the capabilities of an Internet Server API (ISAPI)-compliant server. An ISA is invoked from a browser application and provides similar functionality to a Common Gateway Interface (CGI) application

Advantages of ISAPI Server Extensions

Users can fill out forms and click a submit button to send data to a Web server and invoke your ISA, which can process the information to provide custom content or store it in a database. Web server extensions can use information in a database to build Web pages dynamically, and then send them to the client computers to be displayed. Your application can add other custom functionality and provide data to the client using HTTP and HTML.

Both server extensions and filters run in the process space of the Web server, providing an efficient way to extend the server’s capabilities.


An ISAPI filter is a DLL that runs on an ISAPI-enabled HTTP server to filter data traveling to and from the server. The filter registers for notification of events, such as logging on or URL mapping. When the selected events occur, the filter is called, and you can monitor and change the data (on its way from the server to the client or vice versa). ISAPI filters can be used to provide enhanced logging of HTTP requests (for example, to track who is logging on to your server), custom encryption, custom compression, or additional authentication methods.

Common ISAPI applications

This is a list of common ISAPI applications implemented as ISAPI extensions:

  • Active Server Pages (ASP), installed as standard
  • Asp.Net, installed as standard on IIS 6.0 onwards
  • PHP, available for free to install.
    * What is CGI?

It is a gateway for transferring information between a World Wide Web server and a CGI program.

A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program could be written in any programming language, including C, Perl, Java, or Visual Basic or ASP.NET.

CGI programs are the most common way for Web servers to interact dynamically with users. Many HTML pages that contain forms, for example, use a CGI program to process the form’s data once it’s submitted. Another increasingly common way to provide dynamic feedback for Web users is to include scripts or programs that run on the user’s machine rather than the Web server. These programs can be Java applets, Java scripts, or ActiveX controls. These technologies are known collectively as client-side solutions, while the use of CGI is a server-side solution because the processing occurs on the Web server.

* ISAPI over CGI

->The Internet Server Application Programming Interface (ISAPI) model was developed as a faster alternative to the Common Gateway Interface (CGI).

->ISAPI provides a number of advantages over CGI, including lower overhead, faster loading, and better scalability. T

->The chief difference between the CGI and ISAPI programming models is how processing is handled.

With CGI, the system creates a unique process for every request. Each time an HTTP server receives a request, it initiates a new process. Because the operating system must maintain all these processes, CGI requires many of resources. This inherent limitation makes it difficult to develop responsive Internet applications with CGI.

With ISAPI, requests do not require a separate process. Threads are used to isolate and synchronize work items, resulting in a more efficient use of system resources.


Categories: ASP.NET

Authenticate Multiple Applications using Single Forms Authentication in ASP.NET / Form Authentication Across multiple Applications

Hi Geeks,

Today I came across a situation where i needed to authenticate more than 3 applications using single forms Authentication , I had  the structure of my applications on IIS as follows :



As you see in the above Hosting Structure I have one Main Login Application and

I have to authenticate the application 1,2,3 from the MainLogin application which is at root level and rest of the applications are on sub roots.

At start i thought it would be very critical to do this but Microsoft made it so easy that it wont take so much efforts.

First You need to add the following code to Web.Config file the  MainLogin Application

  1. <authentication mode="Forms">
  2.       <forms loginUrl="login.aspx"></forms>
  3.     </authentication>
  5.     <machineKey validationKey="45AC1CA923F4DC8E5AE294064AFD7810FFB178B21D747B32D3A4765BFA27F892318589A59F09B08C704051504D74969F2EDADBD51CE489343C2A3CF834DEA9D6"
  6.                 decryptionKey="917CF306390024BBDBC94817A22506FDB19123D88D159B524345CB4022895BB8" validation="SHA1"
  7.                 decryption="AES" />


-> Important Note : Dont Ignore…

Paste the same code to the Web.Config file of all the applications with same machine key,validation key,deception key otherwise it wont work.

If you are adding other forms authentication parameters like name ,Protection,path,domain,timeout , you should add same parameters with same values in Web.Config file of all applications.

To Configure the Machine key for the application see Configure Machine key

-> So the main Question here is HOW did it WORK????

1) Whenever user sends  request to the server it always checks for the .ASPXAUTH Cookie.

Note : .ASPXAUTH Cookie is the cookie which is generated by the the logon page creates a cookie that contains a forms authentication ticket that is set for the session only if you are using  ASP.NET inbuilt Login Control otherwise you need to generate the ticket using following code

Add Authentication Ticket
  1. if (Membership.ValidateUser(userName.Text, password.Text))
  2. {
  3.     if (Request.QueryString["ReturnUrl"] != null)
  4.     {
  5.         FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
  6.     }
  7.     else
  8.     {
  9.         FormsAuthentication.SetAuthCookie(userName.Text, false);
  10.     }
  11. }
  12. else
  13. {
  14.     Response.Write("Invalid UserID and Password");
  15. }

So whenever user successfully log in using Main Login Application it will generate the .ASPXAUTH Cookie with Forms Authentication Ticket which contains all the credentials for the authentication and this cookie is used by the other applications to start their authenticated session.


Hope This Will Help You Smile

Categories: ASP.NET

Internet Information Services (IIS) 7 Application Pools / Types of Application Pools/Difference between Integrated and Classic Application Pool.

December 6, 2011 3 comments

Hi Geeks,

Today , I got a chance to host a ASP.NET application on IIS , and i learnt the advantage of Application pool of IIS in deep.

In this article we will see how application pool works and their types :

Application Pool

The application Pools element contains configuration settings for all application pools running on your Internet Information Services (IIS) 7 server. An application pool defines a group of one or more worker processes, configured with common settings that serve requests to one or more applications that are assigned to that application pool. Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer. Process boundaries separate each worker process; therefore, application problems in one application pool do not affect Web sites or applications in other application pools. Application pools significantly increase both the reliability and manageability of your Web infrastructure.

You can choose to use the default application pool provided by IIS on install, or you can create your own application pool. You can run as many application pools on your IIS 7 server as you need, though this can affect server performance. Application pools can contain one or more worker processes. Each worker process represents work being done for a Web site, Web application, or Web service. You can create a Web garden by enabling multiple worker processes to run in a single application pool.

In IIS 7, each application pool uses one of two .NET integration modes for running ASP.NET applications: Integrated or Classic. The .NET integration mode defined for the application pool determines how IIS processes an incoming request to the sites, applications and Web services that run in that application pool.

Types of Application Pools

There are two types of application pools

1) Integrated  (default)

2) Classic


Integrated mode allows IIS to process requests in the application pool by using the IIS 7 integrated pipeline. This allows ASP.NET modules to participate in IIS request processing regardless of the type of resource requested. Using integrated mode makes available features of the ASP.NET 2.0 request pipeline available to requests for static content, as well as ASP, PHP and other content types. By default, IIS 7 application pools run in this mode.

Classic mode uses the IIS 6.0 processing pipeline for hosting ASP.NET applications. In this mode, requests are processed initially through IIS 7 modules, and ASP.NET requests are further processed by the aspnet_isapi.dll. The ASP.NET processing pipeline is separate from the IIS 7 processing pipeline, and the ASP.NET request processing pipeline features are not available to other resource types. This also means that an ASP.NET request must pass through authentication and authorization modules in both process models. While this is not as efficient as Integrated mode, it does allow you to run applications developed using ASP.NET version 1.1 on an IIS 7 server without modifying the application to run in Integrated mode.


Categories: ASP.NET

ASP.NET – Create controls dynamically in using JavaScript and JavaScriptSerializer. [Part II]

November 29, 2011 3 comments

Hi Geeks,

In our last post Create Controls dynamically in ASP.NET using Hidden Field .In this article we will see how to create controls dynamically using JavaScript and JavaScriptSerializer.


We have our HTML view as follows

<form id="form1" runat="server">
    <input id="btnAdd" type="button" value="add" onclick="AddTextBox()" />
    <br />
    <br />
    <div id="TextBoxContainer">
        <!--Textboxes will be added here -->
    <br />
    <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="Post" />
which looks on browser as follows

-> Now on add button click we have to add the text boxes dynamically and on post we have to preserve the text boxes and their values.

-> We use JavaScript and JavaScriptSerializer to do this.

We have our JavaScript Code as follows

 <script type="text/javascript">

GetDynamicTextBox(value)  {           

 return ‘<input name = "DynamicTextBox" type="text" value = "’ + value + ‘" />’ +     ‘<input type="button" value="Remove" onclick = "RemoveTextBox (this)" />’ 

        function AddTextBox() {

            var div = document.createElement(‘DIV’);

            div.innerHTML = GetDynamicTextBox("");



        function RemoveTextBox(div) {



        function RecreateDynamicTextboxes() {

            var values = eval(<%=Values%>);

            if (values != null) {

                var html = "";

                for (var i = 0; i < values.length; i++) {

                    html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";


                document.getElementById("TextBoxContainer").innerHTML = html;



        window.onload = RecreateDynamicTextboxes;


-> As you see in above code we use AddTextBox method to create the text box on Add button click.

-> As well as we have called method  RecreateDynamicTextboxes on window load event because dynamic controls disappears on post as we saw in last post.

-> The RemoveTextbox method called on remove button on click event to remove the buttons

on clicking add button we will have out put as follows


Problem of Dynamic Controls on Page Post Backs :

-> Retrieving/Preserving the textbox values at server side on Page Post

Its very easy to create the dynamic controls but it is not that much easy to take their values at server side on post.                                                                                                                


As we are creating the control dynamically they disappears when page post backs so we also need to take care of this condition and we need to re create the controls when page post backs

-> Solution:

We use JavaScriptSerializer to save the textbox values.

Code on the Server side on Page_Load event is as follows

protected string Values;

protected void Page_Load(object sender, EventArgs e)


      string[] textboxValues = Request.Form.GetValues("DynamicTextBox");

      JavaScriptSerializer serializer = new JavaScriptSerializer();

      this.Values = serializer.Serialize(textboxValues);


Categories: ASP.NET

ASP.NET – Create controls dynamically in and preserving the controls and their values on post back using Hidden Field . [Part I]

November 28, 2011 2 comments

Hi Geeks,

Many times while working with ASP.NET Web forms we come across the situation where  we need to add the controls like Text Box,labels dynamically.

In this post we will see an example where we add multiple Text Box control dynamically to the Web Form.

Suppose we  have the HTML of our Web Form as follows


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<script type="text/javascript">
function onClickOfButton() { 

   var textBoxValues = "";





asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
asp:Button ID="Button1" runat="server" Text="CreateDynamic Control"   

     OnClick="Button1_Click" />

asp:Button ID="Button2" runat="server" Text="Post" OnClick="Button2_Click"
OnClientClick="onClickOfButton();" />
table id="tblDynamic" runat="server">

    <asp:HiddenField ID="hdField" runat="server" />


  The output of the Html above is as this image



->We take input from the user , to create number of text boxes and onClick of the    CreateDynamicControl button we will add the textboxes to the tblDynamic

Code on the  CreateDynamicControl  button_Click event will be as follows

    //CreateDynamic Control click
protected void Button1_Click(object sender, EventArgs e)

       private void CreateControls()
           int number_Of_Controls = Convert.ToInt32(TextBox1.Text);
           HtmlTableRow Row = new HtmlTableRow();
           for (int i = 0; i < number_Of_Controls; i++)
               TextBox txt1 = new TextBox();
               txt1.ID = "txtDynamic_" + i.ToString();
               HtmlTableCell cell = new HtmlTableCell();


User gives input as 3 and three textboxes will be generated on click event as follows,

we insert values 11,22,33 in those fields.



Problem of Dynamic Controls on Page Post Backs :

Retrieving/Preserving the textbox values at server side on Page Post

Its very easy to create the dynamic controls but it is not that much easy to take their values at server side on post.                                                                                                                


As we are creating the control dynamically they disappears when page post backs so we also need to take care of this condition and we need to re create the controls when page post backs


->For this we have taken the Hiddenfield “hdField”  as u see in above html code                      and onPost we save the values of textboxes in the hidden filed through JavaScript function  name “onClickOfButton”

->  code on server side will be as follows

//on post click 
protected void Button2_Click(object sender, EventArgs e)

->Note the  function setValues can be called on any server side event which make page PostBack.

     private void setValues()
          int number_Of_Controls = Convert.ToInt32(TextBox1.Text);
          HtmlTableRow Row = new HtmlTableRow();

//retrieving the values of textboxes

 string[] arr = hdField.Value.Split(new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries);
          for (int i = 0; i < number_Of_Controls; i++)
              TextBox txt1 = new TextBox();
              txt1.ID = "txtDynamic_" + i.ToString();
              txt1.Text = arr[i];
              HtmlTableCell cell = new HtmlTableCell();


After Post Back we have our webpage as follows which shows that or dynamic controls values have been preserved after successful page postback.



Categories: ASP.NET