Monday, July 14, 2014

What is the use of Global.asax file events in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules.

The Global.asax file resides in the root directory of an ASP.NET-based application. The Global.asax file is parsed and dynamically compiled by ASP.NET.


The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

The Global.asax file does not need recompilation if no changes have been made to it. There can be only one Global.asax file per application and it should be located in the application's root directory only.
The Global.asax contains two types of events those are

Events which are not fired for every request

Application_Start() – This event raised when the application starts up and application domain is created.

Session_Start() – This event raised for each time a new session begins, This is a good place to put code that is session-specific.

Application_Error() – This event raised whenever an unhandled exception occurs in the application. This provides an opportunity to implement generic application-wide error handling.

Session_End() – This event called when session of user ends.

Application_End() – This event raised just before when web application ends.

Application_Disposed() – This event fired after the web application is destroyed and this event is used to reclaim the memory it occupies.




Events which are fired for every request

Events which are not fired for every request

Application_BeginRequest() – This event raised at the start of every request for the web application.

Application_AuthenticateRequest – This event rose just before the user credentials are authenticated. We can specify our own authentication logic here to provide custom authentication.

Application_AuthorizeRequest() – This event raised after successful completion of authentication with user’s credentials. This event is used to determine user permissions. You can use this method to give authorization rights to user.

Application_ResolveRequestCache() – This event raised after completion of an authorization request and this event used in conjunction with output caching. With output caching, the rendered HTML of a page is reused without executing its code.

Application_AcquireRequestState() – This event raised just before session-specific data is retrieved for the client and is used to populate Session Collection for current request.

Application_PreRequestHandlerExecute() – This event called before the appropriate HTTP handler executes the request.

Application_PostRequestHandlerExecute() – This event called just after the request is handled by its appropriate HTTP handler.

Application_ReleaseRequestState() – This event raised when session specific information is about to serialized from the session collection.

Application_UpdateRequestCache() – This event raised just before information is added to output cache of the page.


Application_EndRequest() – This event raised at the end of each request right before the objects released.

simple example in Global.asax


First Open visual Studio ---> Create New Website after that right click on Solution explorer and select new item

After select Add New Item window will open in that select Global Application Class and click ok

After add file open Global.asax file and add following code in Global.asax file
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
protected void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
WriteFile("Application Starting");
}
protected void Application_End(object sender, EventArgs e)
{
//  Code that runs on application shutdown
WriteFile("Application Ending");
}
protected void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
string strError;
strError = Server.GetLastError().ToString();
if(Context!=null)
{
Context.ClearError();
Response.Write("Application_Error" + "<br/>");
Response.Write("<b>Error Msg:</b>" + strError + "<br/>"+"<b>End Error Msg<b/>");
}
}
protected void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Response.Write("Session_Start" + "<br/>");
}

protected void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
Response.Write("Session_End"+"<br/>");
}
protected void Application_BeginRequest(object sender,EventArgs e)
{
Response.Write("Application_BeginRequest" + "<br/>");
}
protected void Application_EndRequest(object sender, EventArgs e)
{
Response.Write("Application_EndRequest" + "<br/>");
}
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
Response.Write("Application_AcquireRequestState" + "<br/>");
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
Response.Write("Application_AuthenticateRequest" + "<br/>");
}
protected void Application_AuthorizeRequest(object sender, EventArgs e)
{
Response.Write("Application_AuthorizeRequest" + "<br/>");
}
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
Response.Write("Application_PostRequestHandlerExecute" + "<br/>");
}
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
Response.Write("Application_PreRequestHandlerExecute" + "<br/>");
}
protected void Application_PreSendRequestContent(object sender, EventArgs e)
{
Response.Write("Application_PreSendRequestContent" + "<br/>");
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
Response.Write("Application_PreSendRequestHeaders" + "<br/>");
}
protected void Application_ReleaseRequestState(object sender, EventArgs e)
{
Response.Write("Application_ReleaseRequestState" + "<br/>");
}
protected void Application_ResolveRequestCache(object sender, EventArgs e)
{
Response.Write("Application_ResolveRequestCache" + "<br/>");
}
protected void Application_UpdateRequestCache(object sender, EventArgs e)
{
Response.Write("Application_UpdateRequestCache" + "<br/>");
}
protected void Application_Disposed(object sender, EventArgs e)
{
Response.Write("Application_Disposed"+"<br/>");
}
public void WriteFile(string strText)
{
StreamWriter strWriter = new StreamWriter(@"C:test.txt"true);
string str = DateTime.Now + " " + strText;
strWriter.WriteLine(str);
strWriter.Close();
}
</script>

After adding code in Global.asax open your website aspx page and design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Global Events Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Global Events</h1>
<asp:Button ID="btnEndSession" runat="server" Text="End Session" onclick="btnEndSession_Click" />
<asp:Button ID="btnError" runat="server" Text="Generate Error" onclick="btnError_Click" />
</div>
</form>
</body>
</html>
After that write the following code in code behind
protected void btnEndSession_Click(object sender, EventArgs e)
{
Session.Abandon();
}
protected void btnError_Click(object sender, EventArgs e)
{
int a = 5;
int b = 0;
int c=a / b;
}

Creating C# Class Library (DLL) Using Visual Studio .NET

Step 1:- File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory click OK
After Clicking on button ‘OK’, solution explorer adds one C# class ‘Class1.cs’. In this class we can write our code.


When we double click on Class1.cs, we see a namespace CreatingDLL. We will be use this namespace in our project to access this class library.

Step 2:- Within Class1.cs we create a method named ‘sum’ that takes two integers value and return sum to witch method passed numbers.
using System;
namespace CreatingDLL
{
    public class Class1
    {
        /// <summary>
        /// sum is method that take two integer value and return that sum
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int sum(int x, int y)
        {
            return x + y;
        }
     }
}

Step 3:- Now build the Application and see bin\debug directory of our project. ‘CreatingDLL.dll’ is created.
Now we create another application and take this DLL (CreatingDLL.dll) reference for accessing DLL’s method.

Steps for accessing created DLL
Step 4:- File->New->Project->Visual C# Projects->Windows Form Application.
Step 5:- Designed windows form as bellow figure.
Step 6:- Add reference of DLL (CreatingDLL) which we created before few minutes.
After adding reference of DLL, following windows will appear.

Step 7:- Write code on button click of Windows Form Application. Before creating object and making method of Add DLL, add namespace CreatedDLLin project as bellow code.
using System;
using System.Windows.Forms;
using CreatingDLL;
namespace AccessingDLL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Class1 c1 = new Class1();
            try
            {
                txtResult.Text =Convert.ToString(c1.sum(Convert.ToInt32(txtNumber1.Text),Convert.ToInt32(txtNumber2.Text)));
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

}

Step 8:- Now build the application and execute project and see output.

Inserted data to Creating Xml Tag

Add Xml File And Create Root Tag like <bookstore>  </bookstore>
Xml Name like BookStore.xml

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <table style="width: 100%;">
            <tr>
                <td class="auto-style1">
                    Title:
                </td>
                <td>
                    <asp:TextBox ID="tbTitle" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style1">
                    Author:
                </td>
                <td>
                    <asp:TextBox ID="tbAuthor" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style1">
                    Year:
                </td>
                <td>
                    <asp:TextBox ID="tbYear" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style1">
                    Price:
                </td>
                <td>
                    <asp:TextBox ID="tbPrice" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style1">
                </td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
        <asp:GridView ID="gvBookStoreRecords" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        XmlDocument XmlDocObj = new XmlDocument();
        XmlDocObj.Load(Server.MapPath("BookStore.xml"));
        XmlNode RootNode = XmlDocObj.SelectSingleNode("bookstore");
        XmlNode bookNode = RootNode.AppendChild(XmlDocObj.CreateNode(XmlNodeType.Element, "book", ""));
        bookNode.AppendChild(XmlDocObj.CreateNode(XmlNodeType.Element, "Title", "")).InnerText = tbTitle.Text;
        bookNode.AppendChild(XmlDocObj.CreateNode(XmlNodeType.Element, "Author", "")).InnerText = tbAuthor.Text;
        bookNode.AppendChild(XmlDocObj.CreateNode(XmlNodeType.Element, "Year", "")).InnerText = tbYear.Text;
        bookNode.AppendChild(XmlDocObj.CreateNode(XmlNodeType.Element, "Price", "")).InnerText = tbPrice.Text;

        XmlDocObj.Save(Server.MapPath("BookStore.xml"));

        gridDataBind();

    }
    public void gridDataBind()
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("BookStore.xml"));
        gvBookStoreRecords.DataSource = ds;
        gvBookStoreRecords.DataBind();
    }
}