Sunteți pe pagina 1din 5

What is global.asax, Events in global.asax.

global.asax file contains the code for application level and session level events.
Also known as application file.
It is an optional file, which means we may include or exclude this file from web
application.
The location for file is ROOT folder.

global.asax Events:

1. Application_Start : This event fired when application first time starts. That means
when application is started in IIS server.

2. Application_End : Fired when Application is stopped, that is when IIS stops , IIS
restarts, Server crashed, Or manually application stopped.

3. Application_Error: This is application level error handling. Whenever an


unhandled error occurred this event gets fired. If the error is handled by try-catch
block then this event will not fire.

4. Session_Start : Whenever a user send a request to a page, a new session is


starts, and at this time this Event fires.

5. Session_End : Session remain alive until user closes the browser or session time
out occurs. At the end of session Session_End event occurs.
--------------------------------------------------------------------

Error handling in asp.net application

Error handling can be done by

1. Using a simple approach that is using try –catch block. This is a performance
issue, we cannot put try-catch block everywhere.

2. In the web.config file's customErrors section.


3. In the global.asax file's Application_Error sub.
4. On the aspx or associated codebehind page in the Page_Error sub.

2. web.config: In web.config file we can set the Error mode and Custom Error
Page address, so that whenever a error occurs, it redirects the Control to
Custom Error Page. In custom error page we can write code to display the
ERROR by using “Server.GetLastError” method or redirect control flow to Home
Page.

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.web>
<customErrors defaultRedirect="error.htm" mode="On" />
</system.web>
</configuration>
We can also set the Error page for Error codes.
<customErrors mode="On" defaultRedirect="error.htm">
<error statusCode="500" redirect="error500.aspx?code=500"/>
<error statusCode="404" redirect="filenotfound.aspx"/>
<error statusCode="403" redirect="authorizationfailed.aspx"/>
</customErrors>

Modes : On, Off, RemoteOnly.

3. global.asax: We can write code here to handle the Error on Application level.
We can write code in Application_Error event to handle the Error. We can use
Server.GetLastError or redirect the control flow to Home page or any desired
page by using Response.Redirect.

4. Page_Error: We can also write code in Page_Error event which is responsible


to handle the Page level errors. Page_Error event fires whenever an error is
occurred in the page.

Error handling code also includes code to create an entry in LogFile, which
includes the details of the Error.
http://www.c-
sharpcorner.com/UploadFile/akukreja/CustomErrorHandlingASPNET11142005235614PM/CustomErrorHandlingA
SPNET.aspx

--------------------------------------------------------------------

Types of validation controls in ASP.NET

1. Required Filed validator : Attached with controls to make sure user should
enter some value.
<asp:RequiredFieldValidator ID="rfv_txt1" runat="server" ErrorMessage="Required!" ControlToValidate="txt1"/>

2. Compare Validator: Used to compare two inputs ( Ex Password and Re-


password text box)

<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Passwords don't match!"


ControlToValidate="TextBox3" ControlToCompare="textbox2" />

3. Range validator: This is used to assigned range to a text box, like integer,
dates, string etc.

<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be between 20 and 30"


ControlToValidate="RangeTextbox" Type="Integer" MinimumValue="20" MaximumValue="30" />

4. Regular Expression validator: It Using a REGEX we can validate the input,


like email address, phone no, etc.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="Textbox4" runat="server"
ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"/>

5. Custom Validator: We can create a custom validator and can call a java
script function to add our own validation logic.

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="textbox5"


ClientValidationFunction="validatenumber"
ErrorMessage="Number is not divisible by 6"/>

<script type="text/javascript">
function validatenumber(oSrc,args)
{ args.IsValid = (args.Value % 6 == 0) }
</script>

6. Validation Summary: This control is used to Show the Validation Errors.

<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" HeaderText="You received following


errors" runat="server" />

Note 1: In validation controls we can use TEXT and ErrorMessage property to


show the error message.
Text is used to display the error on page, whereas ErrorMessage is used to show
the error in Validation summary. But if text property is not present control shows
ErrorMessage.

Note 2: One important property of validation controls are ValidationGroup.


We can create validation groups so that the validation occurs for a particular
group. Suppose you have some validation controls on page and TWO different
buttons, and you want that when you click Button1 then only validation occurs
and for Button2 validation will not occurs. In this case you can set the
ValidationGroup property of all the validation controls and Button1 to create a
separate group.

<asp:RequiredFieldValidator ID="rfv_txt1" runat="server" ErrorMessage="Required!" ControlToValidate="txt1"


ValidationGroup="First" />

<asp:RequiredFieldValidator ID="rfv_txt2" runat="server" ErrorMessage="Required!" ControlToValidate="txt2"


ValidationGroup="First" />

Note 3: We can also set Style of the Error message, like back color , font, bold.

http://www.beansoftware.com/ASP.NET-Tutorials/Validation-In-ASP.NET.aspx

--------------------------------------------------------------------
What are Application variables and Session variables?

Application variables: are used to store the variable values on application level,
which means we can create such variables which are available to all the pages in
application and remains alive until the application remains alive.
For example we want to set a counter for Logged in user. For this we can create
a application variable say UserCount and can update the value of counter in
Session_Start and Session_End events in global.asax.
// to set the data
Application( ' UserCount ' ) = 'something';

// to use the data


Response.Write ( 'data is ' + Application ( ' UserCount' ) );

Session variables: are used to store the variable values on Session level, which
means the Session variables values are available only for that session.
Suppose we want to save the User Id for each logged n user. In this case we can
create Session(“UserID”) variable and can set the value for each logged in user
in Login page code.
So the UserID value will be different for each user because Session variables are
Session specific.

// to set the data


Session ( ' UserID ' ) = 'something';

// to use the data


Response.Write ( 'data is ' + Session ( ' UserID' ) );

--------------------------------------------------------------------

How to add the Java Script code block through c#.net/vb.net code?

Insert the script block programmatically. To do this, use either the


1. Page.RegisterStartupScript() or
2. Page.RegisterClientScriptBlock() method.

RegisterStartupScript insert the java script block in the end of the page, whereas
RegisterClientScriptBlock insert the java script block in the top of the page.
So if you want to insert a java script code which runs immediately after the
page loads in client side use StartUpScript. If you put the code on the top of the
page which runs immediately when page loads and your code is on the top of
the page, this code will unable to Search the Controls in the page, because this
piece of java code is being inserted and executed immediately before rendering
the other controls which are below the java script code.
If you want are inserting code which fires for some events (e.g. OnClick(),
OnChange()) you can used either method, but recommended is
ClientScriptBlock().
// Define the JavaScript function for the specified control.
string focusScript = "<script language='javascript'>" +
"document.getElementById('" + ctrl.ClientID +
"').focus();</script>";

// Add the JavaScript code to the page.


Page.RegisterStartupScript("FocusScript", focusScript);
In above code we are inserting a java script code using c# code. The above JS
code is not for a particular event also we are not creating any function was are
just declaring the code in SCRIPT block, such code runs immediately when page
loads in client side, also in this code we are searching a control using
getElemtsbyID. If we put this code on the top of page it will unable to search the
control. That’s why we use RegisterStartupScript, so that it will be in the
bottom of the page and execute after the page and control render.

if ( !Page.IsClientScriptBlockRegistered("mytest") )
Page.RegisterClientScriptBlock("myrest",
"<script>alert('Hello');</script>

Note: the name is StartUp that means we want to run the code immediately in
startup, so use RegisterStartupScript and it will goes to bottom. And to just
insert code any where you can use RegisterClientScriptBlock.

--------------------------------------------------------------------

S-ar putea să vă placă și