Thursday, September 30, 2010

Abstract and Sealed concepts

Abstract classes and members

Abstract keyword used to define class and class members for the purpose of inheritance.
An abstract class can't be instantiated and an abstract method doesn't have definition in base class, declaration followed by semicolon.

public abstract classA
{
public abstract void dowork(int i); //Abstract method has only declaration in base class
}

A non abstract derived class of an abstract base class must define all the abstract methods of base class and inherited abstract members from upper hierarchy of base class.
public classB : classA
{
public override void dowork(int i)
{
//Implementation of abstract method of base class
}
}

A. Should not define public or protected internal constructor.
B. Can be define Protected or internal constructor.
C. Abstract members are implicitly Virtual.
D. Declaring an abstract member as Virtual or Static is an error.
E. Abstract class may contain non abstract members, non abstract members can have definition in abstract class, meant common method for all derived classes without overriding the method.
F. An abstract derived class can define or not define abstract members of base class.
G. An abstract class can't be declared as Sealed, because having opposite meaning.
H. Non abstract class can't contain abstract members, abstract method can be declared in Abstract class.
I.  An abstract method declaration don't have braces {}, declaration followed by semicolon only.
    Ex.  public abstract void dowork(int i);
J. An Abstract class must implement all members of inherited Interface but not required to override all abstract members of inherited base class.
k. Abstract method declaration is allowed to override a virtual method of base class.

class A
{
   public virtual void F() {
      Console.WriteLine("A.F");
   }
}
abstract class B: A
{
   public abstract override void F();
}
class C: B
{
   public override void F() {
      Console.WriteLine("C.F");
   }
}

Purpose of abstract class to make common definition of a base class that multiple derived classes can share.
A class library has a abstract class than programmers can use the library and have their own implementation of derived class using base abstract class.

Ex.
     public abstract class Animals
    {
        public void Move()  //Non Abstract function
        {
            string s = "All animals can move";
        }
        public abstract void Breath();   
    }
    public class Dogs : Animals
    {
        public Dogs() { }
        public override void Breath()
        {  //Breath in open air
        }
    }
    public class Fish : Animals
    {
        public Fish() { }
        public override void Breath()
        {  //Breath in water
        }
    }
Dogs DaburMan = new Dogs();
            DaburMan.Breath();   //Abstract function of base abstract class
            DaburMan.Move();     //Non Abstract function of base abstract class
       Fish Shark = new Fish(); 
            Shark.Breath();  //Abstract function of base abstract class
            Shark.Move();    //Non Abstract function of base abstract class

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

Sealed classes and members


A sealed class can't be inherited, Sealed keyword is used to protect from derivation a class.
A sealed class can't be abstract, because of opposite meaning.
A sealed method also can't be override in derived class.
When applied to method or property sealed keyword always used with override keyword.

If you override an base class virtual method in derived class, you can declare that sealed there(on override) to protect override of that method in further derived classes. This negates the virtual aspect of the member for any further derived class.

public class D : C
{
public sealed override void DoWork()
{
// Implementation
}
}

Scenario - Creating Sealed class
1. To take away inheritance feature from users so they can't inherit that class.
2. If we have some internal operation/s in class or function, because access of class or function in this case can be harmful. ex. .net's string class is sealed.
3. If we have static members in class(Static members are sealed by default). ex pen, brush classes are sealed.

Saturday, September 25, 2010

What's new in the .NET framework version 3.5

  1. Framework - 3.5 extends many new features like Linq, WCF those are useful to develop pocket PC, smart phone and distributed mobile applications.
  2. ASP.Net -
    1. 3.5 includes AJAX while in 2.0 it needs to install. Microsoft AJAX library supports client-centric, object orient development which is browser independent. ScriptManager to make a page AJAX enable. UpdatePanel to target a specific area of page rather than refreshing whole page.   
    2. Visual web developer includes improved intellisense for java script and Ajax library.
    3. Listview control displays data provided by data source by using user defined templates. User can select, insert, update, delete and sort records. Listview includes features of data grid, grid view, data repeater and other similar list controls available in 2.0.
    4. Data pager provides paging functionality to data bound controls those implements ‘Ipageableitemcontainer’ interface like listview control.
    5. LinqDataSource for Linq(Language integrated query).
    6. ASP.Net Merge Tool to merge precompiled assemblies (aspnet_merge.exe) .
  1. Add-Ins and Extensibility - 3.5 introduces new architecture and model that enables powerful and flexible support to developers to develop extensible applications.

  2. CLR – 3.5 has improved CLR. Also has improvements in collection, garbage collection, better reader and writer locks in threading, i/o and pipes, reflection, diagnostics etc.

  3. Cryptography – 3.5 includes improved features for security. Some new cryptography classes added those used to verify and obtain information of manifest signature. 3.5 supports suite B cryptography algorithms published by National Security Agency(NSA).

  4. Networking Several features of networking get improved in 3.5. Peer to peer networking is server less networking technology allows network devices to share resources and communicate with each other directly, is get improved in 3.5.

  5. LINQ Its a new feature in 3.5 extends powerful query capabilities to language syntax of C#, VB.Net. Its standard, easy to understand and learn. 3.5 extends some assemblies those enable the use of Linq to query .net collections, databases, xml documents, ado.net data sets.
    System.Linq – (exist in System.core.dll) Extends standard operators and types for Linq.
    System.Data.Linq – Enables interaction with databases.
    System.Data.Linq.Mapping – Enables to generate Linq to Sql object model.
    System.xml.Linq – Enables Linq to access and modify xml documents.

  6. Expression trees – Expression trees are new in .net 3.5, it provides a way to present language level code in the form of data.

Thursday, September 2, 2010

SQL SERVER - Sql Server2000 Vs Sql Server 2005

  1. In 2005 enterprise manager and query analyzer given together, you can also open multiple windows in same enterprise manager.
  2. In 2005 you can create 2(pow(20)-1) databases while in 2000 its 65,535.
  3. 2005 introduced some new data types like ‘xml’.
  4. In 2005 you can store large value and object type by using ‘max’ like varchar(max), nvarchar(max), varbinary(max).
  5. In 2005 you can write try – catch statements in stored procedure.

    NSRI (shortcut to remember) in Sql Server 2005 –

    Notification services enhancement
    Service broker
    Reporting service enhancement
    Integration service enhancement

Delegate

A delegate is a type that defines a method signature. When you create an instance of the delegate, you can associate a method to the instance of compatible signature, now you can call or invoke that method by the delegate instance.
Delegates are used to pass a method as argument to other method. A delegate instance can be assigned a method of any accessible class or struct that matches signature of delegate, method can be static or instance method.
Ex.
Public Delegate int myDelegate(int x, int y); //Delegate declaration
Public int add(int a, int b) //Method definition
{
Return a+b;
}
myDelegate del = add;  //Delegate instance del assigned method ‘add’
                                   //(Equivalent to  myDelegate del = new myDelegate(add); )

del(12, 30); //call or invoke

General terms
1. Delegates are like function pointers in C or C++.
2. Delegates can be used to pass a method as argument to other method.
3. Delegates can be chained together, multiple methods can be called on a single event. When you call a delegate that is chained(added multiple delegates) then all the methods called on this single call this is called Multicasting or Chaining of delegates. All methods called in the sequence in which they added. 
4. Covariance allows a more derived return type method to be assign than delegate’s return type.
5. Contravariance allows less derived parameters type method to be assign than delegate’s parameter’s type.
6. Framework 2.0 introduced anonymous methods, which allows code blocks to be passed to delegate as parameter in place of separately defined method.
Code block may contain anonymous method or lambda expression. 

//Instantition of myDelegate with instance mdel assigned anonymous method
myDelegate mdel = delegate(int m, int n) {
//Code block
}
//Instantition of myDelegate with lambda expression
(input parameters) => expression //lambda expression


myDelegate mdel =  (int x, int y) => { Code block }
OR
myDelegate mdel =  (x, y) => { Code block }  //Compiler infer input types by own

mdel(20,100); //Call or invoke
7. Delegates types ex. del (instance of delegate - myDelegate del; ) are drived from Delegate class, delegate types are sealed they can not be derived from.
8. When you invoke delegate, parameters passed to the delegate, pass to the method and returns value (if have return type) through delegate, its not possible to create custom class from Delegate class.
9. Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter and call the delegate at some later time this is called
Asynchronous callback.
10. Delegate can be assign static method.
11. A delegate can be chained (multicast) with static and instance both type methods together.


In C# 1.0 and later, delegates can be declared as shown in the following example.
// Declare a delegate.
delegate void Del(string str);

// Declare a method with the same signature as the delegate.
static void Notify(string name)
{
    Console.WriteLine("Notification received for: {0}", name);
}
// Create an instance of the delegate.
Del del1 = new Del(Notify);

C# 2.0 provides a simpler way to write the previous declaration, as shown in the following example.
// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;

In C# 2.0 and later, it is also possible to use an anonymous method to declare and initialize a delegate, as shown in the following example.
// Instantiate Del by using an anonymous method.
Del del3 = delegate(string name)
    { Console.WriteLine("Notification received for: {0}", name); };

In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example.
// Instantiate Del by using a lambda expression.
Del del4 = name =>  { Console.WriteLine("Notification received for: {0}", name); };

Combining or multicasting of delegates
Public Delegate void Del(String s);
Class Test
{
Static void hello(string s)
{
System.Console.WriteLine(“Hello {0}!”,s);
}

Static void Goodbye(string s)
{
System.Console.WriteLine(“Good Bye {0}!”,s);
}

Static void main()
{
Del a, b, c, d;
a = hello; //Assigning hello method to delegate a

b = Goodbye; //Assigning hello method to delegate a

c = a + b; // ( OR c = a; c += b;)

d = c – b; // ( OR d = c; d -= b;)
a(“Ram”); // Invoke delegate a
b(“Shyam”); // Invoke delegate b
c(“Ravi”); // Invoke delegates a then b
d(“Shubham”); // Invoke delegate a
}
}
Output
Hello Ram! //result of a
Good Bye Shyam! //result of b
Hello Ravi!     //result of c
Good Bye Ravi!
Hello Shubham! //result of d

Friday, August 27, 2010

Static Concept (Shared in VB)

Static Concept
The static modifier can be used with fields, properties, methods, events, constructors, operators and classes. You can not use static modifier with destructors, indexers and types other than classes.
A type or a constant declaration is implicitly static, so that any type defined in class directly accessed by class name.

public class MyBaseC
    {
        public struct MyStruct
        {
            public static int x = 100;
        }
    }

Console.WriteLine(MyBaseC.MyStruct.x); 


Static class
Static class is a class that contains all static members and neither be instantiated nor inherited.
Members of the static class called by the name of class.
Making a class with all static members and a private constructor is same as creating a static class, because a private constructor protects a class to be instantiated.
Terminology
1. Can’t be instantiated.
2. Can’t be inherited.
3. Can contain only static members.
4. Sealed by default, they can not inherit from any class except Object class.
5. Can’t contain instance constructor, can contain static constructor.
Ex.

class myClass
        {
            public class myStaticClass
            {
                public static int Age;
                public static void Display(int x)
                {
                    //Method implementation
                }
            }
            public static void main()
            {
                myStaticClass.Age = 30;
                myStaticClass.Display(55);
            }
        }

Static members
Static members of a class are accessible directly by the name of class, can’t be accessed by instances.
A Static member is shared member for all the instances of class and accessed only by the name of class, only one copy exist of a static member.
Can be used to count no. of instances created or to stores some value that is shared b/w all instances.

Terminology

1. Static methods / properties can’t access other non-static members.
2. Static methods can be overloaded and can’t be overridden because they belong to class not to instance.
3. Constants can’t be declared static, because they are by default static.
4. C# does not support static local variables (variables that are declared in method scope).

Example - For employees of a company, if a class gives Name and address info of company then class should be static because these things are common for all employees.
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
class Math is a static class.

Saturday, August 7, 2010

Generics


Note - Please ignore all the single quotes, put for some technical reason.

A generics is class, method, interface or structure that have place holder for types parameter.
A generic class has type parameter for its fields, methods’ parameters.
A method has type parameter for return type or one of its formal parameters.

Storing value / reference type or different data types in a single list(collection) achievable with ‘ArrayList’.

ArrayList lst1 = new ArrayList();

Lst1.add(10);
Lst1.add(150);
Lst1.add(“Red”);
Lst1.add(“Blue”);

But it comes at a cost of type conversion and not type safe also.
Every time when we add a value type to the list, boxing needed and when we retrieve it from list, unboxing needed, all it done implicitly.

Generics introduced with framework 2.0 that can achieve it without type conversion and also type safe.

Below given class definition can be used with any data type.


Class Myclass <’T’>
{

}

Myclass’<int> mycInt =new Myclass ‘<int>’ ();

Myclass’<'string'> mycStr =new Myclass’<'string'>’();

Namespace System.Collection.Generic provides some collection classes those support Generics.
Like Queue, Stake, List, Linked list etc.

Benefit : Code re-usability, type safe, no type casting required and efficient.

Terminology

1. Generic type definitions are templates you can’t instantiate the template, you must specify type at the time of instantiation.
2. Generic type parameters are place holders for types.
3. When we create instance of generic type definition, we specify type and the instance called ‘constructed type’ or ‘constructed generic type’.
4. General term generic type contains both ‘generic type definition’(template) and ‘generic constructed type’(instance).
5. A generic method has two parameter lists one is generic type and another is formal type.
T MyMethod1(T t) //Not a generic method
{
T temp = t;
Return temp;
}

A generic method must has its own generic types list.

T MyMethod2 <’T’> (T t) //Generic method
{
T temp = t;
Return temp;
}

Class myClass <’T’> //Generic Class
{
T MyMethod1(T t)
{
T temp = t;
Return temp;
}
}

Example : By stake examples we will try to understand benefit of Generics

For integers you can implement and use the IntStack:

public class IntStack
{
int[] m_Items;
public void Push(int item){...}
public int Pop(){...}
}

IntStack stack = new IntStack();
stack.Push(1);
int number = stack.Pop();

For strings you would implement the StringStack:

public class StringStack
{
string[] m_Items;
public void Push(string item){...}
public string Pop(){...}
}

StringStack stack = new StringStack();
stack.Push("Ram");
string name = stack.Pop();

//Using Generics we can make above approach with code reusability

public class Stack'<'T'>'
{
T[] m_Items;
public void Push(T item)
{...}

public T Pop()
{...}

}

Stack'<'int'>' stack = new Stack'<'int'>'(); //Integer stack

stack.Push(1);
stack.Push(2);
int number = stack.Pop();

Stack'<'string'>' stack = new Stack'<'string'>'(); //String stack

stack.Push("Ram");
stack.Push("Shyam");
string name = stack.Pop();

A generic class is declared without a specific type applied to it in the definition. Rather, the type is specified at the time the object is used.

Q. How Generics are type-safe?
Ans. A Generic type is a template, we specify type at the time of instantiation then you can add or assign items of only specified type to that instance, can't be added any type other than specified type, if you attempt to add any other type code will not compile .
===================
Ex.
public class Lineclass<'T'>:Page
{
public T LineMethod<'T'>(T t)
{
T Temp = t; return Temp;
}
internal string convt<'T'>(T Tnt)
{
T temp = Tnt; return temp.ToString();
}
public void main()
{
Lineclass<'double'> lc = new Lineclass<'double'>();
Response.Write(lc.convt(lc.LineMethod(500.00)));
}
}

**************************************************************
Generics - Brief detail

Requirement of generics -
A. Eliminating Repetitive code blocks with different data type.
B. Performance issue.
C. Insuring type safety.
D. Making code efficient.

Multiple generic types -
A single type can define multiple generic-type parameters. consider the code block

public Class Node'<'K,T'>'
{

public K Key;
public T Item;
public Node'<'K,T'>' NextNode;

public Node()
{
Key = DEFAULT(K);
Item = DEFAULT(T);
NextNode = null;
}

public Node(K key, T item, Node'<'K,T'>' netxtNode)
{
Key = key;
Item = item;
Nextnode = nextNode;
}

}

public class LinkedList'<'K,T'>'
{
Node'<'K,T'>' mHead;
public LinkedList()
{
mHead = new Node'<'K,T'>'();
}

public void AddHead(K key, T item)
{
Node'<'K,T'>' newNode = new Node'<'K,T'>'(key, item, mHead.NextNode);
mHead.Nextnode = newNode;
}
}

using List = LinkedList'<'int,string'>';
Public class ListClient
{
Void Main()
{
List Node1 = List();
Node1.Addhead(5,"First Node");
}
}

Constraint - When you define generic type, you can define constraints also there to restrict client code to use type that constraints allows.
You can define one or more constraints on generic type definition.

Requirement of Constraints - Whenever we need to validate or compare an item of generic list, compiler must have some guarantee that used operator or method will be applicable (compatible) with any type argument supplied by client code, this can be achieved by constraints.

Constraint

Description

Where T : struct

Type argument must be value type and not nullable.

where T : class

Type argument must be reference type, it can be class, interface, array, delegate.

where T : new()

Type argument must have a parameter less public constructor. If you are using this constraints with other then it must specified at last.

where T :

Type argument must be given base type or derived from given base type.

where T :

Type argument must be given interface type or type that implemented given interface. Multiple interface constraints can also be defined. Supplied interface type can be generic type.

where T : U

Type argument must be type or derived type of type supplied for generic U



Inheritance with generics -
If you inheriting a generic class in a concrete class than you must specify constructed generic type at inheritance.
public class vehicle'<'T'>'
{
}
Public class Car : Vehicle'<'int'>'
{
}

If child class is a generic class then you can use type parameter of base class for child class
Public class Car'<'T'>' : Vehicle'<'T'>'
{
}

If base class having constraints for generic type than you must re specify constraints at inheritance.
public class Car'<'T'>' : vehicle'<'T'>' where T : new()
{
}

Ex.2
public class Bike'<'T'>' : vehicle'<'T'>' where T : struct
{
}

Generic methods -
A method can define generic type parameters, even if containing class not using generics at-all this method called Generic method.
A generic method has type parameter for one of its formal parameter and it's return type.

public class Bicycle
{
public T Drive'<'T'>'()
{
T t = null;
return t;
}

public T Drive'<'T'>'(T t, int a)
{
return t;
}

}

If you are overriding a method of base class you must re-specify generic parameters.
If virtual method having constraint than you must re-specify constraints also on overridden method.
you can't add more constraints on overridden method.

public void SomeMethod'<'T'>'(T t) where T : IComparable'<'T'>'
{...}

At calling of generic method you have to specify data type of generic parameter type.
Bicycle obj = new Bicycle();

obj.Drive(); //Compile time error
obj.Drive'<'int'>'(); //Ok

obj.Drive("hello", 3); //Ok
obj.Drive'<'string'>'("hello", 3); //Also ok

C# compiler is smart enough, so if one of the parameter of method is generic type then you can call method
without specifying data type for generic type parameter, compiler will determine data type automatically by using passed
value of parameter.
obj.Drive'<'string'>'("hello", 3);

Generic static methods -
public class Truck'<'T'>'
{
public static void Speed(T t)
{....}

public static T Speed'<'X'>'(T t, X x)
{....}

}

If a static method using generic type parameter of its class then we will call it like
Truck'<'int'>'.Speed();

If method is generic then we will call it like
Truck'<'string'>'.Speed'<'int'>'("speed measer", 50);

Delegates and Generics - A Delegate can also define generic parameters like methods.

public class Truck'<'T'>'
{
public delegate void MsgSpeed(T t); //Delegate within class
public void SpeedA(T t);
public void SpeedB'<'X'>'(X x)
{....}

}

Truck'<'int'>' trk = new'<'int'>'();
Truck'<'int'>'.MsgSpeed delk;
delk = trk.speedA;
delk(20);

public delegate void TrcSpeed'<'X'>'(X x); //Delegate declared outside class
TrcSpeed'<'string'>' delc;
delc = new TrcSpeed'<'string'>'(trk.SpeedB);
delc("Del trace");

Reflection and Generics - type of Type now can represent generic type.

LinkedList'<'int,string'>' list = new LinkedList'<'int,string'>'();

Type type1 = typeof(list); //Bounded types
Type type2 =list.GetType();

Type typeU1 = typeof(LinkedList'<','>'); //Unbounded types
for multiple generic types we use ",".

Thursday, August 5, 2010

Welcome to my blog

I heartily welcome you on my blog.
I’ll post here my learnings from .net technology.


Thanks.

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...