Wednesday, July 27, 2011

Tips on Exception Handling

1. Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not. Lot of developers uses this handy method to ignore non-significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

2. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

3. Always catch only the specific exception, not generic exception.
Good:
Private Sub ReadFromFile (fileName As String)
Try
// read from file.
catch (FileIOException ex)
// log error.
// re-throw exception depending on your case.
Throw
End Try
End Sub

Not Good:
Private Function ReadFromFile (fileName As String) As String
Try
// read from file.
Catch (Exception ex)
// Catching general exception is bad... we will never know whether
// it was a file error or some other error.
// Here you are hiding an exception.
// In this case no one will ever know that an exception happened.
Return String.Empty
End Try
End Function

4. No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an 'unexpected general error', this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to 'ignore and proceed'.

5. When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.
Good:
Catch
// do whatever you want to handle the exception
throw
Not Good:
catch (Exception ex)
// do whatever you want to handle the exception
throw ex

6. Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

7.Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

8. Write your own custom exception classes if required in your application. Do not derive your custom exceptions from the ApplicationException class. Instead, inherit from base class System.Exception.

Good bye Exceptional Handling

Some Quick help

1) Make a field readonly:
txtName.Attributes.Add("readonly", "readonly")

2) Keyboard enter button is pressed in the textbox and fire an event:
This is done to ensure that when the keyboard enter button is pressed in the textbox we fire the "btnButton" click event
txtName.Attributes.Add("onkeypress", "return WebForm_FireDefaultButton(event, '" + btnButton.ClientID + "')")

3) To set the focus on a control like Textbox when the page loads.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "focus", "setTimeout(""try{ document.getElementById('" & txtName.ClientID & "').focus(); } catch(err){}"", 1200);", True)

4) To directly access the key and value of the resource file.
lblName.Text = GetGlobalResourceObject("ABC", "Name") ////Where Main refers for a file “ABC.resx”


5) To disable controls of a form/page

// Below is the method definition
Public Sub DisableControl(ByVal ctrl As Control)
For Each subctrl As Control In ctrl.Controls
DisableControl(subctrl)
Next

If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Enabled = True
CType(ctrl, TextBox).ReadOnly = True
ElseIf TypeOf ctrl Is RadioButtonList Then
CType(ctrl, RadioButtonList).Enabled = False
ElseIf TypeOf ctrl Is CheckBox Then
CType(ctrl, CheckBox).Enabled = False
ElseIf TypeOf ctrl Is RadioButton Then
CType(ctrl, RadioButton).Enabled = False
End If
End Sub

Monday, August 16, 2010

What are events in GLOBAL.ASAX file?

The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The Global.asax file contains the following events:
Application_Init: Fired when an application initializes or is first called. It is invoked for all HttpApplication object instances.
Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
Application_Error: Fired when an unhandled exception is encountered within the application.
Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed. It is fired only once during an application's lifetime.
Application_BeginRequest: Fired when an application request is received. It is the first event fired for a request, which is often a page request (URL) that a user enters.
Application_EndRequest: The last event fired for an application request.
Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has finished executing an event handler.
Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
Application_PreSendContent: Fired before the ASP.NET page framework send content to a requesting client (browser).
Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
Session_Start: Fired when a new user visits the application Web site.
Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

Difference between ASP and ASP.Net

ASP session state is dependent on IIS process very heavily. So if IIS restarts ASP session variables are also recycled

ASP.NET session can be independent of the hosting environment thus ASP.NET session can maintained even if IIS reboots.

ASP session only works when browser supports cookies

ASP.NET session can be used with browser side cookies or independent of it.

ASP session state has no inherent solution to work with Web Farms

ASP.NET session can be stored in state server and SQL SERVER which can support multiple servers.

ASP is interpreated

ASP.Net is complied

ASP uses ADO

ASP.Net uses ADO.Net

ASP, there was no server controls. You have to write all html tags manually

ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form

ASP uses vb script for server side coding. Vb Script is not supported any more in ASP.NET

nstead, ASP.NET supports more languages including C#, VB.NET, J# etc.

ASP did not support Page level transactions

SP.NET supports Page level transactions

ASP does not offer support for Web Services and rich data structures like DataSet which allows disconnected data processing.

ASP.NET offers support for Web Services and rich data structures like DataSet which allows disconnected data processing.

ASP had maximum of 4 built in classes like Request, Response, Session and Application

ASP.NET using .NET framework classes which has more than 2000 in built classes

ASP has Mixed HTML and coding logic

Separate code and design logic possible

Limited development and debugging tools available

Variety of compilers and tools available including the Visual studio.Net

No in-built support for XML

Full XML Support for easy data exchange

No fully distributed data source support.

Fully distributed data source support

Poor Error handling system

Full proof error handling possible

Limited OOPS support

Completely Object Oriented.

Sunday, August 8, 2010

How to freeze Gridview columns in ASP.net?

I am writing below blog from one of my last project experience. I was doing a project called timesheet where i was in need of showing lots of details of the user whose timesheet is been submitted. For Example: Name, DOB, Department, Type, Designation and all the 30/31 days of the months.

Since it became difficult to show all the information in gridview becuase there is no built in functionality of scrolling. So I thought of freezing some of the columns of the gridview and keeping all other columns as it is.

I used CSS to handle this.

Find below the html:

<style type="text/css">

.Container

{

overflow: auto;

}

.FreezeCell

{

background-color:#d9e9ff;

position: relative;

font-family:Segoe UI;

font-size:11px;

font-weight:normal;

cursor: auto;

left: expression(document.getElementById("GridView1").scrollLeft-1);

}

.FreezeHeader

{

background-color:#d9e9ff;

font-weight:normal;

font-family:Segoe UI;

font-size:11px;

position: relative;

cursor: auto;

top: expression(document.getElementById("GridView1").scrollTop-1);

z-index: 10;

}

.FreezeHeader.locked

{

z-index: 99;

}

style>

<div id="div1" class="Container" style="width: 200px; color: #4977bc;

border-style: solid; border-width: thin;" runat="server">

<asp:GridView ID="GridView1" CssClass="GridView" runat="server" Width="250px"

GridLines="Both" BorderWidth="1px" AutoGenerateColumns="false">

<HeaderStyle BackColor="#d9e9ff" Font-Bold="false" Font-Names="Segoe UI" Font-Size="11px" />

<Columns>

<asp:BoundField DataField="name" HeaderText="Name" HeaderStyle-Width="100px" ItemStyle-CssClass="FreezeCell"

HeaderStyle-CssClass="FreezeCell">

<ItemStyle VerticalAlign="Top" BackColor="#ffffff" Width="100px"/>

asp:BoundField>

<asp:BoundField DataField="age" HeaderText="Age" HeaderStyle-Width="50px" >

<ItemStyle VerticalAlign="Top" Width="50px" HorizontalAlign="center" BackColor="#ffffff" />

asp:BoundField>

<asp:BoundField DataField="sex" HeaderText="Sex" HeaderStyle-Width="50px"

HeaderStyle-HorizontalAlign="left">

<ItemStyle VerticalAlign="Top" Width="50px" HorizontalAlign="left" BackColor="#ffffff" />

asp:BoundField>

<asp:BoundField DataField="datetime" HeaderText="DateTime" HeaderStyle-Width="15px"

HeaderStyle-HorizontalAlign="left">

<ItemStyle VerticalAlign="Top" Width="150px" HorizontalAlign="left" BackColor="#ffffff" />

asp:BoundField>

Columns>

asp:GridView>

div>

C# Source Code:

using System;

using System.Data;

using System.Configuration;

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;

using System.Collections.Generic;

public class PersonInfo

{

private string name;

public string Name

{

get { return name; }

set { name = value; }

}

private string age;

public string Age

{

get { return age; }

set { age = value; }

}

private string sex;

public string Sex

{

get { return sex; }

set { sex = value; }

}

private DateTime datetime;

public DateTime DateTime

{

get { return datetime; }

set { datetime = value; }

}

}

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

List<PersonInfo> listPersonInfo = new List<PersonInfo>();

for (int i = 0; i <>

{

PersonInfo p = new PersonInfo();

p.Name = "Ashraf" + i.ToString();

p.Age = "23" + i.ToString();

p.Sex = "Male";

p.DateTime = DateTime.Now;

listPersonInfo.Add(p);

}

GridView1.DataSource = listPersonInfo;

GridView1.DataBind();

}

}

}

This works perfectly for me.