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.

Friday 25 November 2011

Difference between Var , Dynamic , Object Keyword

Var is type safe ie when we click on the dot(.) it will display the public members of the type which the var is currently holding.But dynamic on the other hand will not be able to display the list.There will be no compilation error on the dynamic keyword even if we use some junk characters as its member methods or properties.Its just like the old style programming where there is no type safety.At run time the method or property may or may not be there. 
Internally how dynamic is handled is just a reflection code.It checks for the member through reflection and it invokes the member if exists.Else throws exception.If you want to see the reflected code of dynamic keyword just use the reflector

var is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:
var s = "abc";
Console.WriteLine(s.Length);
and
string s = "abc";
Console.WriteLine(s.Length);
All that happened was that the compiler figured out that s must be a string (from the initializer). In both cases, it knows (in the IL) that s.Length means the (instance) string.Length property.
dynamic is a very different beast; it is most similar to object, but with dynamic dispatch:
dynamic s = "abc";
Console.WriteLine(s.Length);
Here, s is typed as dynamic. It doesn't know about string.Length, because it doesn't knowanything about s at compile time. For example, the following would compile (but not run) too:
dynamic s = "abc";
Console.WriteLine(s.FlibbleBananaSnowball);
At runtime (only), it would check for the FlibbleBananaSnowball property - fail to find it, and explode in a shower of sparks.
With dynamic, properties / methods / operators / etc are resolved at runtime, based on the actual object. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, like javascript.

Saturday 19 November 2011

Understanding the Page Life Cycle can be very important as you begin to build Pages with MasterPages and UserControls.
Does the Init event fire first for the Page, the MasterPage or the UserControl? 
What about the Load event?
If you make an incorrect assumption about the sequence that these events fire, then you may end up with a page that simply doesn't behave the way you had anticipated.
By running a simple test, we can see exactly when each event fires.  Our test setup is composed of a Page, MasterPage, UserControl, Nested UserControl and Button control as follows:
  • The Page is tied to the MasterPage
  • The UserControl is on the Page
  • The Nested UserControl is on the UserControl
  • The Button is on the Nested UserControl.
  • Clicking the Button calls the Page.DataBind method
Each event on these controls has been set to call Debug.WriteLine as each event is raised.  In addition to the events that get raised for regular pages, I've also set up an HttpModule and wired up all of those events as well. The results in the Debug output window of running this page and Clicking the Button are as follows:
BeginRequest - HttpModule
AuthenticateRequest - HttpModule
PostAuthenticateRequest - HttpModule
PostAuthorizeRequest - HttpModule
ResolveRequestCache - HttpModule
PostResolveRequestCache - HttpModule
PostMapRequestHandler - HttpModule
AcquireRequestState - HttpModule
PostAcquireRequestState - HttpModule
PreRequestHandlerExecute - HttpModule
PreInit - Page
Init - ChildUserControl
Init - UserControl
Init - MasterPage
Init - Page
InitComplete - Page
LoadPageStateFromPersistenceMedium - Page
ProcessPostData (first try) - Page
PreLoad - Page
Load - Page
Load - MasterPage
Load - UserControl
Load - ChildUserControl
ProcessPostData (second try) - Page
RaiseChangedEvents - Page
RaisePostBackEvent - Page
Click - Button - ChildUserControl
    DataBinding - Page
    DataBinding - MasterPage
    DataBinding - UserControl
    DataBinding - ChildUserControl
LoadComplete - Page
PreRender - Page
PreRender - MasterPage
PreRender - UserControl
PreRender - ChildUserControl
PreRenderComplete - Page
SaveViewState - Page
SavePageStateToPersistenceMedium - Page
SaveStateComplete - Page
Unload - ChildUserControl
Unload - UserControl
Unload - MasterPage
Unload - Page
PostRequestHandlerExecute - HttpModule
ReleaseRequestState - HttpModule
PostReleaseRequestState - HttpModule
UpdateRequestCache - HttpModule
PostUpdateRequestCache - HttpModule
EndRequest - HttpModule
PreSendRequestHeaders - HttpModule
PreSendRequestContent - HttpModule 

Monday 7 November 2011

Message Exchange Patterns (MEP) in WCF

Message Exchange Patterns (MEP) in WCF :

MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service. For instance, if a consumer sends a message, it needs to know whether it should expect a message back or whether simply sending the request is enough.
Further, can the consumer expect unsolicited messages back from the service?
WCF supports the following three MEPs, each of which is covered in more detail in this section:
  • Request/Response
  • OneWay
  • Duplex

Request/Response :

This is by far the most common MEP and very little has to be done to set it up because the default value for the Is One Way property of Operation Contract Attribute is false.
Thus, as long as you don’t have IsOneWay set to true, and you are not in a Duplex channel setting, you are using Request/Response.
Note that it doesn’t even necessarily mean that you have a non-void return type. That is to say, even with a void return type, if you are using Request/Response, then a response message is still going back to the consumer when the operation is called; it just would have an empty SOAP body.
Also, this two-way communication channel enables the service
to issue faults (if anything goes wrong), return transaction contexts, or both.

In the following code sample, both operations are configured to use the Request/Response MEP:


[ServiceContract()]
public interface ILogisticsService
{
[OperationContract()]
WorkOrderAcknowledgement SubmitWorkOrder(WorkOrder workOrder);
[OperationContract()]
void CancelWorkOrder(int workOrderNumber);
}


Finally, all WCF bindings except the MSMQ-based bindings support the Request/Response MEP.
OneWay :

Sometimes, you simply want to send a message off to a service and have it trigger some sort of business logic, and you aren’t in fact interested in receiving anything back from the service.
In such cases, you might want to use the OneWay MEP, that is, have the consumer simply send one-way messages into the service endpoint without any responses back from the service.
ThisMEP is declared by setting the Is OneWay property on the OperationContractAttribute to true.

The following shows an example of this:

[ServiceContract()]
public interface ILogisticsService
{
[OperationContract(IsOneWay=true)]
void CancelWorkOrder(int workOrderNumber);
}

However, you must keep the following points in mind when considering whether the OneWay MEP is the right choice for you:

  • It cannot be used in conjunction with the FaultContract attribute because for a service to issue faults, it must have a two-way channel of some form, which is not the case with one-way messaging. Nor can it return transaction contexts.
  • It can be dangerous just to send off a one-way message and not have some assurances that it arrived and was processed. So, with that in mind, if an MSMQ binding is feasible in your environment, you might want to use OneWay messaging only when you can couple it with queued message delivery.
  • Note also that, if you want queued message delivery, the OneWay MEP is your only choice, at least as far as the WCF infrastructure is concerned.
  • Also be aware that it does not conform to the asynchronous, send-and-forget semantics that one might think it does, given the name “one-way.” In other words, given the oneway nature of the channel, one might think that as soon as the consumer sends the message, it is processed asynchronously from that point on and the client is free to do other things.
Duplex :
The Duplex MEP is a two-way message channel whose usage might be applicable in either of these two situations:

  • The consumer sends a message to the service to initiate some longer-running processing and then subsequently requires notification back from the service, confirming that the requested processing has been done.
  • The consumer needs to be able to receive unsolicited messages from the service.
Because there are two Service contracts to consider in a Duplex MEP scenario, namely the Service contract and the Callback contract, this MEP is declared by associating the Callback contract with the Service contract.
This association is done through the CallbackContract property
of the ServiceContractAttribute that is adorning the service that needs to be capable of calling back to a consumer.

For an example of this, consider a simple “Hello World” application, this time where a consumer sends a one-way message to a greeting service, and at some point after that, the service calls back to the consumer and says, “I have processed your greeting request and here it is; I am calling you back with it now.”

The following code shows not only the Service
contract, the Callback contract, and how they are associated but also how the service implementation (that is, the service type) uses the OperationContext to ask for a reference to the Callback contract, thereby enabling the service to call back to the consumer.
Here is the code:


[ServiceContract]
interface IGreetingHandler
{
[OperationContract(IsOneWay = true)]
void GreetingProduced(string greeting);
}

[ServiceContract(CallbackContract =
typeof(IGreetingHandler))]
interface IGreetingService
{
[OperationContract(IsOneWay = true)]
void RequestGreeting(string name);
}

[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]
class GreetingService : IGreetingService
{
public void RequestGreeting(string name)
{
Console.WriteLine("In Service.Greet");
IGreetingHandler callbackHandler =
OperationContext.Current.GetCallbackChannel<IGreetingHandler>();
callbackHandler.GreetingProduced("Hello " + name);
}
}