Tuesday, 23 September 2014

Improve the Performance of an ASP.Net Application

Here are a few tips to improve the performance of your ASP.Net application.
  1. Viewstate
    View state is the wonder mechanism that shows the details of the entry posted on the server. It is loaded every time ifrom the server. This option looks like an extra feature for the end users. This needs to be loaded from the server and it adds more size to the page but it will affect the performance when we have many controls in the page, like user registration. So, if there is no need for it then it can be disabled.

    EnableViewState = "false" needs to be given based on the requirements. It can be given at the control, page and config level settings.
     
  2. Avoid Session and Application Variables
    A Session is a storage mechanism that helps developers to take values across the pages. It will be stored based on the session state chosen. By default it will be stored in the Inproc. That default settings uses IIS. When this Session variable is used in a page that is accessed by many numbers then it will occupy more memory allocation and gives additional overhead to the IIS. It will make the performance slow.

    It can be avoided for most scenarios . If you want to send the information across pages then we can use a Cross Post-back, Query string with encryption. If you want to store the information within the page then caching the object is the best way.
     
  3. Use Caching
    ASP.Net has the very significant feature of a caching mechanism. It gives more performance and avoids the client/server process. There are three types of caching in ASP.Net.

    If there is any static content in the full pages then it should be used with the Output cache. What it does is, it stores the content on IIS. When the page is requested it will be loaded immediately from the IIS for the certain period of time. Similarly Fragment paging can be used to store the part of the web page.
     
  4. Effectively use CSS and Script files
    If you have large CSS files that are used for the entire site in multiple pages, then based on the requirements, it can be split and stored with different names. It will minimize the loading time of the pages.
     
  5. Images sizes
    Overuse of images in the web site affect the web page performance. It takes time to load the images, especially on dial-up connections. Instead of using the background images, it can be done on the CSS colors or use light-weight images to be repeated in all of the pages.
     
  6. CSS based layout
    The entire web page design is controlled by the CSS using the div tags instead of table layout. It increases the page loading performance dramatically. It will help to enforce the same standard guideline throughout the website. It will reduce the future changes easily. When we use the nested table layout it takes more time for rendering.
     
  7. Avoid Round trips
    We can avoid unnecessary database hits to load the unchanged content in the database. We should use the IsPostBack method to avoid round trips to the database.
     
  8. Validate using JavaScript

    Manual validation can be done at the client browser instead of doing at the server side. JavaScript helps us to do the validation at the client side. This will reduce the additional overhead to the server.

    The plug-in software helps to disable the coding in the client browser. So, the sensitive application should do the server side validation before going into the process. 
     
  9. Clear the Garbage Collection

    Normally .Net applications use Garbage Collection to clean the unused resources from memory. But it takes time to clear the unused objects from memory.

    There are many ways to clean the unused resources. But not all of the methods are recommended. But we can use the dispose method in the finally block to clean up the resources. Moreover we need to close the connection. It will immediately free the resources and provides space in memory.
     
  10. Avoid bulk data store on client side

    Try to avoid more data on the client side. It will affect the web page loading. When we store more data on the hidden control then it will be encrypted and stored on the client side. It can be tampered with by hackers as well.
     
  11. Implement Dynamic Paging
    When we load a large number of records into the server data controls like GridView, DataList and ListView it will take time to load. So we can show only the current page data through the dynamic paging.
     
  12. Use Stored Procedure

    Try to use Stored Procedures. They will increase the performance of the web pages. Because it is stored as a complied object in the database and it uses the query execution plans. If you pass the query then it will make a network query. In the Stored Procedure a single line will be passed to the backend.
     
  13. Use XML and XSLT

    XML and XSLT will speed up the page performance. If the process is not more complex then it can be implemented in XSLT.
     
  14. Use Dataset

    A DataSet is not lightweight compared with DataReader. But it has the advantages of a disconnected architecture. A DataSet will consume a substantial amount of memory. Even though it can have more than one day. If you want to perform many operations while loading the page itself, then it might be better to go with a DataSet. Once data is loaded into the DataSet it can be used later also.
     
  15. Use String Builder in place of String

    When we append the strings like mail formatting in the server side then we can use StringBuilder. If you use string for concatenation, what it does every time is it creates the new storage location for storing that string. It occupies more spaces in memory. But if we use the StringBuilder class in C# then it consumes more memory space than String.
     
  16. Use Server.Transfer

    If you want to transfer the page within the current server then we can use the Server.Transfer method. It avoids roundtrips between the browser and server. But it won't update the browser history.
     
  17. Use Threads

    Threads are an important mechanism in programming to utilize the system resources effectively. When we want to do a background process then it can be called a background process.

    Consider the example of when clicked on send, it should send the mail to 5 lakhs members yet there is no need to wait for all the processes to complete. Just call the mail sending process as a background thread then proceed to do the further processing, because the sending of the mail is not dependent on any of the other processes.

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” come 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 questionHow 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 ProcessRequestmethod 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.

Monday, 21 July 2014

Captcha using C# in ASP.NET

In this Article, I will explain how to incorporate Captcha Control in ASP.Net. Captcha control helps to avoid spam and generally used in Contact us or Sign Up forms.
Basically the user is shown an image with some characters and user has to fill the same character in a textbox provided, then the content of the image is matched with the textbox and if it matches it ensures that it’s a valid submission and the form gets submitted.
To start with you will need o download the Free Captcha User Control from here
Once it is done you will need to add reference of the same
Right Click your Website and Click Add Reference


Add Reference


Browse and select the DLL File


Browse and Select the DLL File


Once the reference is added you will need to add this key to the web.config
<add verb="GET" path="CaptchaImage.axd"
 type="MSCaptcha.CaptchaImageHandler, MSCaptcha" />

As shown below in the httpHandlers section


Adding key to Web.Config


Now Register the control on your page using the following
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>

As shown below


Registering the User Control


Now add the Captcha control on the page where you intend to place it
<cc1:CaptchaControl ID="Captcha1" runat="server"
 CaptchaBackgroundNoise="Low" CaptchaLength="5"
 CaptchaHeight="60" CaptchaWidth="200"
 CaptchaLineNoise="None" CaptchaMinTimeout="5"
 CaptchaMaxTimeout="240" FontColor = "#529E00" />

As shown below


Adding the control on webpage
   
There are various parameters like which you can set
CaptchBackgroundNoise – Sets the amount of Noise you want in background noise
CaptchaLength – Length of the Captcha Text
CaptchaHeight – Height of Captcha control
CaptchaWidth – Width of Captcha control
CaptchaLineNoise – Line Noise in image
CaptchaMinTimeout – Minimum Time Captcha image is valid
CaptchaMaxTimeout – Maximum Time Captcha image is valid

To verify I have added the following code to button click event
C#
protected void btnVerify_Click(object sender, EventArgs e)
{
    Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
    if (Captcha1.UserValidated)
    {
        lblMessage.ForeColor = System.Drawing.Color.Green;
        lblMessage.Text = "Valid";
    }
    else
    {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "InValid";
    }
}

VB.Net
Protected Sub btnVerify_Click(ByVal sender As Object,
ByVal e As System.EventArgs)
   Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim())
   If Captcha1.UserValidated Then
     lblMessage.ForeColor = System.Drawing.Color.Green
     lblMessage.Text = "Valid"
   Else
     lblMessage.ForeColor = System.Drawing.Color.Red
     lblMessage.Text = "InValid"
   End If
End Sub

Finally the Captcha control looks like below


Captcha Control

Wednesday, 21 May 2014

Real Time Pan Card Validation While Entering

<asp:TextBox ID="AN_UC7_txtpan" runat="server" class="input-style-newone"  onkeyup="return CheckPAN(this.id,event,'CPH1_ID_AN_ODProposer_AN_UC7_lblerrpan');"
                                    onkeypress="return CheckPAN(this.id,event,'CPH1_ID_AN_ODProposer_AN_UC7_lblerrpan'); "
                                    MaxLength="10" TabIndex="5" oncopy ="return false" onpaste="return false" oncut="return false" ></asp:TextBox>


 <div class="error-box" style="width: 500px">
                                    <div class="error-box-inner">
                                        <asp:Image ID="AN_UC7_Imgerriconpan" runat="server" src="images/error-icon.jpg" Style="margin: 0 5px -1px 0;
                                            display: none" />
                                        <asp:Label ID="AN_UC7_lblerrpan" runat="server" Text=""></asp:Label>
                                    </div>
                                </div>



function IsOnlyNumeric(strString) {
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}


function CheckPAN(obj, evt, lblname) {
    var lbl = lblname;
    var ctrlname = obj;
    var ucctrlname = ctrlname;
    var strInitial = ucctrlname;

    var code = (evt.which) ? evt.which : evt.keyCode ? evt.keyCode : evt.charCode;
    //For IE7 browser
    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }
    if (navigator.userAgent.search("Firefox") != -1) {
        if (code == 32 || code == 190) {
            var pancard = document.getElementById(obj).value;
            document.getElementById(obj).value = pancard.substring(0, pancard.length - 1);
        }
    }
    if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || (code == 13 || code == 8 || code == 9)) {
        var pancard = document.getElementById(obj).value;    
   
        if ((pancard.trim().length > 0 && IsOnlyNumeric(pancard.charAt(0).toString()) == true) || (pancard.trim().length > 1 && IsOnlyNumeric(pancard.charAt(1).toString()) == true) || (pancard.trim().length > 2 && IsOnlyNumeric(pancard.charAt(2).toString()) == true) || (pancard.trim().length > 3 && IsOnlyNumeric(pancard.charAt(3).toString()) == true) || (pancard.trim().length > 4 && IsOnlyNumeric(pancard.charAt(4).toString()) == true)) {
            document.getElementById(obj).value = pancard.substring(0, pancard.length - 1);
            document.getElementById(lbl).innerHTML = ""; //"Starting five digits should be Alphabets";
            if (pancard.trim().length == 1) {
                document.getElementById(obj).value = "";
            }
            return false;
        }
        if ((pancard.trim().length > 5 && IsOnlyNumeric(pancard.charAt(5).toString()) == false) || (pancard.trim().length > 6 && IsOnlyNumeric(pancard.charAt(6).toString()) == false) || (pancard.trim().length > 7 && IsOnlyNumeric(pancard.charAt(7).toString()) == false) || (pancard.trim().length > 8 && IsOnlyNumeric(pancard.charAt(8).toString()) == false)) {
            document.getElementById(obj).value = pancard.substring(0, pancard.length - 1);
            document.getElementById(lbl).innerHTML = ""; //"6,7,8 & 9th digits should be numeric";
            return false;

        }
        if (pancard.trim().length > 9 && IsOnlyNumeric(pancard.charAt(9).toString()) == true) {
            document.getElementById(obj).value = pancard.substring(0, pancard.length - 1);
            document.getElementById(lbl).innerHTML = ""; // "Last digit should be Alphabet";
            return false;
        }
    }
    else {
        return false;
    }
    return true;
}

Wednesday, 7 May 2014

Asp.net set session timeout

Asp.net set session timeout:


By default our websites session timeout is 20 mins after that session will gets expire suppose if we want to set our custom timeout in our applications we can set it in different ways 


Write below code in .CS file
  string str_jscript = "TimeOutExpire(" + Convert.ToString(Session.Timeout * (60 * 1000)) + ");";
        Page page = System.Web.HttpContext.Current.Handler as Page;
        System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "", str_jscript, true);



Write Below code  in .ASPX page

 <script type="text/javascript">
        var timer;
        function TimeOutExpire(obj) {
            window.clearTimeout(timer);
            timer = window.setTimeout(function () { window.location = "Loginpage.aspx?PID=EAN" }, parseInt(obj));
        }          
    </script>

Displaying a Custom Error Page


Introduction

In a perfect world there would be no run-time errors. Programmers would write code with nary a bug and with robust user input validation, and external resources like database servers and e-mail servers would never go offline. Of course, in reality errors are inevitable. The classes in the .NET Framework signal an error by throwing an exception. For example, calling a SqlConnection object's Open method establishes a connection to the database specified by a connection string. However, if the database is down or if the credentials in the connection string are invalid then the Open method throws a SqlException. Exceptions can be handled by the use oftry/catch/finally blocks. If code within a try block throws an exception, control is transferred to the appropriate catch block where the developer can attempt to recover from the error. If there is no matching catch block, or if the code that threw the exception is not in a try block, the exception percolates up the call stack in search of try/catch/finally blocks.

Examining the Three Types of Error Pages

When an unhandled exception arises in an ASP.NET application one of three types of error pages is displayed:
  • The Exception Details Yellow Screen of Death error page,
  • The Runtime Error Yellow Screen of Death error page, or
  • A custom error page
  • Figure 1 shows the Exception Details YSOD page. Note the URL in the browser's address window:http://localhost:62275/Genre.aspx?ID=foo. Recall that the Genre.aspx page lists the book reviews in a particular genre. It requires that GenreId value (a uniqueidentifier) be passed through the querystring; for example, the appropriate URL to view the fiction reviews is Genre.aspx?ID=7683ab5d-4589-4f03-a139-1c26044d0146. If a non-uniqueidentifier value is passed in through the querystring (such as "foo") an exception is thrown.
aspnet_tutorial11_CustomErrors_cs_figure01.png (852×602)






Using a Custom Error Page

Every web application should have a custom error page. It provides a more professional-looking alternative to the Runtime Error YSOD, it is easy to create, and configuring the application to use the custom error page takes only a few moments. The first step is creating the custom error page. I've added a new folder to the Book Reviews application named ErrorPages and added to that a new ASP.NET page named Oops.aspx. Have the page use the same master page as the rest of the pages on your site so that it automatically inherits the same look and feel.


With the error page completed, configure the web application to use the custom error page in lieu of the Runtime Error YSOD. This is accomplished by specifying the URL of the error page in the <customErrors> section'sdefaultRedirect attribute. Add the following markup to your application's Web.config file:


<system.web>
        <customErrors mode="RemoteOnly"
                      defaultRedirect="~/ErrorPages/Oops.aspx" />

        ...
    </system.web>

The Clickjacking attack, X-Frame-Options

ASP.NET web application security 

Overview:


This article helps you build and enable robust web applications with respect to various aspects of securities that need to be taken care while designing a system. The system designed without considering security assessment leads to non compliance and may come under security threats. Such systems are vulnerable to harmful attacks. The guide below will foster the strengthening of applications and mitigate the risk of probable attacks and reduce unauthorized activities. The problem, scenario, and solution statement stated here are .NET centric. I have tried to cover most essential security review items that cause most issues and non compliance


Real time scenario

Assume there is an e-commerce site where we can purchase a book online. There will be another website with the exact replica but with a few changes such that users are motivated to transact. A scenario where an e-commerce site will have a button with a Buy caption and a malicious site will have a screen with a masked non–event button ‘Donate’ just placed above it. The moment the user clicks on the masked non-event button ‘Donate’, in reality, it will trigger the low level z-index Buy button. This is how hackers can misuse your website for their purpose.


Solution : This works absolutely fine for all authentication modes

Write Below code in Global.asax file:


void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    }