Set source view as default view for Web Pages in Visual Studio

By default in Visual Studio for any web pages design view is the default view. Which may causes some time to load if your page is having many controls . So If you want to change the default view from Design View to Source View, just perform the following steps.

Go to “Tools” > “Options” and Navigate to “HTML Designer” Section.

sourceview

Advertisements

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

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.

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 .

Unable to Start Web Site on IIS – “Process can not access the file because It’s being used by another process”. How to resolve ?

I was trying to run one of my local IIS hosted site I got page not found error. I was quite surprised to see that error because the site was up and running few hours back. I opened the IIS and found that my Site Application was in stopped mode. I started the web application and got the error message displayed below

Problem : Error message “Process can not access the file because It’s being used by anther process”  while starting the web application from IIS.

Investigation and Resolution:  Earlier my web site was running on the default IIS port ( Port 80 ).  From the error message it’s clear that port 80 is being used by some other process or some one is blocking it.

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

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.

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.

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

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 for executing all kind of asp.net requests and responses.  The process name is “WebDev.WebServer.Exe” which takes care of all request and response of a 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 places. 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 Services) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has its 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 the response back to clients.

Request Processing :

Hope, till now it’s clear to you that what is the 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 for managing all the request and response that are coming from the client system.  All the ASP.Net functionality runs under the scope of the worker process.  When a request comes to the server from a client worker process is responsible for generating 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 the worker process.  Application pools are used to separate sets of IIS worker processes that share the same configuration.  Application pools enable 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 impact other web application as they are configured into different application pools.

Application Pool with multiple worker processes is called “Web Garden.”
Now, I have covered all the basic stuff like the Web server, Application Pool, Worker process. Now let’s have a look how IIS process the request when a new request comes up from a client.
If we look into the IIS 6.0 Architecture, we can divide 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 the particular Application pool. Now here is one question, How HTTP.SYS does come to know where to send the request?  This is not a random pickup. Whenever we create 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 checked for the Application Pool and based on the application pool it sends 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 receives the request, it just passes the request to worker process (w3wp.exe). The worker process “w3wp.exe” looks up the URL of the request 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 an aspnet_regiis command.

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

When this method called, a new instance of HTTPContext is created.  Which is accessible using HTTPContext.Current  Properties. This object remains alive during the 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. Every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of a module is 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 HTTPModule if we need to handle anything during upcoming request and response.

HTTP Handlers are the endpoints in the HTTP pipeline. All request that is passing through the HTTPModule should reach to HTTPHandler.  The  HTTP Handler generates the output for the requested resource. So, when we were requesting for any aspx web pages,   it returns the corresponding HTML output.
All the request now passes from httpModule to respective HTTPHandler then the method and the ASP.NET Page life cycle starts.  This ends the IIS Request processing and starts the ASP.NET Page Lifecycle.

Conclusion

When the client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to particular  Application Pool. Application Pool then forwards the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTP handler. After that, the ASP.NET Page LifeCycle events start.
This was a just overview of IIS Request Processing to let Beginner’s know how the request gets processed in the backend.  If you want to learn about 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.

Beginners Guide’s to ASP.NET MVC Framework – Part 1 of n


This article describes overview of ASP.NET MVC Framework , MVC Control Flow etc.

This article is the Part 1 of the ASP.NET MVC Framework series.  In this article I have describes very basic over view of MVC Framework and the control flow of MVC. I will write a few articles in this series which will help all the beginners to move ahead. This article is only about what MVC is.

Overview

The Model-View-Controller (MVC) design pattern is an architectural design patterns for any standard development that separates the components of an application. This allows application to handle very flexible and extensible and easy to handle. ASP.NET MVC Framework is also one of the standard web development frameworks which separate the components of web development application different components.

ASP.NET MVC Framework having three main components

  1. Model
  2. View
  3. Controller

4

Model: The model manages the behavior and data of the application domain, responds to requests for information about its state from the view, and responds to instructions to change state (usually from the controller).

View: This represent the presentation layer of the web application. The view manages the display of information based on the data of model that is requested by controller.

Controller: Controller handles the user interaction with the web application.  User request comes through controller to model and manipulate the records from it and then render the data using View to UI.

Below diagram showing the overview of these three components

1

Request Flow for ASP.NET MVC Framework

  1. Request comes from User to Controller
  2. Controller processes request and forms a data Model
  3. Model is passed to View
  4. View transforms Model into appropriate output format
  5. Response is rendered to Browser

2

Above picture showing you the actual flow of ASP.NET MVP Framework.  Request comes from client to Controller and controller decided which model to used and based on that data rendered into browser.

Now, just have a closer look into to the MVC Flow,

3

In the next article I will give the explanation of each of every step. You just need to remember these are the basic flow of an MVC Application.

ASP.NET Web Forms and  MVC

MVC is not a replacement if ASP.NET Web Form based development. This seats on the top of ASP.NET Development.  MVC Framework simply divides the overall application architecture into three components.

For More information on the basic of MVC Framework please read :
ASP.NET MVC Overview (C#)

Summary

This is the startup article for MVC beginners. Many more to come. Where I will explain details of each of them with sample application. Finally there would be a complete ASP.NET project on MVC Framework. Hope this series will be helpful for all.