Saturday, January 22, 2011

IIS in depth

Web server is used 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.

 
 


 
 

 
 

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.

 
 

The web server process that was being debugged has been terminated by Internet Information Services (IIS)

By default, debugging a website or web project within Visual Studio bring up the built-in server of Visual Studio. But, we do have a problem to change the server to an IIS instance. I recently switched to debugging on IIS on my Windows 7. Debugging works fine. The only problem is that if your code hit some breakpoint and if you leave the program in 'break' mode for more than 90 seconds, Visual Studio shows the following message:


 




 


 


After a bit tweaking around in the new IIS interface, I got the solution:




  • Open Internet Information Services (IIS) Manager.

  • From the server tree (the item with the name as the server name), choose Application Pools.

  • Choose the Application Pool corresponding to your testing IIS website (usually it has the same name as your IIS website)

  • Right-click and choose Advanced Settings.


  • From the Process Model node, change the Ping Maximum Response Time (seconds) to a comfortably higher value (I have set the value to 900 seconds which is 15 minutes).

     


Alternatively, you can also set the Ping Enabled property to False.

Apparently what happens is that the server keeps pinging the worker process and waits for a response. When in debugging mode, the worker process is affectively suspended, which results in the ping not being responded.


 


 

Thursday, January 13, 2011

Bypass specific IP from rendering google analytics code

To bypass specific IP from rendering google analytics code, follow the following steps.



  1. List the IP which you wants to bypass from rendering into your web application, and add in web.config file

    e.g. <add key="ByPassUrl" value="101.101.101.100"/>


  2. Create a Usercontrol and named "GoogleAnalytics.ascx" replace your google analytics code with "<google analytics code here>".

    <%@Control Language="C#" AutoEventWireup="true" CodeFile="GoogleAnalytics.ascx.cs"
    Inherits="Include_GoogleAnalytics"%>


    <script type="text/javascript">


    <% if (ConfigurationManager.AppSettings["showGoogleAnalytics"] == "True") {%>


    <% if (!strByPassUrl.Contains(requestUrl)) {%>


    var _gaq = _gaq || [];


    _gaq.push(['_setAccount', '<google analytics code here>']);


    _gaq.push(['_trackPageview']);


    (function() {


    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;


    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';


    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);


    })();


    <% } %>


    <% } %>


    </script>


     


  3. Declare following 2 public variable in "GoogleAnalytics.ascx.cs" file

    public string requestUrl = HttpContext.Current.Request.UserHostAddress.ToString();
    public
    string strByPassUrl = clsCommon.value("ByPassUrl");


  4. Add "GoogleAnalytics" user control in master page of the application within <Head></Head> tag.

    <head runat="server">


    <uc2:GoogleAnalytics ID="GoogleAnalytics1" runat="server"/>


    </head>


Note :- 1) Before Copying Google analytics code verify with google analytics script, provided in google analytics account.

2) check if "showGoogleAnalytics" key is present in web.config file.

Thursday, December 30, 2010

Generating Random Strings of Characters in SQL

The following Transact SQL procedure can be used to generate a random string of characters. As such it can be used to for example generate a default password for a user. The specific characters that are used to generate the string can be specified, so it can be customised (e.g. to only create passwords of digits or lower cased letters). The length of the generated random string can also be specified.

It is recommended that this SQL procedure be used as a stored procedure.

Using as a Stored Procedure


The following stored procedure creates a random string of characters of a length specified by the parameter @Length:
CREATE PROCEDURE sp_GeneratePassword
(
@Length int
)
AS
DECLARE @RandomID varchar(32)
DECLARE @counter smallint
DECLARE @RandomNumber float
DECLARE @RandomNumberInt tinyint
DECLARE @CurrentCharacter varchar(1)
DECLARE @ValidCharacters varchar(255)

SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+&$'

DECLARE @ValidCharactersLength int
SET @ValidCharactersLength = len(@ValidCharacters)
SET @CurrentCharacter = ''
SET @RandomNumber = 0
SET @RandomNumberInt = 0
SET @RandomID = ''
SET NOCOUNT ON
SET @counter = 1

WHILE @counter < (@Length + 1)
BEGIN
SET @RandomNumber = Rand()
SET @RandomNumberInt = Convert(tinyint, ((@ValidCharactersLength - 1) * @RandomNumber + 1))
SELECT @CurrentCharacter = SUBSTRING(@ValidCharacters, @RandomNumberInt, 1)
SET @counter = @counter + 1

SET @RandomID = @RandomID + @CurrentCharacter
END

SELECT @RandomID AS 'Password'
GO

Wednesday, December 15, 2010

Extension Methods

The .NET Framework employs the concept of sealed classes. A sealed class is a class that cannot be inherited from. But, what if we want to extend these classes? Based on the meaning of sealed it's not possible. Compound the technical inability to extend sealed classes with classes that are defined as the result of a LINQ query, called projections, and there is no opportunity to extend.

Another desire that class designers have is to avoid deep inheritance trees. Generally using inheritance to add a capability or two is undesirable because it leads to deep inheritance trees that are difficult to comprehend and maintain.


To overcome some of these challenges Microsoft introduced the extension method. Extension methods are defined in separate static classes as static methods and the first argument of the method is the extended type. The extended type—the first argument—is modified with the keyword this. Although an extension method is a static method in a static class, extension methods have member method semantics. That is, extension methods are called is if they were a member of the extended class, a regular member method.


Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.



Extension method are only in scope when you explicitly import the namespace into your source code with "using" directive.


namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static string Reverse(this String strReverse)
{
char[] charArray = new char[strReverse.Length];
int len = strReverse.Length - 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = strReverse[len - i];
}
return new string(charArray);
}
}
}

using ExtensionMethods;
protected void Page_Load(object sender, EventArgs e)
{
string str = "Hello Extension Methods";
string strReverse = str.Reverse();
}

Thursday, November 18, 2010

Finding Geolocation information from ip address in asp.net

Ip is the internet protocol for communication between nodes.

Ip is used to identify a host and address the location. If we need to identify the user

who are all accessing our website and store the ip address in our database is very simple and very easier.

This is the way to track the users ip address. Fetch a client's ip address as soon as he access our web site in asp.net.

Some of them may use a proxy ip address. But we can get their ip address with this simple code.

Add following namespace in page
using System.Net;

string ipAddress ="";

//Get the Host Name
string hostName = Dns.GetHostName();

//Get The Ip Host Entry
IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);

//Get The Ip Address From The Ip Host Entry Address List
IPAddress[] ipAddress = ipHostEntry.AddressList;

ipAddress = ipAddress[ipAddress.Length - 1].ToString();

To get the Geolocation of IP address you can use the various
API which would gives you result in various different format(csv,xml)

http://www.ipinfodb.com/ip_location_api.php

You can get Geolocation information from

http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Response comes in XML format. using xml deserialize, I deserialize the response.

[XmlRootAttribute(ElementName = "Response", IsNullable = false)]

public class IPLocator
{
private string longitude;
public string Longitude
{
get { return longitude; }
set { longitude = value; }
}

private string latitude;
public string Latitude
{
get { return latitude; }
set { latitude = value; }
}
private string zip;
public string Zip
{
get { return zip; }
set { zip = value; }
}

private string ip;
public string IP
{
get { return ip; }
set { ip = value; }
}
}

After deserialization IPLocater class bind All properties of requested IP Address.

Binding Class is return IPLocater class.

Code of IPDetals Class
public IPLocator GetData(string ipAddress)
{
IPLocator ipLoc = new IPLocator();
try
{
//apiKey can be generated from below link

//http://www.ipinfodb.com/ip_location_api.php

string apiKey = "anykey";
string path = "http://api.ipinfodb.com/v2/ip_query.php?key=" + apiKey + "&ip=" + ipAddress + "&timezone=false";

WebClient client = new WebClient();
string[] eResult = client.DownloadString(path).ToString().Split(',');

if (eResult.Length > 0)
ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
}
catch
{ }

return ipLoc;
}

//Desrialize XML String
private Object Deserialize(String pXmlizedString)
{
XmlSerializer xs = new XmlSerializer(typeof(IPLocator));

MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));

XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

return xs.Deserialize(memoryStream);

}

//String to UTF8ByteArray

private Byte[] StringToUTF8ByteArray(String pXmlString)
{

UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
}

//You can get the Geolocation infoamation here

string ipAddress = HttpContext.Current.Request.UserHostAddress;

IPDetails ipDetails=new IPDetails ();
IPLocator ipLocater = ipDetails.GetData(ipAddress);
Response.Write(ipLocater.CountryName);

Tuesday, October 26, 2010

Windows Communication Foundation in Framework 4.0

Windows Communication Foundation (WCF) provides the following improvements:

  • Configuration-based activation: Removes the requirement for having an .svc file.
  • System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
  • Routing Service: Allows you to route messages based on content.
  • Support for WS-Discovery: Allows you to create and search for discoverable services.
  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
  • WCF REST features:
    • Web HTTP caching: Allows caching of Web HTTP service responses.
    • Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
    • Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
    • Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
    • Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
  • Simplified configuration: Reduces the amount of configuration a service requires