Monthly Archives: June 2010

Static Classes

Static classes are loaded automatically by the .NET when the program or namespace containing the class is loaded.
The main features of a static class are:
# They only contain static members.
# They cannot be instantiated.
# They are sealed.
# They cannot contain Instance Constructors

If you include instance member in static class then you will get compile time error.

static class CompanyInfo
{
public static string GetCompanyName() { return “CompanyName”; }
public static string GetCompanyAddress() { return “CompanyAddress”; }
}

Advertisements

Leave a comment

Filed under C#

ASP.Net Page Life Cycle

Leave a comment

Filed under .Net

ASP.NET Application Life Cycle for IIS

Application Life Cycle


Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain.

Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.

Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.

Step 6:-Now following events are executed by HttpAlication like:
–ValidateRequest() for validating information sent by the browser to determine whether it contain malicious markup or for Cross-site scricpting attacks.
–URL mapping if it is configured in UrlMapping section in web.config.
–BeginRequest() event
–AuthenticateRequest() event
–AuthorizeRequest() event
….
….
….
–EndRequest() event

REFERENCES

http://www.codeproject.com/Articles/121096/Web-Server-and-ASP-NET-Application-Life-Cycle-in-D

http://www.codeproject.com/Articles/73728/ASP-NET-Application-and-Page-Life-Cycle

Leave a comment

Filed under .Net

ref vs out

ref
it is necessary to initialize them before passing to the function(compile time error, if not done).

 protected void Page_Load(object sender, EventArgs e)
{           
            int a = 20;
            Response.Write(a + “<BR>”);
            DoSome(ref a);      //we need to pass value with ref keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(ref int aa)
{
            aa = 30;
}

out
no assignment is required, but you must assign a value in which function this is passed.
If the other side doesn’t need any information about this object except where to store the object, you probably should just use ‘Out’.

protected void Page_Load(object sender, EventArgs e)
 {           
            int a = 20;           
            DoSome(out a);      //we need to pass value with out keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(out int aa)
{
            aa = 30;
}

2 Comments

Filed under .Net, C#

What is GAC? Where GAC located on machine?

GAC is known as Global Assembly Cache where the shared assembiles are being kept. GAC can be found on a system at \\Assembly ie. C:\Windows\Assembly.
GAC is a Folder that contains DLL that have strong name. As DLL differ by strong names+public key and since strong name can not be same hence we can put two DLL with same name into GAC. For example SameNameApp.dll and SameNameApp.dll can co-exist in GAC if the first one have version 1.0.0.0 and the second have 1.1.0.0.

DLL =Assembly_name + Version + Culture_Info + public_key

Leave a comment

Filed under .Net

Exception Handling in WCF

**********************************

Server Side Exception Handling

**********************************

Exception Handling in WCF

We basically handle two types of exception in WCF service and covert them to the FaultExcetion<SomeErrorDto> to make client familiar with the exceptions. Let me explain the complete scenario with a sample application XYZ:

Catch (XYZException ex)

{

       //Convert Application specific (XYZException) exceptions to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleXYZToFaultException(ex);

}

Catch(Exception ex)

{

      //Convert Generic Exception to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleGenericToFaultException(ex);

}

 

Our XYZException Class

public class XYZException : System.Exception

{

    private int _errorCode;

     public int ErrorCode

    {

        get { return _errorCode; }

        set { _errorCode = value; }

    }

 

    public XYZException(string message, Exception ex)  : base(message, ex)

    {

    }

    public XYZException(string message, int code, Exception ex)  : base(message, ex)

    {

        _errorCode = code;

    }  

}

Our ExceptionHelper class:

using System;

using System.Data.SqlClient;

using System.ServiceModel;

 

public class ExceptionHelper

{

    //Used in the BL(Business Logic) layer

    public static XYZException HandleGenericToXYZException(Exception genExcep)

    {

        //Logging the Generic Execption here before converting it to Application specific

       // (XYZException) exception.

        if ((genExcep != null))

        {

            return new XYZException(genExcep . Message, genExcep);

        }

        else

        {

            return null;

        }

    }

   

    //Convert Application specific Exception to FaultException<XYZErrorDto>

    public static FaultException<XYZErrorDTO> HandleXYZToFaultException(XYZException xyzExcep)

    {

        return HandleGenericToFaultException(xyzExcep);

    } 

    //Used in WCF service.

    public static FaultException<XYZErrorDTO> HandleGenericToFaultException(Exception genExcep)

    {

        XYZErrorDTO objXYZErrDTO = new XYZErrorDTO();

        if ((genExcep != null))

        {

            objXYZErrDTO = new XYZErrorDTO(genExcep.Message);

        }

        else

        {

            objXYZErrDTO = new XYZErrorDTO(“An unexpected error has occurred in the system”);

        } 

        //Logging the Generic Execption here before converting it to FaultException.

        return new FaultException<XYZErrorDTO>(objXYZErrDTO);

    }

}

*********************

UI Exception Handling

**********************

Now it is clear the UI will only receive Exceptions of type FaultException only from server, moreover we need to handle the Generic exception raised at the UI also. So if the UI code logic involve server resource usage the we have to catch both the exceptions else there will be only catching of general exception as shown below:

 Try

{

     //Logic involve usage of server resources 

}

Catch (FaultException ex)

{

      UIExceptionHelper.HandleFaultException(ex);        

}

Catch (Exception ex)

{

      UIExceptionHelper.HandleGenericException(ex);    

}

Our UIExceptionHelper class:

using System.ServiceModel;

using System.Diagnostics.EventLog;

 public class UIExceptionHelper

{

     public static void HandleFaultException(FaultException<XYZErrorDTO> faultExcep)

    {

        try

        {

            //Logging FaultException before displaying on Screen.          

            LogManager.LogError(faultExcep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            WebMsgBox.Show(Decl.WEB_MSG, faultExcep.Detail.Message);

        }

        catch (Exception ex)

        {

        }

    }

     public static void HandleGenericException(Exception excep)

    {

        try

        {

            //Logging the Generic message before redirecting to custom error page.

            string strMsg = excep.Message.Replace(Constants.vbCrLf, ” “);

            string strTrace = excep.StackTrace.Replace(Constants.vbCrLf, ” “);

            LogManager.LogError(excep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            //Redirecting to Custom Error Page for Generic Exceptions.

            Response.Redirect(Decl.ERROR_PAGE + “?Error=” + strMsg + “&Trace=” + strTrace);

        }

        catch (Exception ex)

        {

        }

    }

}

Refrences

http://msdn.microsoft.com/en-US/library/seyhszts(v=VS.80).aspx

http://dhananjaykumar.net/2010/05/23/fault-contract-in-wcf-with-learning-video/

Leave a comment

Filed under C#, WCF

Asynchronous Programming

Asynchronous Programming

When you create delegate, the compiler generates three methods Invoke, BeginInvoke, EndInvoke. Invoke is used to execute delegate synchronously, and rest two methods allow you to have asynchronous programming.

BeginInvoke takes the same parameters as delegate itself, plus another two parameters- an AsyncCallback which is called after the BeginInvoke execution, and an object parameter which is made available through the AsyncState property of the IAsyncResult parameter which is passed to the AsyncCallback.

The call to BeginInvoke returns an IAsyncResult which can be used to call EndInvoke, and you don’t have to pass a callback delegate to be executed if you don’t want to – just pass null as the last but one parameter to BeginInvoke.

private delegate int DoubleMeDelegate(int x);

protected void Page_Load(object sender, EventArgs e)

{

   for (int i = 1; i < 5; i++)

  {

     DoubleMeDelegate d = new DoubleMeDelegate(DoubleMe);

     d.BeginInvoke(i, new System.AsyncCallback(InvokeMessage), d);

   }

Thread.Sleep(1900);

}

private void InvokeMessage(IAsyncResult ar)

{

   DoubleMeDelegate dEnd = (DoubleMeDelegate)ar.AsyncState;

   int result = dEnd.EndInvoke(ar);

   Response.Write(result + “<br/>”);

}

private int DoubleMe(int single)

{

   Thread.Sleep(100);

   return (2 * single);

}

Leave a comment

Filed under C#