Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, March 21, 2013

ASP.Net Page Life Cycle

The general Page Life Cycle Stages are:
1. Page request - Here Page is requested by the user.
2. Start – Sets the properties such as Request, Response, IsPostBack and UICulture.
3. Page initialization - Controls on the page are available and each control's UniqueID property is set.
4. Load – Controls are loaded here if it is a PostBack request.
5. Validation – Sets the IsValid property.
6. Postback Event handling – Event handlers will be called if it is PostBack.
6. Rendering - the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
7. Unload - Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded.

Common life cycle Events:
1. PreInit – Start event of the Page life cycle and here every page controls are initialized.
2. Init – This is used to read or initialize control properties.
3. InitComplete – Used for processing tasks that require all initialization be complete.
4. PreLoad - This is used before Perform any processing that should occur before Load.
5. Load - Use the OnLoad event method to set properties in controls and establish database connections.
6. Control Event - These are control specific events such as – Button Click, DropDownIndexChanged etc.
7. Load Complete - This event is used for performing those tasks which require load has been completed.
8. PreRender - In this event page insures that all child controls are created.
9. SaveStateComplete - This event occurs after viewstate encoded and saved for the page and for all controls.
10. Render – This is not an event. The page instance calls this method to output the control’s markup, after this event any changes to the page or controls are ignored.
11. Unload – Nothing but cleanup task like closing the files, database connections etc.,

This table shows stages and corresponding Events

Stage Events/Method
Initialization of the page Page_Init
Loading of the View State LoadViewState
processing of the Post back data LoadPostData
Loading of Page Page_Load
Notification of PostBack RaisePostDataChangedEvent
Handling of PostBack Event RaisePostBackEvent
Pre Rendering of Page Page_PreRender
Saving of view state SaveViewState
Rendering of Page Page_Render
Unloading of the Page Page_UnLoad

Monday, March 18, 2013

Seriaization


Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again.

Some good uses for serialization/deserialization include: 
  1. Storing user preferences in an object.
  2. Maintaining security information across pages and applications.
  3. Modification of XML documents without using the DOM.
  4. Passing an object from on application to another.
  5. Passing an object from one domain to another.
  6. Passing an object through a firewall as an XML string. 

class Person
{
    private String personName;
    private Int32 personAge;

    public String Name
    {
        get
        {
            return personName;
        }
        set
        {
            personName = value;
        }
    }

    public Int32 Age
    {
        get
        {
            return personAge;
        }
        set
        {
            personAge = value;
        }
    }
}
Person oPerson = new Person();
oPerson.Name = "Sandeep Rauniyar";
oPerson.Age = 25;

we wanted to save a copy of this object just as it is at this very moment. We could serialize it as an XML document that would look something like this:

   
     Sandeep Rauniyar


     25

Rules of Xml serialization


1. XML Serialization serializes the public fields and properties of a class, or the parameters and return values of methods into an XML stream.

2. XML Serialization does not include methods, indexers, private fields, or read-only properties (except read-only collections). Because XML is an open standard, the resulting XML stream can be processed by any application on any platform. For example, ASP.NET Web Services use XML Serialization to create XML streams to pass as data throughout the Internet or Intranets. Conversely, deserialization takes such streams and constructs an object. 

3. The following items can be serialized using XmlSerialzer:
  • Public read/write properties.
  • Public fields.
  • Classes that implement ICollection or IEnumerable.
  • XmlElement objects.
  • XmlNode objects.
  • DataSet objects.
4. XmlSerialzer gives complete control over serializing an object into XML. For example, XmlSerialzer enables you to:
  • Specify whether a field or a property should be encoded as an element or as an attribute.
  • Specify which XML namespace to use.
  • Specify the name of an element or attribute if a field / property name is inappropriate.

XML Serialization Considerations

he following should be considered when using XmlSerialzer class:
  • Type identity and assembly information is not included. In other words, XML serialization does not maintain type fidelity. To maintain type fidelity use binary serialization instead.
  • Only public properties and fields can be serialized. To serialize non-public data use binary serialization instead.
  • A class must have a default constructor to be serialized with the XmlSerialzer class.
  • Methods cannot be serialized.
  • XmlSerialzer class can serialize classes that implement IColleciton and IEnumerable differently if they meet certain requirements.

Rules of static constructor

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Tuesday, March 5, 2013

.NET Framework release history

Generation Version number Release date Development tool Distributed with
1.0 1.0.3705.0 13 February 2002 Visual Studio .NET N/A
1.1 1.1.4322.573 24 April 2003 Visual Studio .NET 2003 Windows Server 2003
2.0 2.0.50727.42 7 November 2005 Visual Studio 2005 Windows Server 2003 R2
3.0 3.0.4506.30 6 November 2006 Expression Blend Windows Vista, Windows Server 2008
3.5 3.5.21022.8 19 November 2007 Visual Studio 2008 Windows 7, Windows Server 2008 R2
4.0 4.0.30319.1 12 April 2010 Visual Studio 2010 N/A
4.5 4.5.50709.17929 15 August 2012 Visual Studio 2012 Windows 8, Windows Server 2012

Monday, March 4, 2013

How to create custom error reporting pages in ASP.NET by using Visual C# .NET


This article describes how to use Visual C# .NET code to trap and respond to errors when they occur in ASP.NET. ASP.NET has improved the error handling options from traditional Microsoft Active Server Pages (ASP). In ASP.NET, you can handle errors at several different levels in your applications.

New features in ASP.NET

ASP.NET offers several advances in how you can handle and respond to errors. In traditional ASP, you handle errors with "On Error Resume Next" (or try-catch blocks in JScript). Alternately, if you are running Microsoft Internet Information Services (IIS) 5.0, you use the ASPError object to create a custom error reporting page. However, these approaches have their limitations.

ASP.NET provides several levels at which you can handle and respond to errors that may occur when you run an ASP.NET application. ASP.NET provides three main methods that allow you to trap and respond to errors when they occur: Page_Error,Application_Error, and the application configuration file (Web.config).

This article demonstrates how to use these new features in your ASP.NET application. Although this article describes how to provide custom error pages and general error reporting as it relates directly to ASP.NET, this article does not describe other error handling approaches such as the try-catch-finally block and the Common Language Runtime (CLR) exception system.

How to use the Page_Error method

The Page_Error event handler provides a way to trap errors that occur at the page level. You can simply display error information (as the sample code to follow does), or you can log the event or perform some other action.

Note This example displays detailed error information in the browser only for demonstration purposes. You will want to be cautious when displaying detailed information to the end user of the application, especially when the application is running on the Internet. A more appropriate action would be to display a message to the user notifying them that an error has occurred, and then actually logging the specific error details in the event log.

This example throws a null exception, which forces an error to occur in the Page_Load event handler. Follow these steps to create the initial page that will demonstrate using the Page_Error event handler. Follow these steps to add a new file named PageEvent.aspx to your project: Open Microsoft Visual Studio .NET.

In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.

In the Name text box, type PageEvent.aspx, and then click Open.





Add the following code to PageEvent.aspx: <script language=C# runat="server">  void Page_Load(object sender, System.EventArgs e)  {   throw(new ArgumentNullException());  }    public void Page_Error(object sender,EventArgs e)  {   Exception objErr = Server.GetLastError().GetBaseException();   string err = "<b>Error Caught in Page_Error event</b><hr><br>" +   "<br><b>Error in: </b>" + Request.Url.ToString() +   "<br><b>Error Message: </b>" + objErr.Message.ToString()+   "<br><b>Stack Trace:</b><br>" +                    objErr.StackTrace.ToString();   Response.Write(err.ToString());   Server.ClearError();  }  </script>  






Note In this code sample, the AutoEventWireup attribute is not explicitly set. If you do not explicitly assign a value to the AutoEventWireup attribute, the default value true is used. If you are using Visual Studio .NET to develop your applications, the Web Form template code explicitly sets the AutoEventWireup attribute value to false. There is an important difference between the default value that ASP.NET uses, and the default value that the Visual Studio .NET template code assigns to this attribute. If the AutoEventWireup attribute value is set to false, the event handlers that are declared in the .ASPX page do not fire. This may be confusing if you do not know about this functionality.

From the File menu, click Save PageEvent.aspx.

Right-click the page, and then click View in Browser to run the page. Notice that the error is thrown and reported according to the code specifications.



Note You may notice that the code issues a call to Server.ClearError. This prevents the error from continuing to theApplication_Error event handler.

In addition, you should also take note of the Inherits attribute in the @ Page directive. If Inherits is set, you must build the project before you browse to the page. If you do not build the project first, you receive the following error message: 'Project.PageEvent' is not a valid type





How to use the Application_Error method

Similar to the Page_Error event handler, you can use the Application_Error event handler to trap errors that occur in your application. Due to the event's application-wide scope, you can log of application error information or handle other application-level errors that may occur.

The sample to follow is based on the preceding Page_Error code sample and would be fired if the error in Page_Load was not trapped in the Page_Error event handler. The Application_Error event handler is specified in the Global.asax file of your application. For simplicity, the steps in this section create a new page in which to throw the exception, trap the error in theApplication_Error event handler of the Global.asax file, and write the error to the event log. The following steps demonstrate how to use the Application_Error method: Add a new file named AppEvent.aspx to your project.

Add the following code to AppEvent.aspx: <script language=C# runat="server">   void Page_Load(object sender, System.EventArgs e)   {   throw(new ArgumentNullException());   }  </script>  






Note The information discussed in the "Page_Error" section about the AutoEventWireup attribute also applies to the code sample in this step. See the information in the "Page_Error" section for more details.

From the File menu, click Save AppEvent.aspx.

Add the Application_Error event handler to the Global.asax file to trap the error that you throw in the Page_Load event handler of the AppEvent.aspx page. Notice that you must add another using statement for the System.Diagnosticsnamespace to Global.asax to use the event log.

Add the following code to the Global.asax file: using System.Diagnostics;    protected void Application_Error(object sender, EventArgs e)  {   Exception objErr = Server.GetLastError().GetBaseException();   string err = "Error Caught in Application_Error event\n" +   "Error in: " + Request.Url.ToString() +   "\nError Message:" + objErr.Message.ToString()+   "\nStack Trace:" + objErr.StackTrace.ToString();   EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);   Server.ClearError();   //additional actions...  }  







Save the Global.asax file.

In Visual Studio .NET, on the Build menu, click Build.

Right-click the page, and then click View in Browser. In this case the page will be blank, however, you should notice that a new entry has been added in the event log. This sample makes an entry in the Application log, which is accessible from the Event Viewer. After logging the error you might want to redirect the user to another more user-friendly error page, or perform some additional actions if needed.



How to use the Web.config file

If you do not call Server.ClearError or trap the error in the Page_Error or Application_Error event handler, the error is handled based on the settings in the <customErrors> section of the Web.config file. In the <customErrors> section, you can specify a redirect page as a default error page (defaultRedirect) or specify to a particular page based on the HTTP error code that is raised. You can use this method to customize the error message that the user receives.

If an error occurs that is not trapped at any of the previous levels in your application, this custom page is displayed. This section demonstrates how to modify the Global.asax file so that Server.ClearError is never called. As a result, the error is handled in the Web.config file as the last point to trap the error. Open the Global.asax file from the previous example.

Comment out the Server.ClearError line to ensure that the error surfaces in the Web.config file.

Save your changes to Global.asax. Your code should now appear similar to the following: using System.Diagnostics;    protected void Application_Error(object sender, EventArgs e)  {   Exception objErr = Server.GetLastError().GetBaseException();   string err = "Error Caught in Application_Error event\n" +   "Error in: " + Request.Url.ToString() +   "\nError Message:" + objErr.Message.ToString() +   "\nStack Trace:" + objErr.StackTrace.ToString();   EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);   //Server.ClearError();   //additional actions...  }  







Add the following code to the <customErrors> section to redirect the user to a custom page: <customErrors defaultRedirect="http://hostName/applicationName/errorStatus.htm" mode="On">  </customErrors>  





Note You must modify the file path in defaultRedirect attribute so that it references the relevant Web server and application names.

Because the errors that are trapped at this level are sent to a default error page, you must create an error page named ErrorStatus.htm. Keep in mind that you are using this method to control what is presented to the user, so this example uses an .htm page for the error page. Add the following code to ErrorStatus.htm: <HTML>  <HEAD>  <TITLE></TITLE>  <META NAME="GENERATOR" Content="Microsoft Visual Studio 7.0">  </HEAD>  <BODY>       <b>Custom Error page!</b>       <br>       You have been redirected here from the <customErrors> section of the        Web.config file.  </BODY>  </HTML>  







To test the code, save the files, build the project, and then view AppEvent.aspx in the browser. Notice that when the error is thrown, you are redirected to the ErrorStatus.htm page.



Although you can reference a default error page in the value of the defaultRedirect attribute in the <customErrors> section, you can also specify a particular page to redirect to based on the HTTP error code that is raised. The <error> child element allows for this option. For example: <customErrors defaultRedirect="http://hostName/applicationName/errorStatus.htm" mode="On">   <error statusCode="404" redirect="filenotfound.htm" />  </customErrors>  





Note The page that is specified in defaultRedirect of the <customErrors> section is an .htm file. I

Notice that the <customErrors> section includes a mode attribute that is set to On. The mode attribute is used to control how the error redirection occurs. For example, if you are developing the application, you most likely want to see the actual ASP.NET error messages and do not want to be redirected to the more user-friendly error page. The mode attribute includes the following settings: On: Unhandled exceptions redirect the user to the specified defaultRedirect page. This mode is used mainly in production.

Off: Users receive the exception information and are not redirected to the defaultRedirect page. This mode is used mainly in development.

RemoteOnly: Only users who access the site on the local computer (by using localhost) receive the exception information. All other users are redirected to the defaultRedirect page. This mode is used mainly for debugging.