Friday, 7 December 2012

Abstract class in c# ,asp.net


All about abstract classes.
By Jayababu, 26 Feb 2004
   4.55 (148 votes)

Top of Form
Introduction
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:
 Collapse | Copy Code
abstract class absClass
{
}
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:
 Collapse | Copy Code
abstract class absClass
{
  public abstract void abstractMethod();
}
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:
 Collapse | Copy Code
abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}
A sample program that explains abstract classes:
 Collapse | Copy Code
using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0},
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers andMultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation andMultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers andMultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.
Example
 Collapse | Copy Code
//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. TheAddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2and the MultiplyTwoNumbers is implemented there.
Abstract properties
Following is an example of implementing abstract properties in a class.
 Collapse | Copy Code
//Abstract Class with abstract properties
abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}
In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.
Important rules applied to abstract classes
An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
 Collapse | Copy Code
//Incorrect
abstract sealed class absClass
{
}
Declaration of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.
 Collapse | Copy Code
//Incorrect
private abstract int MultiplyTwoNumbers();
The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
 Collapse | Copy Code
//Incorrect
public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static.
 Collapse | Copy Code
//Incorrect
publpublic abstract static int MultiplyTwoNumbers();
Abstract class vs. Interface
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
 Collapse | Copy Code
interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.


Page life cycle in asp.net


General page life cycle stages:
1.       Page Request : - The  page request occur before the page life cycle begin .
2.       Start:- In the start, page properties such as request and response are set. At this stage , also determine whether the request is a postback or a new request and set’s ispostback  properties .this stage also set’s the uiculture properties .
3.       Initialization’s :- During the page initialization all controls are available and uniqueId properties of every control is set .A master page and theme are also apply in this stage if applicable .
4.       Load :- during the load , if the current request is postback   ,control properties are set with recover from viewstate and control state
5.       Post back event handling : - If the request is postback then control event handler are called , after the validate method for all validator control are called , which set’s the Isvalid property of all validator control .
6.       Rendering:- before rendering  viewstate of page and controls are saved. During the rendering  stage page call render method for every control of the page .
7.       Unload:- the unload event call after when the page is fully rendered ,sent to the client , and ready to discarded .
Life cycle event:
Within each stage of page life cycle , the page raised some events that you can use to run your own code .
1.       PreInit:- raised after the start stage has been complete and before initialization event raised .
Use this event for following :-
1.1   check is Ispostback .
1.2   create or re-create dynamic controls.
1.3   Set a master page dynamically .
1.4   Set theme property
1.5   Read or set profile property values.

2.       InIt:-  Raised after controls have been initialized and any skin setting has been applied . Use this event to read or initialize control properties .
3.       Initcomplete:- Raised at the end of the page initialization stage . Use this event to make changes to view state that you want to make sure persisted after the next post back .
4.       Preload:- Raised after the page loads view state for itself and all controls, and after it process post back data that is included with the request instance .
5.       Load:-  The page object call onload method on page object . use the onload event method to set properties in controls and establish the data base connection .
6.       Controls Event:- use this event to handle thre specific control event , such as button click event .
7.       Load Complete :- Raised at the end of the event handling stage .
8.       Pre Render : -Raised after the page object has created the all control that are required in order to render the page . Use this event to make final changes to the content of the  page .
9.       Pre Render complete :- Raised after data bound whose DataSourcdeId property set call its databind method .
10.   Save state complete:- Raised after the
11.   Unload:



Find nth top salary in MSSQl Server Query


use playwithjoinsbybookstore

select top 1 a.salary,name  from (select distinct top 3 salary ,name from Tbl_Employ order by salary desc ) as a order by salary 



and also with aggregate function 

select min(salary) from tbl_employ where salary in (select top 5 salary from tbl_employ order by salary desc

Monday, 3 December 2012

The MVC 4 improve those features

1. Refreshed and modernized default project templates
2. New mobile project template 
3. Many new features to support mobile apps
4. Recipes to customize code generation 
5. Enhanced support for asynchronous methods. 

   For more details, you can refer to: Click here

Monday, 5 November 2012

Generic Class or types


Generic Types

Generics are the most powerful feature of C# 2.0. It allows defining type-safe data structures, without committing to actual data types. In C# 1.0 we can either declare reference type or value type. But in most of the application we come across situation where we need type that can hold both reference & value type. In such situation we use generic types.

Why Generics?
  1. Generic type doesn't care what the type is. We can specify the type at runtime.
  2. It avoids boxing difficulties. In C# 1.0, if we want to put any object into a List, Stack, or Queue objects, we have to take type as System.Object.
  3. It boosts the performance of the application because we can reuse data processing algorithm without duplicating type-specific code.
How Generic implemented:

(1)    Generic type is instantiated at run-time not compiled time
(2)    Generic type are checked at time of declaration not at instantiation
(3)    It works for both reference type & value type.

Let's create simple class "GenericList" using C# 1.0 & 2.0 respectively & compare them.


Code GenericList Class (C# 1.0)

using System;
using System.Collections.Generic;
using System.Text; 
public class GenericList
    {
        private  object[] elements;
        private int count; 
        public GenericList()
        {
            elements = new object[10];
        }
        public object this[int index]
        {
            get { return elements[index]; }
            set { elements[index] = value; }
        } 
        public void Add (object parm)
        {
            if (count == elements.Length)
            {
                  // Increase the
                  object[] tmpArray = null ;
                  elements.CopyTo(tmpArray,0);
                  elements = new object[count * 2];
                  elements = tmpArray;                             
            }
            elements[count] = parm;
            count = count + 1;
        }
   }    

Main Method:

static void Main(string[] args)
        {
            Console.WriteLine("using C# 1.0"); 
            GenericList list = new GenericList();
            list.Add(20);        //Argument is boxed
            list.Add(40);        //Argument is boxed
            list.Add("Sixty");   //Error in retrieving
            Console.WriteLine("Item Added"); 
            int val = (int)list[0]; //Casting required
            Console.WriteLine("Value retrived : " + val); 
        }

Memory Consumption

In C# 1.0 boxing is necessary evil to make type system work. While working with structures of System.Collection namespace (Stacks,List,Hashtable etc) we face the problem in insertion & retrieval of values. We need to take System.object as type & System.object is reference type, so whenever we access the hashtable, the runtime has to box the values to put into the collection & need to unbox to take it out.

list.Add(20);        //Argument is boxed

In C# int takes 4 byte but when it boxed it take (4+8) 12 bytes, which is 3 times to normal size.
In C# 2.0 the type is decided at runtime so boxing does not take place.

Type Safe

When we use the statement

list.Add ("Sixty"); or List [3] = "sixty";

It compiles successfully but later on if some one pulls value and cast it into integer it fails. The problem is fixed in C# 2.0; we will get compilation error there.


Code GenericList Class (C# 2.0)

public class GenericList<T>
    {
        public GenericList()
        {
            elements = new T[10]; 
        } 
        private T[] elements;
        private int count;        
        public T this[int index]
        {
            get {return elements [index];}
            set {elements [index] = value;}
        }    
        public void Add (T parm)
        {
            if (count == elements.Length)
            {
                T[] tmpArray = null;
                elements.CopyTo(tmpArray, 0);
                elements = new T [count * 2];
                elements = tmpArray; 
            } 
            elements [count] = parm;
            count = count + 1;  
        } 
    }

Main Method:

static void Main(string[] args)
{Console.WriteLine("using C# 1.0"); GenericList<int> genericList = new GenericList<int>();genericList.Add (10);          //No boxinggenericList.Add (20);          //No boxing
// genericList.Add("Fifty");   //Compile Time ErrorConsole.WriteLine("Item Added"); int valGeneric = (int)genericList[0]; //No Casting RequiredConsole.WriteLine("Value retrived : " + valGeneric); 
}

Some other Points:

(1) Type parameter can be applied to Class, struct, interface & delegates.
 struct Buket<K, V>; interface ICompare<T>
(2)    Type parameter can have constraints.

Wednesday, 10 October 2012

Asp.Net 2 tier and 3 tier architecture ..



3 Tier Architecture:===================
1st Tier is your Presentation Tier which is your asp/aspx page.

2nd Tier is your Business/Logic Tier which is your custom components.

3rd Tier is your Data Tier which is your database MS SQL Server or Microsoft Access or ORACLE etc.



2 Tier Architecture:
===================

1st Tier is your Presentation Tier which is your asp/aspx page.

2nd Tier is your Business/Logic Tier which issues SQL statements directly to Database.

2 Tier Architecture eliminates the use of custom components, but its a good practice to use 3 Tier architecture to make secure your Business/Logic Tier.