File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ValidationSummary" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Validation Summary</title>
</head>
<body>
<form id="form1" runat="server">
<div>
A number (1 to 10):
<asp:textbox id="txtValidated" runat="server"></asp:textbox>
<asp:rangevalidator id="RangeValidator"
runat="server"
Type="Integer"
MinimumValue="1"
MaximumValue="10"
ControlToValidate="txtValidated"
Text="<img src='ErrorIcon.jpg' alt='Error' />"
ErrorMessage="The First Number Is Not In The Range">
</asp:rangevalidator>
Not validated:
<asp:textbox id="txtNotValidated" runat="server"></asp:textbox><br/>
<br />
<asp:button id="cmdOK"
runat="server"
Text="OK"
OnClick="cmdOK_Click"
Width="44px"></asp:button><br />
<br />
<asp:label id="lblMessage"
runat="server"
EnableViewState="False"></asp:label><br />
<br />
<asp:ValidationSummary id="ValidationSummary1"
runat="server"
ShowMessageBox="True"></asp:ValidationSummary>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ValidationSummary : System.Web.UI.Page
{
protected void cmdOK_Click(object sender, EventArgs e)
{
if (!Page.IsValid) return;
lblMessage.Text = "cmdOK_Click event handler executed.";
}
}
Information
Information
work around this problem, use one of the following methods:
- For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
- For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example: If you use this workaround, the code that follows Response.Redirect is executed.
Response.Redirect ("nextpage.aspx", false);
- For Server.Transfer, use the Server.Execute method instead.
Information
If you want to put your video on YouTube to share with people all over the world, you may choose FLV format video as it’s the best way for all of you. But not all videos are FLV video format. So, you may search video to FLV converter via google. You might find some free video converter with low quality, or some commercial video converter with high quality and also high price. Is there any other method with high quality and free of payment? There is always a way for your imagination.
Besides using video converter to convert video to FLV, you also can use C#.NET to convert video to FLV on WEB, with high quality and free of payment. The method is very easy if you know something about C#.NET.
First, you need download some files from .NET
1)ffmpeg.exe
2)ffplay.exe
3)pthreadGC2.dll
After downloading the 3 files above, we’ll start the converting of video to flv steps:
1), Make a windows application or new .net web site
2), Copy & Paste the 3 downloaded files to root location
3), Now, you need Copy & Paste the codes (written below)
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + “OriginalVideo”;
//Path of the original file
outputPath = AppPath + “ConvertVideo”;
//Path of the converted file
imgpath = AppPath + “Thumbs”;
//Path of the preview file
string filepath = Server.MapPath(“~/OriginalVideo/” + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(“.”);
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + “.” + ext;
filepath = Server.MapPath(“~/OriginalVideo/” + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = “~/OriginalVideo/” + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
while (a.Exists == false)
{
}
long b = a.Length;
while (i != b)
{
}
string cmd = ” -i \”" + inputPath + “\\” + fileName + “\” \”" + outputPath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.flv” + “\”";
ConvertNow(cmd);
string imgargs = ” -i \”" + outputPath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.flv” + “\” -f image2 -ss 1 -vframes 1 -s 280×200 -an \”" + imgpath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.jpg” + “\”";
ConvertNow(imgargs);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + “ffmpeg.exe”;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for “filebuffer” it will be “flvtool2.exe”
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
while (proc.HasExited == false)
{
}
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
}
4), Here, you need put an upload to page, and then, rename to “ fileuploadImageVideo”
5), put an button and rename to “btn_Submit”
6), Make the following folders
a, OriginalVideo
b, ConvertVideo
c, Thumbs
7), Import Class “using System.IO;”
Now, you can run the application and choose a video file to convert the video to FLV format. You’ll get the converted video in ConvertVideo Folder
Besides using video converter to convert video to FLV, you also can use C#.NET to convert video to FLV on WEB, with high quality and free of payment. The method is very easy if you know something about C#.NET.
First, you need download some files from .NET
1)ffmpeg.exe
2)ffplay.exe
3)pthreadGC2.dll
After downloading the 3 files above, we’ll start the converting of video to flv steps:
1), Make a windows application or new .net web site
2), Copy & Paste the 3 downloaded files to root location
3), Now, you need Copy & Paste the codes (written below)
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + “OriginalVideo”;
//Path of the original file
outputPath = AppPath + “ConvertVideo”;
//Path of the converted file
imgpath = AppPath + “Thumbs”;
//Path of the preview file
string filepath = Server.MapPath(“~/OriginalVideo/” + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(“.”);
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + “.” + ext;
filepath = Server.MapPath(“~/OriginalVideo/” + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = “~/OriginalVideo/” + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
while (a.Exists == false)
{
}
long b = a.Length;
while (i != b)
{
}
string cmd = ” -i \”" + inputPath + “\\” + fileName + “\” \”" + outputPath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.flv” + “\”";
ConvertNow(cmd);
string imgargs = ” -i \”" + outputPath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.flv” + “\” -f image2 -ss 1 -vframes 1 -s 280×200 -an \”" + imgpath + “\\” + fileName.Remove(fileName.IndexOf(“.”)) + “.jpg” + “\”";
ConvertNow(imgargs);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + “ffmpeg.exe”;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for “filebuffer” it will be “flvtool2.exe”
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
while (proc.HasExited == false)
{
}
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
}
4), Here, you need put an upload to page, and then, rename to “ fileuploadImageVideo”
5), put an button and rename to “btn_Submit”
6), Make the following folders
a, OriginalVideo
b, ConvertVideo
c, Thumbs
7), Import Class “using System.IO;”
Now, you can run the application and choose a video file to convert the video to FLV format. You’ll get the converted video in ConvertVideo Folder
Information
year = DateTime.Now.Year.ToString("d");
ddlYear.Items. Add(new ListItem(year - 5, year - 5));
ddlYear.Items.Add(new ListItem(year - 4, year - 4));
ddlYear.Items.Add(new ListItem(year - 3, year - 3));
ddlYear.Items.Add(new ListItem(year - 2, year - 2));
ddlYear.Items.Add(new ListItem(year - 1, year - 1));
ddlYear.Items.Add(new ListItem(year, year));
ddlYear.Items.Add(new ListItem(year + 1, year + 1));
ddlYear.Items.Add(new ListItem(year + 2, year + 2));
ddlYear.Items.Add(new ListItem(year + 3, year + 3));
ddlYear.Items.Add(new ListItem(year + 4, year + 4));
ddlYear.Items.Add(new ListItem(year + 5, year + 5));
..........................................................................................................
ddlYear.Items. Add(new ListItem(year - 5, year - 5));
ddlYear.Items.Add(new ListItem(year - 4, year - 4));
ddlYear.Items.Add(new ListItem(year - 3, year - 3));
ddlYear.Items.Add(new ListItem(year - 2, year - 2));
ddlYear.Items.Add(new ListItem(year - 1, year - 1));
ddlYear.Items.Add(new ListItem(year, year));
ddlYear.Items.Add(new ListItem(year + 1, year + 1));
ddlYear.Items.Add(new ListItem(year + 2, year + 2));
ddlYear.Items.Add(new ListItem(year + 3, year + 3));
ddlYear.Items.Add(new ListItem(year + 4, year + 4));
ddlYear.Items.Add(new ListItem(year + 5, year + 5));
..........................................................................................................
public void GetMyMonthList(DropDownList MyddlMonthList,bool SetCurruntMonth)
{
DateTime month = Convert.ToDateTime("1/1/2000");
for (int i = 0; i < 12; i++)
{
DateTime NextMont = month.AddMonths(i);
ListItem list = new ListItem();
list.Text = NextMont.ToString("MMMM");
list.Value = NextMont.Month.ToString();
MyddlMonthList.Items.Add(list);
}
if (SetCurruntMonth == true)
{
MyddlMonthList.Items.FindByValue(DateTime.Now.Month.ToString()).Selected = true;
}
}
Information
CREATE TABLE [dbo].[Tbl_BarCode](
BarCode int NOT NULL PRIMARY KEY,
CombinedId AS 'ABCD-' + CAST(BarCode as varchar(16)) ,
[BarcOdeDescription] [nvarchar](50) NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] smalldatetime,
BarCode int NOT NULL PRIMARY KEY,
CombinedId AS 'ABCD-' + CAST(BarCode as varchar(16)) ,
[BarcOdeDescription] [nvarchar](50) NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] smalldatetime,
Information
URL rewrining using web.config and URL rewriting using global.asax
URL rewrining using web.config:
URL rewriting in web.config is only use for small number of pages. Here you have to rewrite every page manually in web.config. I am writing sample code for 4 urls.
xml version="1.0"?>
<configuration>
<urlMappings enabled="true">
<add url="~/About-company.aspx"
mappedUrl="~/index.aspx?id=1" />
<add url="~/About-products.aspx"
mappedUrl="~/index.aspx?id=2" />
<add url="~/Contact-us.aspx"
mappedUrl="~/index.aspx?id=3" />
<add url="~/our-team.aspx"
mappedUrl="~/index.aspx?id=4" />
urlMappings>
. . .
configuration>
URL rewriting using global.aspx:
This very simple way and very use full. In this way we can rewrite N number of pages and there is no need extra server configuration. Only you have to use Application_BeginRequest event. Inside this event use Context.RewritePath method to set which URL will execute internally in code behind. Here is the code:
string NewsID = CurrentPath.Substring(CurrentPath.IndexOf("/"));
HttpContext MyContext = HttpContext.Current;
MyContext.RewritePath("/news-show.aspx?News=" + NewsID);
}
}
URL rewrining using web.config:
URL rewriting in web.config is only use for small number of pages. Here you have to rewrite every page manually in web.config. I am writing sample code for 4 urls.
xml version="1.0"?>
<configuration>
<urlMappings enabled="true">
<add url="~/About-company.aspx"
mappedUrl="~/index.aspx?id=1" />
<add url="~/About-products.aspx"
mappedUrl="~/index.aspx?id=2" />
<add url="~/Contact-us.aspx"
mappedUrl="~/index.aspx?id=3" />
<add url="~/our-team.aspx"
mappedUrl="~/index.aspx?id=4" />
urlMappings>
. . .
configuration>
URL rewriting using global.aspx:
This very simple way and very use full. In this way we can rewrite N number of pages and there is no need extra server configuration. Only you have to use Application_BeginRequest event. Inside this event use Context.RewritePath method to set which URL will execute internally in code behind. Here is the code:
void Application_BeginRequest(object sender, EventArgs e)
{
// Get the current path
string CurrentURL_Path = Request.Path.ToLower();
if (CurrentURL_Path.StartsWith("/news/"))
{
CurrentURL_Path = CurrentURL_Path.Trim("/");{
// Get the current path
string CurrentURL_Path = Request.Path.ToLower();
if (CurrentURL_Path.StartsWith("/news/"))
{
string NewsID = CurrentPath.Substring(CurrentPath.IndexOf("/"));
HttpContext MyContext = HttpContext.Current;
MyContext.RewritePath("/news-show.aspx?News=" + NewsID);
}
}
Information
Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.
.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter
The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.
The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...
Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.
.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter
The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.
The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...
Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.
Information
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets invoked on each request and the second set which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization request.
Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.
Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();
}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
End Sub
Here we make use of the Application_Error() method to capture the error using the Server.GetLastError().
Conclusion:
In this article, we learnt that Global.asax is a file used to declare application-level events and objects. The file is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End, and so on. I would encourage you to explore the methods corresponding to the events and analyze the best possible methods to use them in your application, if needed.
Information
Introduction
Introduction
public class Global:System.Web.HttpApplication
Here I will explain what is the purpose of Global.asax file and how we can use Global.asax file in asp.net.
Description:
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 fired for every request
Events which are not fired for every request
Now I will explain about
Events which are 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.
Now we will see
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.
Now we will see all these events with 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;
}
how to add Global.asax.cs file in asp.net or how to add Code behind file for Global.asax in asp.net
Introduction
Here I will explain how to add code behind file for Global.asax in asp.net.
Description:
In previous post I explained clearly about Global.asax file uses and events in asp.net. Here I will explain how to add code behind file to Golbal.asax in asp.net. In one of my project I started writing code in Global.asax file but we decided to write code in Global.asax.cs file code I tried to search for that one but that is not available in our application at that I learn one thing that is we need to add Global.asax and Global.asax.cs these files to our application. For that one first right click on solution explorer and select Add New item
After that select Global Application class file and click ok now Global.asax file added successfully to our application
After add our Global.asax file to application that would be like this
And our Global.asax file contains code like this
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. } </script> |
Now our requirement is to add Global.asax.cs file to our code for that again right click on solution explorer and select Add new item another wizard will open in that select Class file and give name as Global.asax.cs and click Add
After click Add that will show one warning message like this now click yes
After adding our Global.asax.cs file we need make some changes to use Global.asax.cs file those are first remove entire script code from your Global.asax file
<script runat="server"> --------------------------- --------------------------- --------------------------- </script> |
And change this line in Global.asax file to
<%@ Application Language="C#" %> |
To
<%@ Application Language="C#" CodeBehind="~/App_Code/global.asax.cs" Inherits="Global" %> |
Now open Global.asax.cs file and change this like
public class Global |
To
Subscribe to:
Posts (Atom)