Monday, August 25, 2008

Exception Handling Unplugged..!!

What is Exception Handling and why do we need it?

The mark of a good, robust program is planning for the unexpected, and recovering if it does happen. Errors can happen at almost any time during the compilation or execution of a program. We can detect and deal with these errors using Exception Handling. Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. At the heart of the .NET Framework is the Common Language Runtime (CLR) which in addition to acting as a virtual machine and interpreting and executing IL code on the fly, performs numerous other functions such as type safety checking, memory management, garbage collection and Exception handling. The .NET framework contains lots of standard exceptions. It allows you to define how the system reacts in unexpected situations like 'File not found' , 'Out of Memory' , bad logic, non-availability of operating system resources other than memory, 'Index out of bounds' and so on.

When the code which has a problem, is executed, it 'raises an exception'. If a programmer does not provide a mechanism to handle these anomalies, the .NET run time environment provides a default mechanism, which terminates the program execution. This mechanism is a structured exception handling mechanism




Exceptions in C#

Exceptions in C# are represented by objects with type names representative of the type of error that occurred in the program. Exceptions in C# provide a structured, uniform, and type-safe way of handling both system level and application level error conditions. . In C#, all exceptions must be represented by an instance of a class type derived from System.Exception. System.Exception class is the base type of all exceptions.An object of an exception is that which describes the exceptional conditions occuring in a code that means, we are catching an exception, creating an object of it, and then throwing it.

Like other modern and structured programming languages, C# also provides a rich mechanism of Exception Handling. Exceptions are handled in C# using the 'try/catch/finally' statements. These keywords are also named as Structured Exception Handling (SEH). The code which 'may cause an exception' is enclosed within a 'try' block as shown below:

try
{
// this code may cause an exception.
}

Your code feels safe now as it has been protected. If an exception does occurs in the code enclosed within the 'try' block, you can handle it. To handle an exception, attach a 'catch' block to the 'try'.

try
{
// this code may cause an exception.
// If it does cause an exception, the execution will not continue.
// Instead,it will jump to the 'catch' block.
}
catch (Exception ex)
{
// I get executed when an exception occurs in the try block.
// Write the error handling code here.
}

Having understood the basic syntax, let's rewrite the example ShowingExceptions

// Example ShowingExceptions using structured exception handling the C# way.

class ShowingExceptions
{
static void main()
{
Console.Write("Please enter a number :");
string str = Console.ReadLine();
double dNo;
}
try
{
dNo = double.Parse(str);
Console.WriteLine("Parsing successfully without errors");
}
catch(Exception ex)
{
Console.WriteLine("Error : {0} is not a valid number", str);
}

}

Execution :
Please enter a number : Hello

Output:

Error: Hello is not a valid number.

Thus here we notice that when the exception does occur, the program stops executing code from the try block and immediately jumps to the catch block. This is why the output, " Parsing successfully without errors " is not displayed when the exception occurs.

NOTE:

It is not a good idea to display the raw exception message to the user. Instead, show a friendly message to the user and log the actual exception message to some log file for trouble shooting purposes.

Moreover, in the above example, we are handling all types of exceptions. But it is a bad practise to catch all exceptions. You should catch only specific exceptions which are expected in the specific code block. For example, if you are attempting to allocate the memory, you may catch 'System.OutOfMemoryException' and if you are performing mathematical operations, you may catch
'System.DivideByZeroException' exception. Also, you can create and throw custom exceptions.

Eg:



ArgEx ArgumentException = new ArgumentException("You entered bad data");
throw ArgEx;

Ok, But what about the finally block?

C# provides the finally block to enclose a set of statements that need to be executed regardless of the course of control flow. So as a result of normal execution, if the control flow reaches the end of the try block, the statements of the finally block are executed. Moreover, if the control leaves a try block as a result of a throw statement or a jump statement such as break , continue, or goto, the statements of the finally block are executed. The finally block is basically useful in three situations: to avoid duplication of statements, to release resources after an exception has been thrown and to assign a value to an object or display a message that may be useful to the program.

Let's see the example Showing Exceptions again:

// Example ShowingExceptions using finally
class ShowingExceptions
{
static void main()
{
Console.Write("Please enter a number :");
string str = Console.ReadLine();
double dNo;
}
try
{
dNo = double.Parse(str);
Console.WriteLine("Parsing successfully without errors");
}
finally
{
Console.WriteLine("Storing the number as 1.0");
dNo = 1.0; // dNo is assigned the value 1.0 irrespective of an error.
}
}

What are the other Exception Classes?

Here's a list of few Common Exception Classes:

System.ArithmeticException-A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException


System.ArrayTypeMismatchException-Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.


System.DivideByZeroException-Thrown when an attempt to divide an integral value by zero occurs.


System.IndexOutOfRangeException-Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.


System.InvalidCastExceptionThrown when an explicit conversion from a base type or interface to derived types fails at run time.


System.MulticastNotSupportedException-Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.


System.NullReferenceException-Thrown when a null reference is used in a way that causes the referenced object to be required.


System.OutOfMemoryException-Thrown when an attempt to allocate memory (via new) fails.


System.OverflowException-Thrown when an arithmetic operation in a checked context overflows.

Best Interview

One of the best interviews!!!




Interviewer: Tell me about yourself.




Candidate: I am SAMEER GUPTA. I did my Tele Communication engineering from
BabanRao Dhole-Patil Institute of Technology.




Interviewer: BabanRao Dhole-Patil Institute of Technology? I had never heard
Of this college before!




Candidate: Great! Even I had not heard of it before getting an admission
Into it . What happened is - due to cricket world cup I scored badly! In 12th.I
Was getting a paid seat in a good college. But my father said (I prefer to
Call him 'baap') - "I can not invest so much of money".(The baap actually said
- "I will never waste so much of money on you"). So I had to join this
College. Frankly speaking this name - BabanRao Dhole-Patil, can at the most be
Related to a Shetakari Mahavidyalaya.







Interviewer: ok, ok. It seems you have taken 6 years to complete your
Engineering.




Candidate: Actually I tried my best to finish it in 4 years. But you
Know, these cricket matches and football world cup, and tennis
Tournaments. It is difficult to concentrate. So I flunked in 2nd and
3rd year. So in all I took 4 + 2 = 7 years.




Interviewer: But 4+2 is 6.




Candidate: Oh, is it? You know I always had KT in maths. But I will try
To keep this in mind. 4+2 is 6, good, thanks. These cricket matches
Really affect exams a lot. I think they should ban it.




Interviewer: Good to know that you want cricket matches to be banned.




Candidate: No, no... I am talking about Exams!!




Interviewer: Ok, What is your biggest achievement in life?




Candidate: Obviously, completing my Engineering. My mom never thought I
Would complete it. In fact, when I flunked in 3rd year, she was looking for a job
For me in BEST (Bus corporation in Maharashtra) through some relative.




Interviewer: Do you have any plans of higher study?




Candidate: he he he.. Are you kidding? Completing 'lower' education
Itself was so much of pain!!




Interviewer: Let's talk about technical stuff. On which platforms have
You worked?




Candidate: Well, I work at SEEPZ, so you can say Andheri is my current
Platform. Earlier I was at Vashi center. So Vashi was my platform then. As you can
See I have experience of different platforms! (Vashi and Andheri are the
Places in Mumbai)




Interviewer: And which languages have you used?




Candidate: Marathi, Hindi, English. By the way, I can keep quiet in
German, French, Russian and many other languages.




Interviewer: Why VC is better than VB?




Candidate: It is a common sense - C comes after B. So VC is a higher
Version than VB. I heard very soon they are coming up with a new
Language VD!




Interviewer: Do you know anything about Assembly Language?




Candidate: Well, I have not heard of it. But I guess, this is the
Language our ministers and MPs use in assembly.




Interviewer: What is your general project experience?




Candidate: My general experience about projects is - most of the times
They are in pipeline!




Interviewer: Can you tell me about your current job?




Candidate: Sure, Currently I am working for Bata InfoTech Ltd. Since
Joining BIL, I am on Bench. Before joining BIL, I used to think that
Bench was another software like Windows.




Interviewer: Do you have any project management experience?




Candidate: No, but I guess it shouldn't be difficult. I know Word and
Excel. I can talk a lot. I know how to dial for International phone call
And use speaker facility. And very important - I know few words like -
'Showstoppers ' , 'hotfixes',
'SEI-CMM','quality','versioncontrol','deadlines' , 'Customer
Satisfaction' etc. Also I can blame others for my mistakes!




Interviewer: What are your expectations from our company?







Candidate: Not much.



1. I should at least get 40,000 in hand.



2. I would like to work on a live EJB project. But it should not have
Deadlines. I personally feel that pressure affects natural talent.



3. I believe in flexi-timings.



4. Dress code is against basic freedom, so I
Would like to wear t-shirt and jeans.



5. We must have sat-sun off. I will suggest Wednesday off also, so as to
Avoid breakdown due to overwork.



6. I would like to go abroad 3 times a year on short term
preferably 2-4 months) assignments. Personally I prefer US, Australia and
Europe. But considering the fact that there is a world cup in West Indies in
2007, I don't mind going there in that period. As you can see I am modest and
don't have many expectations. So can I assume my selection?







Interviewer: he he he ha ha ha. Thanks for your interest in our
organization. In fact I was never entertained so much before. Welcome to
INFOSYS .. :-))




No intention to offend anybody..

Getting Started with IIS7

Introduction


Visual Studio comes with an inbuilt web server. No doubt the inbuilt web server comes handy during development. However, finally your web site needs to sit inside Internet Information Services (IIS). If you are an ASP.NET developers you are probably familiar with IIS6. The new generations of Windows namely Windows Vista and Windows Server 2008 come with IIS7. The new version of IIS is different than earlier versions in many areas. In fact the entire architecture of IIS has been revamped for the good. In this article I am going to give you a jump start on IIS7. I will confine myself to the features that are most commonly needed by ASP.NET developers. If you wish to deploy your websites on IIS7 then this article should give you a good start.

New Architecture of IIS7
As I mentioned earlier, IIS7 has been revamped since its previous versions. The most significant areas of improvement (for developers) are modular architecture, IIS user interface, request processing pipeline and ASP.NET integration. Let's see each of these improvements in brief.

Modular Architecture
The new architecture introduced in IIS7 is modular in nature. Individual features of IIS are organized in various functionally related modules. This allows administrators to install only the required features resulting in decreased footprint of the web server. Additionally, they can install patches and upgrades related to installed components only. These modules can be turned on or off using "Windows Features" dialog of Windows Vista.



Request Processing Pipeline
In the early versions of IIS there were essentially two request pipelines. One used by IIS and one used by ASP.NET. The request authentication, execution of ISAPI extensions and filters etc. used to happen at IIS level first and then the request used to reach ASP.NET. Then ASP.NET used to run its own authentication and HTTP handlers and modules. As you might have guessed there was some duplication of work and responsibilities. The IIS7 on the other hand provides an integrated requested processing pipeline that combines IIS and ASP.NET processing into a single step.

ASP.NET integration
With ASP.NET 2.0 Microsoft added the ASP.NET tab to the IIS application property dialog. Taking this integration further IIS7 adds a lot more integration that makes administrator's job easy.

IIS User Interface
IIS user interface has been greatly redesigned for better organization.


Now that you have some idea of what IIS7 has to offer, let's see how some common tasks can be performed. I am going to use Windows Vista for all the discussion below. The concepts remain the same for IIS under Windows Server 2008 also.

IIS Manager
The IIS manager can be accessed from Control Panel > System and Maintenance > Administrative Tools > Internet Information Services Manager.

The IIS manager user interface consists of three panes. The left hand side pane is Connections, the middle pane is Workspace and the right hand side pane is Actions.

The Connections pane lists application pools and websites. The workspace pane consists of two tabs at the bottom namely Features View and Content View. The Features View allows you to work with the settings of the selected item from Connections pane whereas the Content View displays all the child nodes (content) of the selected item. The following Figure shows these two views for the "Default Web Site"





Working with Application Pools
Application pool is a group of IIS applications that are isolated from other application pools. Each application pool runs in its own worker process. Any problem with that process affects the applications residing in it and not the rest of the applications. You can configure application pools individually.

In order to create a new application pool, select "Application Pools" under Connections pane. Then click on "Add application pool" from Actions pane. This will open a dialog as shown below:



Specify a name for the new pool to be created. Select .NET framework version that all the applications from the pool will use. Also select pipeline mode. There are two pipeline modes viz. integrated and classic. The integrated mode uses the integrated request processing model whereas the classic mode uses the older request processing model. Click OK to create the application pool.

Your new application pool will now be displayed in the Workspace pane. To configure the application pool click on the "Advanced Settings" option under Actions pane. The following figure shows many of the configurable properties of an application pool.



Creating Websites
One good feature of IIS7 under Vista is that it allows you to create multiple web sites. This feature was missing on Windows XP or Windows 2000 Professional. Server editions of Windows obviously don't have such limitation. To create a new web site, select Web Sites node under Connections pane and then click on "Add Web Site" under Actions pane. This opens a dialog as shown below:



Here, you can specify properties of the new web site including its application pool and physical location.

Creating IIS Applications
Creating an IIS application or a Virtual Directory is quick and simple. Just right click on the web site and choose either "Add Application" or "Add Virtual Directory" to open respective dialogs .





An existing Virtual directory can be marked as an IIS application by right clicking on it and selecting "Convert to Application".

Once you create a website or an IIS application, you can then set several ASP.NET related configuration properties via Workspace pane.

Gridview Row DataBound and Row Command

PageIndexChanged
Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation.
PageIndexChanging
Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation.
PreRender
Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.)
RowCancelingEdit
Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode.
RowCommand
Occurs when a button is clicked in a GridView control.
RowCreated
Occurs when a row is created in a GridView control.
RowDataBound
Occurs when a data row is bound to data in a GridView control.
RowDeleted
Occurs when a row's Delete button is clicked, but after the GridView control deletes the row.
RowDeleting
Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
RowEditing
Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode.
RowUpdated
Occurs when a row's Update button is clicked, but after the GridView control updates the row.
RowUpdating
Occurs when a row's Update button is clicked, but before the GridView control updates the row.
SelectedIndexChanged
Occurs when a row's Select button is clicked, but after the GridView control handles the select operation.
SelectedIndexChanging
Occurs when a row's Select button is clicked, but before the GridView control handles the select operation.
Sorted
Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation.
Sorting
Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.
Unload
Occurs when the server control is unloaded from memory. (Inherited from Control.)



protected void gvWebSite_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {
LinkButton btnButt = (LinkButton)e.Row.Cells[1].FindControl("btnDelete");
btnButt.CommandArgument = e.Row.RowIndex.ToString();
}
if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton l = (LinkButton)e.Row.FindControl("btnDelete"); l.Attributes.Add("onclick", "javascript:return " + "confirm('Are you sure you want to delete " + DataBinder.Eval(e.Row.DataItem, "websitename") + " and all its contents?')");
} }



protected void gvWebSite_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("Delete")) { int rowNumber = Convert.ToInt32(e.CommandArgument); string SiteName = ((Label)gvWebSite.Rows[rowNumber].FindControl("lblSiteName")).Text; string path = ((Label)gvWebSite.Rows[rowNumber].FindControl("lblAdsPath")).Text;
CurrentContext context = (CurrentContext)Session["CurrentContext"]; CurrentUser cuser = (CurrentUser)Session["CurrentUser"]; string PreferredDC = ConfigurationManager.AppSettings["PreferredDC"].ToString(); Microsoft.Provisioning.MPSWSProxy.WindowsBasedHosting.WindowsBasedHosting wbh = new Microsoft.Provisioning.MPSWSProxy.WindowsBasedHosting.WindowsBasedHosting(); wbh.Credentials = new NetworkCredential(cuser.SamAccountName, cuser.Password, cuser.Domain);
string mpsResponse = wbh.DeleteCustomerWebSite(Utilities.RemoveDCFromLdap(PreferredDC, path), SiteName, string.Empty, PreferredDC, string.Empty, true); Retrieve(); }
}



In Design Mode::

'> '>

Configuration Files

Web.Config File:

It is an optional XML File which stores configuration details for a specific asp.net web application.
Note: When you modify the settings in the Web.Config file, you do not need to restart the Web service for the modifications to take effect.. By default, the Web.Config file applies to all the pages in the current directory and its subdirectories.
Extra: You can use the tag to lock configuration settings in the Web.Config file so that they cannot be overridden by a Web.Config file located below it. You can use the allowOverride attribute to lock configuration settings. This attribute is especially valuable if you are hosting untrusted applications on your server.


Machine.Config File:


The Machine.Config file, which specifies the settings that are global to a particular machine. This file is located at the following path:
\WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config
As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
You can override settings in the Machine.Config file for all the applications in a particular Web site by placing a Web.Config file in the root directory of the Web site as follows:
\InetPub\wwwroot\Web.Config




Web.Config Vs Machine.Config

Machine.Config:
i) This is automatically installed when you install Visual Studio. Net.
ii) This is also called machine level configuration file.
iii)Only one machine.config file exists on a server.
iv) This file is at the highest level in the configuration hierarchy.

Web.Config:
i) This is automatically created when you create an ASP.Net web application project.
ii) This is also called application level configuration file.
iii)This file inherits setting from the machine.config