How to set automatically focus on ASP.NET controls when validation fails ?

If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.

To set focus automatically you  have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError  of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically  move to the control which is specified in ControlToValidate.

SetFocus

Continue reading

How to sort ASP.NET DropDownList based on DataValueField or DataTextField using LINQ?

Sorting ASP.NET Dropdown list is very common requirement for any of the web application development.  To Implement this features sometimes developers used to iterate through each and every item and create a sorted list of element then reassign the same source to dropdownlist or sort the element at source itself. But this thing can be done easily using LINQ. In this post I am going describe how you can sort a ASP.NET DropDownList based on either of DataTextField or DataValueField using LINQ and list of KeyValuePair elements as DataSource.

To start with the application, let’s consider you have following List of employee data as datasource of the DropDownList.

 /// <summary>
 /// Create List Of Employee
 /// </summary>
 List<KeyValuePair<int, string>> employees = new List<KeyValuePair<int, string>>
        {        new KeyValuePair<int,string>(1,"Abhijit"),
                  new KeyValuePair<int,string>(2,"Rahul"),
                  new KeyValuePair<int,string>(3,"Kunal"),
                  new KeyValuePair<int,string>(4,"Atul"),
                 new KeyValuePair<int,string>(5,"Abhishek"),
        };
 

In the employee list collection, you have added KeyValuePair for each element, where Key is employee ID and Value is the employee name.  The most interesting part of using KeyValuePair is you can bind either of Key or Value with the DropDownList as per your requirement

Now let’s bind the DropDownList with the DataSource

Continue reading

How to pass external values with GridView HyperLinkField which are not part of your Gridview DataSource member ?

Few days back I have published an article “How to pass multiple values using GridView HyperLinkField ?”,  where I have explained how you can pass multiple parameter with Gridview HyperLinkField using DataNavigationUrlField and  DataNavigateUrlFormatString properties. In this post, I am going to explain how you can pass some external values as parameters with the same hyperlink field.

DataNavigationUrlField use only those  fields as parameter which are the part of GridView DataSource. Now the problem comes when you want to pass some other variables as parameter which are not part of the DataSource.  As shown in below image we are passing EmpID and ParentId as argument and this two field are the data member of GridView DataSource.

GridField

Now Say, You want pass ChildID for that particular record along with ParentID and EmpID and you want hyperlink url should be like “Default.aspx?EmpID=1&ParentID=P1&ChildID=C1”where ChildID is not part of datasource.

You can achieve  this by writing code in code behind for the particular GridView. There is two events where you can overwrite the navigation url of that hyperlink field. You can use  Gridview_RowDataBound or Gridview_PreRender for the same.

Continue reading

How to pass multiple values using GridView HyperLinkField ?

While working with GridView in ASP.NET, most of the time we used HyperlinkField column to navigate from one page to  different page with some value as argument.  In this blog post I have explained how can we pass multiple parameter with HyperLinkField in GridView.

To implement this features you need to know about  DataNavigationUrlField and  DataNavigateUrlFormatString properties of HyperLinkField. Let’s assume that you have a gridview as given below and you have already bind the datasource from code behind.

 <asp:gridview id="GrdEmp">
<columns runat="server" autogeneratecolumns="False" cellpadding="4">
<asp:boundfield datafield="ID" headertext="ID" />
<asp:boundfield datafield="Name" headertext="Name" />
<asp:boundfield datafield="ParentID" headertext="Base ID" />
</columns>
</asp:gridview>

Let’s first consider the case of passing single parameter. First thing that you need to do is, add a GridView “HyperLinkField “ column. After that you need to set the DataNavigationUrlField  and DataNavigateUrlFormatString properties for the same . In DataNavigationUrlField  you have to mention the name of the DataField which you want to bind as querystring. In DataNavigateUrlFormatString  you have to give the formatted URL String for the Navigation. The concept is same here as like FormatString the only difference is the data is coming from DataNavigationUrlField . Continue reading

Identifying Worker Process (w3wp.exe) – IIS 6.0 and IIS 7.0 for Debugging ASP.NET Application

If you are debugging a ASP.NET web application which is hosted on IIS, you need to attach the particular worker process in Visual Studio to start debugging. To Attach a process we can go to Tools > Attach Process or use shortcut key Ctrl +P. The process window will show the worker process (w3wp.exe) which is currently running on IIS. You need to select the process and click on attach button to start the debugging.
Problem starts when you have multiple worker process running on IIS.  If you have multiple sites hosted on IIS and each site having their own application pool then you will see the list of all worker process in the Process Attach window.


Here  you need to identify the particular worker process which is associated with your application pool.

Note: Whenever we create a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS (Kernel Level of IIS) . So whenever HTTP.SYS Received the request from any web application,  it checks for the Application Pool and based on the application pool it send the request Continue reading

How to pass ASP.NET server side array to client side and binding them with Html element?

This is a very often requirement for an ASP.NET Developer to pass a sever side array to client side and access them through java Script. There are several ways to do that. But here I am describing one of the simplest steps to pass server side array to client side. In this blog post you will get to know two things, first one is the how to pass the array from server side to client side and second one is the how to bind that array to an empty “html dropdown” list.

Well, the easiest way to pass the server side array to a client side is  using  “RegisterArrayDeclaration” . RegisterArrayDeclaration method registers a javascript array with the System.Web.UI.Page Object. As the array object registered with the “Page” object so we can access it from javascript easily. RegisterArrayDeclaration takes array name and value of the array element as argument.

In below example, I have registered one array with name of “Skills”.

  protected void Page_Load(object sender, EventArgs e)
    {
       // Register List of Languages
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C#'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'VB.NET'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C++'");
    }

Now, what above declaration does?  This is nothing but a declaration of a java script array like,

Var Skills = new Array('C#', 'VB.NET','C','C++');

These “Skills” array is now only a JavaScript array which is easily accessible by client side code. Now Let’s have a look how to access them and how to bind them in a dropdown list. Continue reading

How to update controls which are outside of updatepanel during partial page rendering?

we generally used update panel to do the partial page postback, which means to postback the controls which are only inside the update panel. For achieve this we simply call Update() method for the corresponding Update Panel. This thing is quite simple when we are trying to update any control which is inside the updatepanel itself. But, The problem may come when we want to update the controls which are outside of UpdatePanel and we need to update the same while updating then control inside updatepanel.

To make it simple. Let’s consider below scenarios. In our web page, we have Two labels (Label1 and Label2). Lable1 present inside the updatePanle and Label2 is in the outside of updatePanel. We have one Button say Button1, which is also inside the UpdatePanel. Now, our requirement is to update the Label2 while we are updating Label1 by Clicking Button1.

below is the code block for above scenarios

      <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode=Conditional>
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <asp:Button ID="Button1" runat="server" Text="Update Button"  onclick="Button1_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
     <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

Now, if we click on “Button1″, it will update only the content of Label1 not Lable2.

The solutions is to use ScriptManager.RegisterDataItem() . Using RegisterDataItem() methods we can register any control with the Particular Page ScriptManager Instance. While registering we need to provide the Control name along with the data item for the control which we want to render. Continue reading

How to get list of all active HttpModules in ASP.NET?

Here is a quick tips to get the list of all active HTTPModules at runtime.  We can get the list of all HttpModules from the web.config or from machine.config file. But, what we need to do if we want to get the list of all active HttpModules during runtime? Yes. We can easily get the details with the help of  HttpApplication and HttpModuleCollection Class. If we quickly recall the IIS Process Request [One detailed Article], when a request reaches to worker Process from client browser, First of all Worker process is responsible to start and HttpRuntime by loading ISAPI filter. After that HttpRuntime load an HttpApplication object with the help of  HttpApplicationFactory class. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication. Below is the code snippet by which we can get the list of active HttpModules.

        //Get Application Instance from Current Content
        HttpApplication httpApps = HttpContext.Current.ApplicationInstance;
        //Get List of modules in module collections
        HttpModuleCollection httpModuleCollections = httpApps.Modules;
        Response.Write("Total Number Active HttpModule : " + httpModuleCollections.Count.ToString() + "</br>");
        Response.Write("<b>List of Active Modules</b>" + "</br>");
        foreach (string activeModule in httpModuleCollections.AllKeys)
        {
            Response.Write(activeModule + "</br>");
        }

Below is the sample output :

This can be quite useful when we want to check if our custom created  module loaded successfully or not .

Shout it

“CompressionEnabled” Session in ASP.NET 4.0

Session is the most important state management mechanism for a web application. In ASP.NET we are having two type of state management

1. In Process

2. Out Process

In process” is the by default session storage mode for ASP.NET Web application. When it comes under Out Process we can use either of state server or SQL Server to persist our session data.

Here I am going to describe one new features added in ASP.NET 4.0 realted with Session. If you want to know about when to use session, what session mode to use, how to configure the session storage please read one of my article “Exploring Session in ASP.NET” published at CodeProject.

In case of In Process, session data stored in In memory of worker process. But when we are talking about “OutProc” session mode, we need to ensure that session data should be “Serialized” first  . So, when we are moving session data from Web Server to Out Process Server ( State Server or SQL Server ) it can be a performance overhead based on the size of data that we are stroing in Session.

ASP.NET 4.0 comes us with a new option for compressing the Session data with Out Process Session mode. To enabling this functionality we need to add “compressionEnabled=”true” attribute with the SessionMode in web.config . Web.config entry would be look like below,

<sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI; data source=.;" <em>compressionEnabled="true" </em>allowCustomSqlDatabase="true">

This will compress / Decompress the session data during serialization / deserialzation of session data. ASP.NET 4.0 used System.IO.Compression.GZStream class to compress the session mode. One more important things to remember that use of compression mode is useful when we are storing large number of data in session because for every request it will going to use Gzip Compression/ Decompression going to be used to access the session variable.

Hope this will helps you !

Shout it

CSS Friendly Menu Control in ASP.NET 4.0


It is very much easier to apply CSS when we have ul,li elements as the HTML content. If we look into ASP.NET Menu Control till Version 3.5, its render as Table-TR-TD Tag. Though Table/Tr/Td is quite useful to display tabular data but sometime  creates  a big problem when we need to do more work with CSS. To overcome this problem we generally used CSS Friendly adapter to render the ASP.NET Control in ul/li mode.

ASP.NET 4.0 makes the things easier for web developer by providing “RenderingMode” properties. Here we can specify RenderMode of a ASP.NET Menu control. Which define the what will be the HTML Render Content Type. Bydefault mode is “List” which means control will be render as ul/li

As per the above diagram we can see that there are three mode available. We can use any one of them as per the requirement. Continue reading

Beginner’s Guide: How IIS Process ASP.NET Request

Introduction

When request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request.  Here I am not going to describe the Page Life Cycle and there events, this article is all about the operation of IIS Level.  Before we start with the actual details, let’s start from the beginning so that each and everyone understand it’s details easily.  Please provide your valuable feedback and suggestion to improve this article.

What is Web Server ?

When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses.  The process name is “WebDev.WebServer.Exe” which actually takw care of all request and response of an web application which is running from Visual Studio IDE.

Now, the name “Web Server” comes into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.

What is IIS ?

IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

Request Processing :

Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts

1.    Worker Process
2.   Application Pool

Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.

Application Pool with multiple worker process is called “Web Garden”.
Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up from client.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer

1.    Kernel Mode
2.    User Mode

Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS.  So whenever a request comes from Client to Server, it will hit HTTP.SYS First.

Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request?  This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.

So, this was the first steps of IIS Request Processing.
Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.

In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.

When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.
Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

When this methods called, a new instance of HTTPContext is been created.  Which is accessible using HTTPContext.Current  Properties. This object still remains alive during life time of object request.  Using HttpContext.Current we can access some other objects like Request, Response, Session etc.

After that HttpRuntime load an HttpApplication object with the help of  HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.
Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.

HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler.  Then  HTTP Handler  generates the output for the requested resource. So, when we requesting for any aspx web pages,   it returns the corresponding HTML output.

All the request now passes from  httpModule to  respective HTTPHandler then method and the ASP.NET Page life cycle starts.  This ends the IIS Request processing and start the ASP.NET Page Lifecycle.

Conclusion

When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective  Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

This was just overview of IIS Request Processing to let Beginner’s know how the request get processed in backend.  If you want to learn in details please check the link for Reference and further Study section.

Reference and Further Study

 

A low-level Look at the ASP.NET Architecture
IIS Architecture

 

Please share your suggestion and feedback.

Filter GridView Records using AJAX Slider Control

Sometimes we need to filter the gridview data based on some range value. On that case we can use AJAX Slider control to provide scrollable Filter functionality with gridview control. Data source for the Gridview can be anything like XML or Database.

You can read the complete article and Implementation and download the sample application  from DotNetFunda.Com

I will also write one article on AJAX MulipleSlider to filter the data based on minimumn and maximum value.

Please share your valuable feedback and suggestion.

ASP.NET 4.0 Features – MetaDescription and MetaKeywords

ASP.NET 4.0, came up with two new properties inside Page Class, those are MetaDescription and MetaKeyWord. This has been introduce because of make web application Search Engine Friendly. Search Engine looks for Meta tag of our web page to get the details of page contents. In ASP.NET 4.0, we can add these two properties with Page class in Code behind or in Page Directives.
If you want to find out the definition of these two properties, Right Click on Page Class and Click on Goto Definition. This will show you the Meta data information of Page Class as shown in below picture

If we set MetaDescription and MetaKeywords either from Code behind or using Page Directive in aspx page, both will be render as “meta” tag in html code.
The main objective of MetaKeywords and MetaDescription proerties to make your web application SEO friendly. In ASP.NET 2.0, HtmlMeta used to do the same, but in ASP.NET 4.0 make these thing  very simple as we can easily add using Page Class.

You can find the Complete Article over,  DotNetFunda.com

It has alreday been shared with

www.dotnetkicks.com

dotnetshoutout.com

delicious.com

digg.com

You can also follow me @ http://twitter.com/AbhijitJana

My New Article : Exploring Caching : Using Caching Application Enterprise Library 4.1

Enterprise Library caching application Block provides ready to use Caching Framework. This  can be used in various application like

* ASP.NET Web application
* Windows Forms
* Console
* Windows Service
* Enterprise Services
* Web service
Implementing caching using Caching Application Block improve the performance of application as well as reduces the development time and cost. This Application blocks provides all kinds of function like adding, removing, managing expiration of cache.
As caching application block is predefined set of code and that are defined in a framework for that we need install Enterprise Library 4.1 First then we need  to add some reference in to our application. These are Microsoft.Practices.EnterpriseLibrary.Caching.dll and Microsoft.Practices.EnterpriseLibrary.common.dll.

I have published one complete article on Codeproject.com which describe how to use Enterprise Caching Application Block 4.1 . Here is my complete article
Exploring Caching : Using Caching Application Enterprise Library 4.1

Please provide your valuable suggestion and feedback to improve my articles.

Thank you !