Saturday, October 16, 2010

Process Vs Threads

Both threads and processes are methods of parallelizing an application. However, processes are independent execution units that contain their own state information, use their own address spaces, and only interact with each other via interprocess communication mechanisms (generally managed by the operating system).Thread is a design construct that doesn't affect the architecture of an application. A single process can have multiple threads; all threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables.
T1 and T2 are threads inside one process.Process is unit of allocation of resources but the threads are unit of execution.Inter process communication is always expensive. it needs context switch, whereas
inter thread communication is cheap, it can use process memory and may not need to context switch. The process are secure as one process is dead, other process wont get affected, but if one thread get corrupt and die ,other threads and even corresponding process will get die.

Sunday, October 10, 2010

.NET Fundamentals 12 (ASP page Error handler)

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).

Page_Error:
The Page_Error event handler provides a way to trap errors that occur at the page level. You can simply display error information or you can log the event or perform some other action.
void Page_Load(object sender, System.EventArgs e)
{
    throw(new Exception());
}


public void Page_Error(object sender,EventArgs e)
{
    Exception objErr = Server.GetLastError().GetBaseException();
    Server.ClearError();
}
Server.ClearError prevents the error from continuing to the Application_Error event handler.

Application_Error:
The Application_Error event handler is specified in the Global.asax file of application. It means other pages in same virtual directory can also use the same error handler.
void Page_Load(object sender, System.EventArgs e)
{
    throw(new Exception());
}
//In Global.asax
 protected void Application_Error(object sender, EventArgs e)
{
    Exception objErr = Server.GetLastError().GetBaseException();
    Server.ClearError();  
}

Note:
1) In both of the above methods AutoEventWireup in aspx page should be true. It is ASP attribute which wires up certain event handlers (like Page_Load, Page_Error etc) to the page.If this attribute is set to false then none of these events will fire. These event handler have fixed name which can't be changed.
2) The error details can be found in Server.GetLastError().GetBaseException().

Web.Config method:
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 section of the Web.config file. In the 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.
Change the settings in customeErrors tag in web.config file.

mode = On
DefaultRedirect = Page where you want to redirect on error.
Inside customeErrors tag you have en error tag in which you can specify different page for different errors.The error tag looks like this:
error statusCode="404" redirect="filenotfound.htm" 
Status code is error code and the redirect will be the page where w want to redirect.


In customErrors we can select mode attribute. It hase 3 values to set:
-> 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.



Here is one more attribute which needs to be set to achive desired purpose, that is redirecmode.
It is an optional property. It has 2 values which can be set depending upon requirement.

ResponseRedirect: Specifies that the URL to direct the browser to must be different from the original Web request URL.In this case the server will completely redirect your application page to error page. All the content of application page will not be available anymore.
ResponseRewrite: Specifies that the URL to direct the browser to must be the original Web request URL.In simple words in this case the url which you see in webbrowser will be the application url only, but the http content will be of error page.Here server rewrite the html content of your application page.

The different among 2 can be seen on refresh of page. In 1st case error page will get refresh. but in 2nd Case your application will again try to reload and if again some error occurs then we will get error page again.



ApplicationInstanceError method:
Wen can use this method in following way:
HttpContext.Current.ApplicationInstance.Error += new EventHandler(ApplicationInstance_Error).
by this we can attach error handler in our application. it is equivalent to response.rewrite method in customeError tag mentioned above. If we have both Application_Error(In Global.asax) as well as ApplicationInstanceError handler then Application_Error will be called 1st and then the other one.
The benefit we get by this is, Response.ReWrite doesn't work for application in different virtual directory, but by this method we get all the benefit of response.rewrite and whoever application uses this Dll having ApplicationInstanceError handler will be able to invoke it.

Sunday, October 3, 2010

.Net Fundamentals 11(Generics)

Why Generics-
Type safety ,better performance,Source code protection and Cleaner code
(Type safty and performance are discussed later)
Source code protection: Developers don't need any source code if they are using generic algorithms.
Cleaner Code: as compiler take care of type safety so we need not to type caste the things again and again. so we get a good readable code.

Better performance - Only in case of value type, as it avoid boxing and unboxing.

Type Safety-
static void Main(string[] args)
{
    ArrayList list = new ArrayList();          
    populateList(list);
    int temp;
    for (int i = 0; i < list.Count; i++)
    {
    temp = (int)list[i];
    Console.WriteLine(temp);
    }
}
private static void populateList(ArrayList list)
{
    list.Add(1);
    list.Add(2);
    list.Add("hello"); //No error from compiler
}It will cause runtime error -> Specified cast is not valid

But in case of generics:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add("hello"); //Compiler shows error

So at compile time itself we get error in case of type mismatch.

Boxing/UnBoxing-
Boxing is the act of converting a value type to a reference type. If we look at line #2 of the first code sample above, we’re putting an Int32 (a value type) into an ArrayList which stores everything as System.Object (a reference type).
Boxing causes memory allocation on managed heap, which causes more frequent garbage collections, which in turn hurt an application performance.
Unboxing is the act of converting a reference type to a value type (e.g., if we were taking an item out of the ArrayList and having to cast: int num = (int)list[0];).

- Generic Type and inheritance
        IList<string> mylist = new List<string>();
        IList<int> myintlist = new List<int>();

Both of these types will be derived from whatever type the generic type was derived from. If the generic List<T> is derived from object, it means list<string> and List<int> are also derived from object.
It does not mean that mylist.GetType()==myintlist.GetType() will return you true.

Inheritance in Generics -
There are different kind of inheritance possible -
Points to remember -
In case of (ii) and (iv) all overridden methods will have to define the types in the generic implementation. In other words we can not have any generic class definition which has overridden method and the return type or input parameters are T.
Here is the example -
class A<T> : C
{
    T temp;
    public A(T t)    { temp = t; }
    public override string  GetT(string t) { return "";}
    public void SetT(T t)    { temp = t;}
}
class C
{
    public C() { }
    public virtual String GetT(string a ) { return "C";}
}
In above case we can not have method GetT taking parameter as T or returning type T.

Generic Interface -
Using generic we can define interface that defines methods with generic parameters. Here is the example -
 Here is nonGeneric IComparable interface
public class A : IComparable
{
    public int myInt = 0;       
    public int CompareTo(object obj)
    {
        A a = obj as A;
        return this.myInt.CompareTo(a.myInt);
    }       
}
Here is Generic Comparable interface.
public class B : IComparable<B>
{
    public int bint = 0;
    public int CompareTo(B other)
    {
        return this.bint.CompareTo(other.bint);
    }      
}
If we compare above 2 examples then we see in 2nd case, we dont need any type cast.

Constraints -
While compiling generic code, c# compiler make sure that the code will work for anytype exist today, or introduced later. For example -
    private void Min<T>(T o1)
        {
            Console.WriteLine(o1.ToString());
        }
The above code compiles successfully but
    private void Min<T>(T o1)
        {
            Console.WriteLine(o1.CompareTo(o1));
        }
Won't compile. As every type will have ToString method available to them, but not every type will have compareTo Method available. Thus CLR provides "constraints" to solve this limitation. We can always define this method like this-
    private void Min<T>(T o1) where T: IComparable<T>
        {
            Console.WriteLine(o1.CompareTo(o1));
        }
It not possible to put a constraint on overridden method, when there is not constraint available on parent method. Here is the example-
    class A<T>
    {
        public A() { }
        public virtual void Min<T>(T o1)
        {
            Console.WriteLine(o1.ToString());
        }
    }
    class B<T> : A<T>
    {
        public B() { }
        public override void Min<T>(T o1) where T:ICloneable
        {
            Console.WriteLine(o1.ToString());
        }
    }
The above code will give error, because Min MEthod doesn't have any constraint in base class, but we are trying to put a constraint in derived class.
Moreover we can not put constraint using object class, which means following code won't compile-
public override void Min<T>(T o1) where T:object
        {
            Console.WriteLine(o1.ToString());
        }
 But its always possible to put constraints of value type or reference type using class/struct as constraints.
Here are some description about different kind of constraints allowed in c# -
Constraint : Description
where T    : struct With a struct constraint, type T must be a value type.
where T    : class The class constraint indicates that type T must be a reference type.
where T    : IMyInterface where T : IMyInterface specifies that type T is required to implement interface IMyInterface.
where T    : MyClass where T : MyClass specifies that type T is required to derive from base class MyClass.
where T    : new() where T : new() is a constructor constraint and specifies that type T must have a default constructor.
where T1   : T2 With constraints it is also possible to specify that type T1 derives from a generic type T2. This constraint is known as naked type constraint.

Code Explosion-
When we use a generic type and specify the type arguments, CLR defines new type object for every type we mention. For example -
        IList<string> mylist = new List<string>();
        IList<int> myintlist = new List<int>();
 For above 2 line, CLR will create 2 different types, list of string and list of int. It means for every method/type combincation CLR will generate native code, which is called as code explosion. This might hurt the performance. In order to overcome this issue, CLR has its own optimization -
Optimization 1 - If one method is called for specific argument then CLR will compile it once and will serve all the instances of this method call from same code generated(in a appdomain).
Optimization 2- CLR compiles the code for reference type only once, as all reference types are just pointers, so List of string and list of Datetime will share the same compiled code.(This is not applicable for Value types)

Setting a Default Value-
If we want to set a default value of any generic type then we need to use "default" keyword, We can not directly assign null, as value type don't have null.
Which means following code will give error -
private static setDefault<T>(T o1)
{
      T temp = null; //error
}
To fix the above code use default-
private static setDefault<T>(T o1)
{
      T temp = default(T);

}
temp will be null if its ref type and will be all bits zero if its a value type.

Comparison of generic type-
private static CompareResult<T>(T o1, T o2)
{
      if(o1 == o2) // error
}
Above code will give error as not every value type has == operator.

Open and closed types-
Type with the generic type parameters(no definition of T) is called open type and CLR does not allow an instance of any open type. If actual data type are passed for all type arguments, it is called as closed type. 
Ex:
Object o;
Open type :
Type t = typeof(Dictionary<,>);
o = createinstance(t); //error

Closed Type:
//DictionaryString is defined like this Dictionary an open type.
//here we have also defined 2nd parameter so it has became a closed type
Type t = typeof(DictionaryString<GUID>);
o = createInstance(t); //No Error


Static Member-

If a static constructor is defined on generic type, then it will be execute once for every close type. 
For example -
There is class which contains static filed x -
public class StaticDemo < T >
{
    public static int x;
}
Because of using the class StaticDemo <T> both with a string type and an int type, two sets of static fields exist:
StaticDemo<string>.x = 4;
StaticDemo<int>.x = 5;
Console.WriteLine(StaticDemo<string>.x); // writes 4

Limitations-
Methamatical operators like +, -, * and /, can not be applied on any generic type, because we dont know the type beforehand.  Which means its impossible to write methematical algo that works on arbitrary data type.

Saturday, October 2, 2010

.Net Fundamentals 10(Marshalling/UnMarshalling)

What is Marshalling/UnMarshalling and type of marshalling in .net?
Marshalling is as process of making an object avail across network or application domain. Marshaling is the act of taking data from the environment you are in and exporting it to another environment.
UnMarshalling creates an object from the marshaled data.
There are 2 ways of Marshalling:
Marshal by Value: In this, the object is serialized into the channel, and a copy of the object is created on the other side of the network. The object to marshal is stored into a stream, and the stream is used to build a copy of the object on the other side with the unmarshalling sequence.Value types are marshalled to unmanaged code on the stack.
Marshal by Reference: Here it creates a proxy on the client that is used to communicate with the remote object. The marshaling sequence of a remote object creates an ObjRef instance that itself can be serialized across the network. Objects that are derived from “MarshalByRefObject” are always marshaled by reference. To marshal a remote object the static method RemotingServices.Marshal () is used. Reference types are passed by address. This means a pointer is passed on the stack, and the pointer contains the address of the marshaled data on the heap. When parameters are passed by reference, a pointer to the parameters on the managed heap is passed to the unmanaged code. Since the unmanaged code receives a pointer, it is possible for the method to modify the data held on the managed heap.
Blittable : A type is considered blittable if it has a common representation in managed and unmanaged code memory. Non-blittable types require custom marshaling to convert between the unmanaged and managed representations.

[InAttribute] and [OutAttribute]
These are called as directional attributes because the control marshalling direction.
[InAttribute] tells the CLR to marshal data from the caller to callee at the begining of the call, while [OutAttribute] tells the CLR to marshal data from the caller to callee upon return. Caller and callee can be either unmanaged or managed code.(Ex. In a P/Invoke call managed code calls unmanaged code, but in reverse P/Invoke unmanaged code calls managed code through function pointer.)

Why can't I serialize .NET Framework classes like exceptions and fonts?
The XmlSerializer is primarily designed with two goals in mind: XML data binding to XSD compliant data structures and operation without any special code access privileges. These two goals work against the XmlSerializer as a general-purpose object persistence solution for some kinds of objects.
General purpose serialization may require accessing private fields, by-passing the framework's standard object construction process, and so on, which in turn requires special privileges. The SoapFormatter from the System.Runtime.Serialization.Formatters.Soap namespace provides an alternative that is not subject to these restrictions, but requires full trust to operate. It also produces an XML format, a generation of which is customizable using the attributes in the System.Runtime.Remoting.Metadata namespace. 

How do I serialize collections of objects?
The XmlSerializer throws an exception when the collection contains types that were not declared to the constructor of the XmlSerializer. You can:
->Declare the types to the serializer by passing in a Type[] with the types to expect within the collection.
      OR
->Implement a strongly-typed collection derived from System.Collections.CollectionBase with an indexer matching the Add() method.

Why can't I serialize hashtables?
The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

Why do exceptions thrown by the XmlSerializer not contain any details about the error?
They do contain all the information, but it's stored in the InnerException property of the exception thrown, which is usually an InvalidOperationException. In general, one should always call ToString() on caught exceptions to get the full details of the exception.

Generic delegates:
As we do event-based programming or implement publish-subscribe pattern, we use the delegate feature from .NET heavily. The code below shows how we can use delegate:
public delegate void MydDelegate(int oldValue, int newValue);
    class TestClass
    {
        public MydDelegate OnDataChanged = null;
        private int _mydata = 0;
        public int MyData
        {
            get { return _mydata; }
            set { UpdateData(value); }
        }

        private void UpdateData(int updatedData)
        {
            if (OnDataChanged != null)
            {
                OnDataChanged(_data, updatedData);
            }
            _data = updatedData;
        }
    }
We can then create an instance of TestClass ,and hook up the event handler to its public delegate as shown below.
     class Program
    {
        static void Main(string[] args)
        {
            TestClass obj = new TestClass();
            obj.OnDataChanged += OnDataChanged;
            obj.Data = 5;
        }
        static void OnDataChanged(int oldValue, int newValue)
        {
            Console.WriteLine("Data changes from " + oldValue + " to " + newValue);
        }
    }
C# 3.0 or .NET 3.5 has new feature that provides us a set of generic delegates with the name "Action" or "Func", the difference between them is Action does not have return type (void), while Func has return type (refer to MSDN documentation). So from example above we can remove following code:
    public delegate void DataChangedDelegate(int oldValue, int newValue);
and replace following code:
        public DataChangedDelegate OnDataChanged = null;
with:
        public Action OnDataChanged = null;
If the delegate returns bool data type for example, then we can use Func function such as:
        public Func OnDataChanged = null;