Friday, December 14, 2012

What is the Sequence of PLC event when the page has Master Page -->Page-->user Control-->Child user Control?


First
_________________________________________________________
  1. PreInit
  2. Init
  3. InitComplete
Second
_________________________________________________________
  1. PreLoad
  2. Load
  3. Controlevents
  4. LoadComplete
Third
 __________________________________________________
  1. Prerender
  2. PrerenderComnplete
  3. SavestateComplete
  4. Render
Fourth
__________________________________________________
 UnLoad

A little bit about  Init:
Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.(MSDN)

And  we can see the sequence of events of a page consisting of “master page àpageàuser controlàchild user controls” as below
---------------------------------------------------------------------------
1.PreInit – Page
     Init :ChildUserContr     
     Init : UserControl     
     Init : MasterPage
2.Init : Page
3.InitComplete :Page
------------------------------------------------------------------------------
LoadPageStateFromPersistenceMedium :Page 
ProcessPostData (1st Try) - Page
-----------------------------------------------------------------------------------------------------------------------------------------------
4.PreLoad – Page  
5.   Load :Page            Load: MasterPage     
       Load : UserControl        
       Load :ChildUserControl
       ProcessPostData  : Page        
       RaiseChangedEvents : Page        
       RaisePostBackEvent :Page

6.  Controlevents      
       DataBinding : Page       
       DataBinding : MasterPage       
       DataBinding :UserControl      
       DataBinding:ChildUserControl
7.LoadComplete : Page
----------------------------------------------------------------------------------------------------------------------
8. PreRender - Page    
     PreRender : MasterPage    
     PreRender : UserControl    
     PreRender : ChildUserControl
9.PreRenderComplete – Page      
---------------------------------------------------------------------------------------------------------------------------------------------------
SaveViewState : Page    
SavePageStateToPersistenceMedium: Page  
----------------------------------------------------------------------------------------------------------------------------------------------------
10.    SaveStateComplete :Page
      Unload - ChildUserControl    
      Unload - UserControl    
      Unload - MasterPage
11.Unload - Page

Polymorphism, Method Hiding and Overriding in C#


Overview
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes AB and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A {}

        class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Foo();  // output --> "A::Foo()"

                B b = new B();
                b.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
The method Foo() can be overridden in classes B and C:
    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
              public void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
There are two problems with this code.
  • The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section.
  • Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }
     }
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }
Conclusion
  • C# is not Java.
  • Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
  • Know what your doing and look out for compiler warnings.

Monday, December 10, 2012

8 WAYS OF CREATING INSTANCE


1. Simple with new keyword
Example1-:
public class Person
{
    public string Name;

}
Person P = new Person();
           P.Name="Deepak";

Example3-: Interface having reference of class
class Program
    {
        
       static void Main(string[] args)
        {
            IHuman P = new Person();
            P.getName();
        }
 

    }

interface IHuman
{
    void getName();
}

public class Person :IHuman
{
  
   public void getName()
   {
       Console.WriteLine("Deepak");
       Console.ReadKey();
   }

}

Example3-: Base Class having reference of derived class.
class Program
    {
        
       static void Main(string[] args)
        {
            DAD D;
            D=new Son1();
            D.getName();
            D = new Son2();
            D.getName();
            Console.ReadKey();
        }
 

    }

 public class DAD
 {
     public virtual void  getName()
     {
         Console.WriteLine("FATHER");
        
     }

 }
public class Son1 :DAD
{
  
   public override void getName()
   {
       Console.WriteLine("SON1");
      
   }

}
public class Son2:DAD
{

    public override void getName()
    {
        Console.WriteLine("SON2");
       
    }

}



2. Activator Class-:
Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited. 


Example1-:
using System;
using System.Reflection;
using System.Text;

public class SomeType
{
    public void DoSomething(int x)
    {
        Console.WriteLine("100 / {0} = {1}", x, 100 / x);
    }
}

public class Example
{
    static void Main()
    {
        // Create an instance of the StringBuilder type using  
        // Activator.CreateInstance.
        Object o = Activator.CreateInstance(typeof(StringBuilder));

        // Append a string into the StringBuilder object and display the  
        // StringBuilder.
        StringBuilder sb = (StringBuilder) o;
        sb.Append("Hello, there.");
        Console.WriteLine(sb);

        // Create an instance of the SomeType class that is defined in this  
        // assembly.
        System.Runtime.Remoting.ObjectHandle oh =
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase,
                                         typeof(SomeType).FullName);

        // Call an instance method defined by the SomeType type using this object.
        SomeType st = (SomeType) oh.Unwrap();

        st.DoSomething(5);
    }
}




Example2-:
    Type T = System.Web.Compilation.BuildManager.GetCompiledType
                         ("//DynamicCompilation//Default2.aspx");
    object obj=  Activator.CreateInstance(T);
    MethodInfo m = T.GetMethod("function");
    object ret=m.Invoke(obj, null);
    Response.Write(ret.ToString());

3. Using assembly class -:Assembly.CreateInstance

Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.
Example-:
 System.Reflection.Assembly ptr =
System.Reflection.Assembly.LoadFrom("ClassLibrary1.dll");
  // get type of class test from just loaded assembly
  Type calcType = ptr.GetType("MyClass2");
    //get the method from above type
     MethodInfo m = calcType.GetMethod("AddNumb");
      //create instance of cass
       object calcInstance = ptr.CreateInstance("MyClass2");
     //invoke the method
    object str=m.Invoke(calcInstance,null);
       MessageBox.Show(str.ToString())

4. Object.MemberwiseClone Method

The MemberwiseClone method creates a shallow copy by creating a new objectand then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
Example-:
    class Program
    {
        static void Main(string[] args)
        {

            Person P = new Person();
            P.Name = "Deepak";
            Person D = P.CreateDuplicateInsatnce();
            Console.WriteLine(D.Name);
         
        }

    }

public class Person
{
   
    public string Name;
   

    public Person CreateDuplicateInsatnce()
    {
       return (Person)this.MemberwiseClone();
    }

}


 

5. Serialize and Deserialize

In simple words, we can say an object conversion in text stream is serialization and text stream creation in object of a classis called deserialization
Example-:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

    class Program
    {
        
       static void Main(string[] args)
        {
            Serialize();
            Deserialize();
        }
        static void Serialize()
        {
           Person P = new Person();
           P.Name="Deepak";
           FileStream fs = new FileStream("DataFile.dat"FileMode.Create);
           BinaryFormatter formatter = new BinaryFormatter();
           formatter.Serialize(fs, P);
           fs.Close();


        }
        static void Deserialize()
        {
            Person D = null;
            FileStream fs = new FileStream("DataFile.dat"FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            D = (Person)formatter.Deserialize(fs);
            fs.Close();
            Console.WriteLine(D.Name);
            Console.ReadKey();

        }

    }

 [Serializable]
public class Person
{
    public string Name;
    public Person CreateDuplicateInsatnce()
    {
       return (Person)this.MemberwiseClone();
    }

}

6. Server.CreateObject(ASP WAY)-:


The CreateObject method creates an instance of an object. 
Example-:
<%
Set adrot=Server.CreateObject("MSWC.AdRotator")
%>


7.  ChannelFactory(WCF Way)-:

Using the ChannelFactory<T> class to make calls to your WCF services is an easier alternative to the laborious process of generating proxies via the SvcUtil tool every time a service contract changes. As its name suggests, ChannelFactory is a factory for creating service communication channels at runtime and creates object .

Example-:

 

[ServiceContract]public interface IService1{
    [OperationContract]
    
string GetData(int value);
    [OperationContract]
    
CompositeType GetDataUsingDataContract(CompositeType composite);
    // TODO: Add your service operations here}
BasicHttpBinding myBinding = new BasicHttpBinding();EndpointAddress myEndpoint = new EndpointAddress("http://localhost:3047/Service1.svc");ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);
IService1 instance = myChannelFactory.CreateChannel();
// Call Service with new object
Console.WriteLine(instance.GetData(10));
myChannelFactory.Close();
 8AppDomain.CreateInstanceAndUnwrap

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.
Example-:

using System;
using System.Reflection;

public class Worker : MarshalByRefObject
{
    public void PrintDomain() 
    { 
        Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName); 
    }
}

class Example
{
    public static void Main()
    {
        // Create an ordinary instance in the current AppDomain
        Worker localWorker = new Worker();
        localWorker.PrintDomain();

        // Create a new application domain, create an instance 
        // of Worker in the application domain, and execute code 
        // there.
        AppDomain ad = AppDomain.CreateDomain("New domain");
        Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(
            Assembly.GetExecutingAssembly().FullName,
            "Worker");
        remoteWorker.PrintDomain();
    }
}

Monday, December 3, 2012

Upcasting and downcasting in C#


Upcasting converts an object of a specialized type to a more general type
Downcasting converts an object from a general type to a more specialized type


BankAccount    ba1,
                   ba2 =   new BankAccount("John", 250.0M, 0.01);
    LotteryAccount la1,
                   la2 =   new LotteryAccount("Bent", 100.0M);

    ba1 = la2;                    // upcasting   - OK
//  la1 = ba2;                    // downcasting - Illegal 
                                  //   discovered at compile time
//  la1 = (LotteryAccount)ba2;    // downcasting - Illegal
                                  //   discovered at run time
    la1 = (LotteryAccount)ba1;    // downcasting - OK 
                                  //   ba1 already refers to a LotteryAccount