Thursday, 29 November 2012

Global Exception Handling in different types of applications

1. Asp.net

System.Web.HttpApplication.Error event

Usually setup in Global.asax

MSDN: How to: Handle Application-Level errors.
Also see:
Complete example for Error Handlers

2. WinForms:

System.Windows.Forms.Application.ThreadException
event
MSDN: Application.ThreadException event
Blog: Top-Level Exception Handling In Windows Forms Applications
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event. 
AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

3. Console applications (also should work with Windows Services – havent checked this though):
System.AppDomain.UnhandledException event
MSDN: AppDomain.UnhandledException Event

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
4. WPF:

System.Windows.Application.DispatcherUnhandledException

MSDN: Application.DispatcherUnhandledException Event
public App() :base() //App.xaml.cs
{
        this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

Also see: WPF Global Exception Handler (StackOverflow)

5. Silverlight:

Application.UnhandledException Event

MSDN: Application.UnhandledException Event
Also see:
Silverlight Error Handling
public App()//App.xaml.cs
{
        this.UnhandledException += this.Application_UnhandledException;
        InitializeComponent();
}
private void Application_UnhandledException(object sender,ApplicationUnhandledExceptionEventArgs e)
{
        //handle exception here.
}
Also take a look at the EntLib Patterns and Practices pack for Silverlight (codeplex.com) {Logging Application Block}

Monday, 19 November 2012

LINQ : LINQPad

 LINQPad lets you interactively query databases in a modern query language: LINQ.  Kiss goodbye to SQL Management Studio
LINQPad supports everything in C# 4.0/5.0 and Framework 4:
And that's not all - there's also specific support for:
And LINQPad is more than a LINQ tool: it's an ergonomic C#/VB/F# scratchpad that instantly executes any expression, statement block or program with rich output formatting – the ultimate in dynamic development. Put an end to those hundreds of Visual Studio Console projects cluttering your source folder

LINQPad Screenshot

Source : http://www.linqpad.net/

Linq : Gettng T-Sql Squery With ToTraceString() method

We can use ObjectQuery.ToTraceString() to figure out what is going on behind the scenes. ToTraceString() returns the TSQL (assuming you are using the SQL Server provider) for that ObjectQuery.

Since we can see the TSQL code that EF generates I can poke around and figure what is going around behind the curtain.

For example if you ran this in LINQPad

void Main()
{
    PubsModel.pubsEntities context =
new
PubsModel.pubsEntities(EF_CONNECTION_STRING);

   
// Entity SQL:
    // Returns ObjectQuery<T> directly
   
ObjectQuery<author> esqlq = context.CreateQuery<author>(
       
"SELECT VALUE a FROM authors AS a"
);
    esqlq.ToTraceString().Dump(
"--CreateQuery"
);
   
   
// Linq to Entities
    // ObjectQuery<T> implements IQueryable<T>
    // This statement returns an ObjectQuery<T>
    // casted as IQueryable<T>
   
IQueryable<author> linqq = from a in context.authors select
a;   
   
// So it must be cast back to execute ToTraceString()
   
((ObjectQuery)linqq).ToTraceString().Dump("--Linq Query"
);
}


You would get:

--CreateQuerySELECT [Extent1].[au_id] AS [au_id], [Extent1].[au_lname] AS [au_lname], [Extent1].[au_fname] AS [au_fname], [Extent1].[phone] AS [phone], [Extent1].[address] AS [address], [Extent1].[city] AS [city], [Extent1].[state] AS [state], [Extent1].[zip] AS [zip], [Extent1].[contract] AS [contract]
FROM [dbo].[authors] AS [Extent1] 
--Linq QuerySELECT [Extent1].[au_id] AS [au_id], [Extent1].[au_lname] AS [au_lname], [Extent1].[au_fname] AS [au_fname], [Extent1].[phone] AS [phone], [Extent1].[address] AS [address], [Extent1].[city] AS [city], [Extent1].[state] AS [state], [Extent1].[zip] AS [zip], [Extent1].[contract] AS [contract]
FROM [dbo].[authors] AS [Extent1] 

Wednesday, 7 November 2012

Using Custom Attributes in C#

Introduction
Attributes give you the ability to store additional information with your application or assembly metadata, which can be queried at runtime by using the .NET Frameworks Reflection capabilities. For example, attributes could be used to indicate whether a class is serializable, or which field in a database a particular property should be written to. In this article we will create a simple custom attribute, and demonstrate how easy it is to retrieve this information at run-time.
Creating our Custom Attribute class
To create our custom attribute class, we will descend from the System.Attribute class as follows :-
public class DescriptionAttribute: Attribute {
 private string description;

 public string Description {get {return description;}}

 public DescriptionAttribute(string description) {
  this.description = description;
 }
}
There is nothing too complicated about our attribute class. It simply allows for a description string to be associated with it (passed into the constructor), and exposes this as a property which can be queried at runtime.
Using our Custom Attribute
We will start off by creating a test class, and use our attribute to associate a description with this class. To do this, we use the following syntax :-
[DescriptionAttribute("This is our test class")]
class AttributeClass {}
or
[Description("This is our test class")]
class AttributeClass {}

Both methods are identical in functionality, and are both valid syntax. The compiler will initially attempt to locate an attribute using the specified class name. If it is unsuccessful, the compiler will append 'Attribute' to the end of the class name and search again. As it is common practice to declare attribute classes using the Attribute suffix but reference them without it, this is the approach I will be taking for the rest of this article.
Querying for our Custom Attribute
Once we have associated our attribute with various source code elements, we can query the metadata of these elements at run-time by using the .NET Framework Reflection classes. Reflection can be used to gain information about every aspect of our class or assembly, including the class or assembly itself.
First we need to extract the metadata for our class, which we do by using the typeof function :-
Type type = typeof(AttributeClass);
The custom attribute information is retrieved into an object array by calling the Type.GetCustomAttributes() function. The method signatures for both overloaded versions are as follows :-
public object[] GetCustomAttributes(
 bool inherit  //Search the members inheritance heirarchy
);
public object[] GetCustomAttributes(
 Type attributeType, //Type of attribute to search for.
 bool inherit  //Search the members inheritance heirarchy
);
We can now retrieve the attribute information for our class, and loop through this array to obtain information about each attribute:-
object[] attributes = type.GetCustomAttributes(true);
foreach (object attribute in attributes) {
 Console.Write("  {0}", attribute.ToString());
 DescriptionAttribute da = attribute as DescriptionAttribute;
 if (da != null)
  Console.WriteLine(".Description={0}", da.Description);
 else
  Console.WriteLine();
}
We are using the as operator to typecast from System.Object to our custom attribute class, so we can access our Description property. Using this technique, if the typecast is invalid our DescriptionAttribute reference will be set to null. If we had used an explicit type cast, for example :-
DescriptionAttribute da = (DescriptionAttribute)attribute;
and the cast was invalid, a System.InvalidCastException exception would be thrown at run-time.
Our output should look something like this :-
Console Output
Attributes can also be associated with class members and properties in the same way as we did for the class. Lets add some more elements to our class and annotate them with our attribute:-
[Description("Here is a public field")]
public string PublicField;

[Description("Here is a private field")]
private string privateField;

[Description("Here is a protected field")]
protected string protectedField;

[Description("Here is a static field")]
static private string staticField;

[Description("Here is a public property")]
public string PublicProp {get {return privateField;}}
Extracting the attribute information for all members of a class is slightly more involved than our previous example. We need get details of each member in the class, and then iterate through the member's attributes :-
MemberInfo[] members = classType.GetMembers();
foreach (MemberInfo member in members)
 ParseAttributes(member);
As the logic to parse the attributes for a class and its members is identical, lets move it to a method so we don't need to duplicate the code. All the type information classes we have used descend from the MemberInfo class, so we will use that in our method's signature :-
static void ParseAttributes(MemberInfo type) {
 object[] attributes = type.GetCustomAttributes(true);
 Console.WriteLine("{0} {1} attributes", type.MemberType.ToString(), type.Name);

 if (attributes.Length != 0) {
  foreach (object attribute in attributes) {
   Console.Write("  {0}", attribute.ToString());
   DescriptionAttribute da = attribute as DescriptionAttribute;
   if (da != null)
    Console.WriteLine(".Description = {0}", da.Description);
   else
    Console.WriteLine();
  }
 }
 else
  Console.WriteLine("  {0} has no attributes", type.Name);
}
It is almost identical to our original code, but now we also check to see whether the member has any attributes, and report if it doesn't. We also use
type.MemberType.ToString()
to extract the type of member we are currently parsing. The output should be as follows :-
Console Output
But where is the information for privateField, staticField and protectedField? When we made the call to classType.GetMembers() we used one of two possible overloaded signatures for that method, and the one we chose returns public members only. The alternative signature looks like this :-
public MemberInfo[] GetMembers(BindingFlags bindingAttr);
The bindingAttr parameter is a bitmask of one or more BindingFlags enumeration members, to indicate which members we are interested in. For a detailed list of all possible values, consult the .NET Framework Help.
The output also showed members declared in the System.Object class, which gives more us information than we desire. We will change our call so we can see the missing members, and suppress the ones in System.Object :-
MemberInfo[] members = classType.GetMembers(
 BindingFlags.Public |      //Get public members
 BindingFlags.NonPublic |   //Get private/protected/internal members
 BindingFlags.Static |      //Get static members
 BindingFlags.Instance |    //Get instance members
 BindingFlags.DeclaredOnly);//Get only members declared in classType
Our output now looks like this :-
Console Output
You will notice that type information for the class constructor, and the getter method for PublicProp were also parsed. Technically this is correct, as they do meet the rules governed by the BindingFlags combination we specified. Although they aren't members we have explicitly created in our class definition, they were created by the C# compiler. It is possible to associate more than one attribute with a member. For example :-
[SomeOther]
[Description("Here is a public field")]
public string PublicField;
You notice from the above method that, unlike methods or class constructors, if an attribute's constructor takes no parameters it is not necessary to specify the () brackets, although it is valid to do so.
Positional vs Named Parameters
Attributes can have both positional and named parameters. Positional parameters are any parameters that were specified in the attribute's constructor. Named parameters are any public members of the attribute class, and should be initialized in the attribute's constructor. To specify a named parameter when using an attribute, use the following syntax :-
[Attribute(ParamName = paramValue)]
When using positional parameters in conjunction with named parameters, any positional parameters must be specified first, and in the same order as they were declared in the constructor. Named parameters can be specified in any order, providing they follow the positional parameters. We will now change our DescriptionAttribute and AttributeClass classes to demonstrate using named parameters and positional parameters. :-
public class DescriptionAttribute: Attribute {
 private string description;
 public string Description {get {return description;}}

 //**ADDED**
 private string extraInfo;
 public string ExtraInfo {get {return extraInfo;} set {extraInfo = value;}}

 public DescriptionAttribute(string description) {
  this.description = description;
  this.extraInfo = "";
 }
}

[Description("This is our test class")]
public class AttributeClass {
 [Description("Here is a public field")]
 public string PublicField;

 [Description("Here is a private field")]
 private string privateField;

 [Description("Here is a protected field")]
 protected string protectedField;

 //**CHANGED**
 [Description("Here is a static field", ExtraInfo = "It is also private")]
 static private string staticField;

 [Description("Here is a public property")]
 public string PublicProp {get {return privateField;}}
}
We will also change our ParseAttributes method to show the value of ExtraInfo, if it has been set :-
..
DescriptionAttribute da = attribute as DescriptionAttribute;
if (da != null) {
 Console.WriteLine(".Description = {0}", da.Description);
 //**ADDED**
 if (da.ExtraInfo != "")
  Console.WriteLine("  {0}.ExtraInfo = {1}",
   attribute.ToString(), da.ExtraInfo);
}
..
Running the program will produce the following output :-

Console Output
Specifying how Attributes can be used
The context in which it is valid to use a custom attribute can be specified by associating the AttributeUsage attribute with the custom attribute class. It allows you to specify which members it is valid for the custom attribute to be used on, whether the attribute can be inherited in derived classes and overriding members, and whether the attribute can be associated with a member multiple times :-
[AttributeUsage(
   AttributeTargets validon, //Positional
   AllowMultiple=bool,       //Named
   Inherited=bool            //Named
)]
The validon positional parameter is a bitmask of one or more AttributeTargets enumerated members, and is used to specify which member elements an attribute can be used with. The AllowMultiple named parameter specifies whether the attribute can be specified multiple times against the same member. The Inherited named parameter specifies whether the attribute should be inherited in descendant classes.
We will now associate another DescriptionAttribute attribute with our class declaration. As attributes by default have AllowMultiple set to false, we will need to use the AttributeUsage attribute to enable us to do this:-
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class DescriptionAttribute: Attribute {
..
[Description("This is our test class")]
[Description("It demonstrates using the DescriptionAttribute attribute")]
public class AttributeClass {
Summary
Attributes are an extremely useful and flexible feature of the .NET Framework. They can be used to associate extra information with the metadata of your assemblies, classes, and class members. It is relatively straightforward to create custom attributes, associate them with source code elements, and query them at runtime.

Monday, 12 March 2012

F5 option is disabled in Visual Studio

If you encounter this situation that green play button, f5 key or Start Debugging option is disabled in visual studio.
Cause:
You have more than one project in Visual Studio solution but none of them is set up as a “Set as Startup Project”.
Solution:
Right click on one of the project and click on the “Set as Startup Project” now the Start green play button, F5 key and Start Debugging option will be enabled

Saturday, 26 November 2011

Exception Handling Interview Questions

What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.


What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
                try
                catch
                finally
2. Use error events to deal with exceptions within the scope of an object.
                Page_Error
                Global_Error
                Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.


Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.


Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.


What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.


Will the following code block compile?
try
{
     throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
     Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
}


No, the following compile time error is reported.
A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').



Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.


What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class.

For example, the following code defines a class for the UserLoggedOnException:


public class UserLoggedOnException : System.ApplicationException
{
     // Exception constructor (overloaded).
     public UserLoggedOnException()
     : this("The user is already logged on to the server", null)
     {
     }
     public UserLoggedOnException(string message)
     : this(message, null)
     {
     }
     public UserLoggedOnException(string message, Exception inner)
     : base(message, inner)
     {
     }
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.


What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.


Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.


Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:


As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.


Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
     // Get the error.
     Exception ex = Server.GetLastError();
     // Store the message in a session object.
     Session["Error"] = ex.Message;
     // Clear the error message.
     Server.ClearError();
     // Redisplay this page.
     Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:


Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
     // Display error. if any.
     if (Session["Error"] != null)
     {
     litError.Text = "The following error occurred:
     " +
     Session["Error"].ToString();
     // Clear the Session state variable.
     Session["Error"] = null;
     }
}


Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.


Is the following code legal?
try
{
     Response.Write("Try block executed");
}
finally
{
     Response.Write("Finally block executed");
}


Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.


What is wrong with using the following type of exception handler?
catch(Exception E)
{
     //Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.




Will the second catch block handle the exception thrown by the first catch block?
try
{
     throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
     throw new Exception();
}
catch(Exception E)
{
     Response.Write(E.Message);
}


No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.


What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
     throw new Exception();
     try
     {
          Response.Write("Hello");
     }
     catch (Exception E)
     {
          Response.Write(E.Message);
     }
}

The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block

Exception Handling

Error handling is very important for any serious application. It is very crucial that the application is capable of detecting the errors and take corrective measures to the maximum possible extend. If the error situation is beyond the control of the application, it should report the situation to the user/administrator so that an external action can be taken.
The following are the most common ways of handling exceptions in an ASP.NET web application.
  1. Structured Exception Handling
  2. Error Events
  3. Custom Error Pages
Structured Exception Handling
The most popular error handling is Structured Exception Handling (SEH). Most of us are familiar with it in the form of try..catch blocks. All of us use SEH a lot in whatever application that we are working on. The primary focus of SEH is to make sure that a block of code is executed correctly, and if an exception takes place, we have another piece of code which can take care of the exception and take some corrective measures if possible.
SEH is used to protect the application from an exceptional situation where something unexpected happens. For example the application tries to connect to a database server and the server is not available. It is an exceptional situation or an exception :-). If such a case happens the developer can handle the situation in the catch block and take the necessary action. I have seen smart developers making use of SEH for the application logic too. for example, assume that the developer needs to open a file and display the content. Ideally he needs to check if the file exists first and then if it exists open it as follows. (This kind of programming is called DEFENSIVE Programming).
1.If file exists    
2.    work with the file 
3.else    
4.   take action 
5.end if
But the developer can simply use a try..catch block to open the file without even checking if the file exists as 1.try    
2.     just work with the file 
3.catch 
4.     file-does-not-exist-exception    
5.     take action 
6.end try
The above approach reduces the complexity of checking for the existing of the file etc. However it adds some overhead to the system. Generating and handling an exception takes some system resources. I have also seen people using SEH to branch the code execution to a specific upper function block, from inside a series of complex nested functions.
For example function a calls b and b calls c and c calls d and d calls e and if the developer wants to transfer control to a specific location in any of the parent methods, he or she can make use of SEH. SEH is mostly used for procedure/function level error handling. Any code which access external resources like database connections, files/folders, URLs should always be inside try..catch blocks because they are most vulnerable for exceptions.
I have experienced a lot of trouble with combo boxes too and hence would recommend that any action that you do on a combo box should be inside try/catch blocks. Another area where you might consider is working with a dataaset where a null value can cause an exception.
Error Events
Most of the times we will be able to put the code into try..catch blocks. But exceptions occurs in exceptional situations. There might be several cases when we would not be able to fore-see that a given block code is vulnerable to a specific exception.
For example,
1.dim CustomerName as string = new string("jacob")
The above statement is not a candidate for an error. No one would expect that the above statement can generate an error. But what if the system memory is full? The system is not able to allocate memory for that variable and it will throw an exception. Is it practical to put every line of code in try..catch blocks and catch every possible exception with every line of code? Of course not.
The best idea is to use Error Events of ASP.NET to handle such exceptions. Error events can be used to catch exceptions which are not handled with SEH. Asp.net provides three events to handle error conditions.
  1. a. page_error
  2. b. global_error
  3. c. application_error
You can write excpetion handling code in page_error to handle any un-handled exceptions that occur inside your page. similarly global_error and application_error can be used for application-wide error handling. From within the error event (page_error, global_error or application_error) you need to find the exception which occured. Server.GetLastError() can be used to retrieve the exception which triggered the error. After you have processed the error, you should call Server.ClearError() so that the further exception processing/handlers are not called.
Custom Error Pages
Yet another way you can handle errors in ASP.NET Web applications is by using Custom Error pages. When an exception occurs you can redirect the user to a customized page which explains the error condition or just give a friendly note to the user. The scope of Custom error page is very much large that it can even detect errors which are not related to the web application. For example, if your web application is down, still you can instruct IIS to show the user a specific page.
Custom error pages can be configured in 3 different ways.
  1. 1. Configure the custom error page with IIS
  2. 2. Configure the custom error page with web.config
  3. 3. Configure the custom error page declaratively in each web form
 Configuring a custom error page with IIS

You can configure a custom error page with IIS by opening the properties window of your application.  Custom error pages in IIS work based on HTTP response codes. you can define a custom page for each HTTP error that you need to handle. The question "which error code should I handle" largely depends on your application. However, I think the following HTTP response codes may be handled in a normal web application. HTTP 401 - Unauthorized HTTP 404 - Page Not Found HTTP 408 - Request Timeout HTTP 500 - Internal Server Error HTTP 503 - Server Not Available
Configuring Custom Error Pages in Web.Config
The section if web.config can be used to configure error pages. The following example shows a typical example.
1.<customerrors defaultredirect="Error.aspx" mode="on">    
2.     <error redirect="PageNotFound.aspx" statuscode="404" />    
3.     <error redirect="InternalServerErr.aspx" statuscode="500" /> 
4.</customerrors>
Note: Custom error handling using web.config is applicable to ASP.NET resources only. For example, if a "page not found" error occurs with an aspx file, your custom error page will be displayed. However if a "page not found" error occurs for an html file, your application's error handler page will not be launched. To handle situations external to the web application, the setting needs to be configured with IIS.
Page Level Error Configuration
The error configuration on web.config has application wide scope. However, it is possible to configure the error pages for a given web form. You can specify error pages declaratively on your web form as shown in the following example.
1.<%@ page 
2.    language="vb" 
3.    AutoEventWireup="false" 
4.    codebehind="pagename.aspx.vb" 
5.    inherits="projectname.pagename" 
6.    errorPage="Error.aspx" %>
Setting on the web page supersedes the configuration setting on the web.config. In the above example, if an error occurs inside the above page (pagename.aspx) the user will be taken to "error.aspx" which might contain the details of the page. You can use Server.GetLastError() to identify the exception and can display an appropriate message to the user.