Monday, September 24, 2007

FAQ in Generics

1. Which Versions of the .NET Framework Support Generics?
Generics are only supported on version 2.0 and above of the Microsoft .NET framework, as well as version 2.0 of the compact framework.
2. Can I Use Generics in Web Services?
Unfortunately, no. Web services have to expose a WSDL-based contract. Such contracts are always limited by the expressiveness of the message format being used. For example, HTTP-GET based web services only support primitive types such as int or string, but not complex types like a DataSet. SOAP-based web services are more capable, but SOAP has no ability to represent generic type parameters. As a result, at present, you cannot define web services that rely on generic types. That said, you can define .NET web services that rely on closed constructed generic types, for example:
[C#]
public class MyWebService
{
[WebMethod]
public List GetCities()
{
List cities = new List();
cities.Add("New York");
cities.Add("San Francisco");
cities.Add("London"); return cities;
}
}
In the above example, List will be marshaled as an array of strings.
3. Can I Use Generics in Enterprise Services?
Unfortunately, no. All methods and interfaces on a ServicedComponent-derived class must be COM-visible. The COM type system is IDL, and IDL does not support type parameters.
4. Can I Use Generics in Indigo?
Unfortunately, no. SOAP has no ability to represent generic type parameters, and so all methods and interfaces on an indigo service contract or service class can only use primitive types such as integers or strings, or specific known types that provide a data contract. As a result, at present, you cannot define Indigo services that rely on generic types, that is, services that leave it up to the service consumer to specify the types to use when invoking the service.
5. Can I Use Generics in .NET Remoting?
Yes. You can expose generic types as remote objects, for example:
[C#]
public class MyRemoteClass : MarshalByRefObject {...}
Type serverType = typeof(MyRemoteClass);
RemotingConfiguration.RegisterWellKnownServiceType(serverType, "Some URI", WellKnownObjectMode.SingleCall);
Note that the specific type arguments used must be a marshalable type, that is, either serializable or derived from MarshalByRefObject. Consequently, a generic remote type will typically place a derivation constraint from MarshalByRefObject on its generic type parameters when expecting reference type parameters:
[C#]
public class MyRemoteClass : MarshalByRefObject where T : MarshalByRefObject {...}
To administratively register a generic type, provide the type arguments in double square brackets.
For example, to register the class MyRemoteClass with an integer, you should write:

The double square brackets is required in case you need to specify multiple type arguments, in which case, each type arguments would be encased in a separate pair of brackets, separated by a comma. For example, to register the class MyRemoteClass with an integer and a string, you would write:

Creating a new instance of generic remote objects is done just as with non-generic remote objects.
6. Can I Use Visual Studio 2003 or the .NET Framework 1.1 to Create Generics?
Unfortunately no. Generics are only supported on version 2.0 and above of the Microsoft .NET framework. Code that relies on generics must run on version 2.0 of the CLR. Because of the way the CLR version unification works, a run-time process can only load a single version of the CLR. Consequently, a process that loaded version 1.1 of the CLR cannot use generic types. If you must use generic types from .NET 1.1, you can use the following work-around: First, wrap the generic types with object-based types (at the expense of course of the benefits of using generics). Next, load the wrapper classes in a separate process which loads version 2.0 of the CLR, and provide remote access to the wrapper classes to legacy clients in process that use version 1.1 of the CLR. For remote communication you can use any number of cross-process communication mechanisms, such as Remoting, Enterprise Services, sockets, etc.
6. What Environment Do I Need to Use Generics?
To deploy and run code that uses generics you need version 2.0 or higher of the .NET runtime.
7. Can I Use Generics on the Compact Framework?
Yes. The .NET Compact Framework version 2.0 supports generics. Like most other things with the .NET Compact Framework, the generics support is very close but not exactly the same as the normal .NET Framework, due to performance and schedule constrains. You can use generics with both C# and Visual Basic for the compact framework. The compact framework does apply certain limitations on generics, the notable ones are:
· The compact framework does not verify constraints are runtime, only at compile time.
· You can only have up to 8 generic type parameters per generic type.
· You cannot use reflection on unbounded generic types.
8. Which .NET Languages Support Generics and How?
Both C# 2.0 and Visual Basic 2005 support defining and consuming generics. Visual C++ 2005 also supports generics in addition to classic C++ templates. Visual J# 2005 supports consuming generic types but not defining them. At present, it is not known of other vendors besides Microsoft that added generics support for their languages.
9. Where Does the .NET Framework Itself Use Generics?
Version 2.0 of the .NET Framework makes use of generics in three main areas: The System namespace added a large set of static generic methods to the Array type. These methods automate and streamline common manipulations of and interactions with arrays. The System namespace also defined a number of generic utility delegates, which are used by the Array type and the List class, but can be used freely in other contexts as well. In addition, System provides support for nullable types. The System namespace defines the IComparable interface and the EventHandler delegate, both generic reincarnations of their non-generic predecessors. The System namespace also defines the IEquatable interface, used to check for equality of two values. The System namespace defines the ArraySegment used to allocate a strongly typed portion of an array.
The System.Collections.Generic namespace defines generic collection interfaces, collections and iterator classes, similar to the old, non generic ones available in the System.Collections namespace. The System.Collections.Generic namespace also defines a few generic helper classes and structures.
The System.ComponentModel namespace defines the class BindingList. A binding list is used very similar to a mere generic list, except it can fire events notifying interested parties about changes to its state.
The System.Collections.ObjectModel namespace defines a few types such as Collection that can be used as base types for custom collections.
Finally, all the types that supported IComparable in .NET 1.1 support IComparable and IEquatable in .NET 2.0. This enables you to use common types for keys, such as int, string, Version, Guid, DateTime, and so on.
10. What Are the Generic Collection Classes?
The System.Collections.Generic namespace contains the majority of the new generic collections. These collections are by and large the generic reincarnation of the collections available in the System.Collections namespace. For example, there is a generic Stack and a generic Queue classes. The collections in System.Collections.Generic are used in much the same way as their predecessors. In addition, some of the collections where renamed in the process. The Dictionary data structure is equivalent to the non-generic HashTable, and the class List is analogous to the non-generic ArrayList. System.Collections.Generic also defines new types that have no equivalent in System.Collections, such as LinkedList and KeyValuePair. In addition, The System.Collections.Generic namespace defines generic interfaces such as ICollection and IList. To support generic-based iterators, System.Collections.Generic defines the IEnumerable and IEnumerator interfaces, and these interfaces are supported by all the generic collections. It is important to note that the generic collections can be used by clients that do not rely on generics, because all the generic collections also support the non-generic collection and iteration interfaces (IList, ICollection, IEnumerable). For example, here is the definition of the List class:
[C#]
public class List : IList,IList {...}
The System.ComponentModel namespace defines the type BindingList.
[C#]
public class BindingList : Collection, IBindingList,ICancelAddNew,IRaiseItemChangedEvents
{
public event ListChangedEventHandler ListChanged;
public event AddingNewEventHandler AddingNew;
public BindingList();
public BindingList(List list);
public T AddNew();
//More members
}
BindingList is used similarly to a generic list, except it can fire events notifying interested parties about changes to its state, so you can bind it to user interface controls such as the ListBox. You can use BindingList directly or you can wrap it around an existing List.
The System.Collections.ObjectModel namespace defines the types Collection, KeyedCollection, ReadOnlyCollection, and ReadOnlyCollection provided as base types for custom providers. Interestingly enough, none of the .NET-provided generic collections actually use these base collections.
Finally, the System namespace defines the ArraySegment helper structure, which can be used to obtain a generic-based segment of a provided array.
The following table lists the generic collections and their supporting types, including mapping the generic collections to those of System.Collections or other namespaces when applicable.





Type
Namespace
Non-Generic Equivalent
Comment
ArraySegment
System
-
Used to obtain a generic-based segment of a provided array
BindingList
System.ComponentModel
-
Linked list that fires state changes events
Collection
System.Collections.ObjectModel
Collection
Non abstract base class for other collections
Comparer
System.Collections.Generic
Comparer
Implements IComparer and IComparer
Dictionary
System.Collections.Generic
HashTable
Implements IDictionary
EqualityComparer
System.Collections.Generic
-
Abstract class implementing IEqualityComparer
ICollection
System.Collections.Generic
ICollection
Count and synchronization for a collection
IComparer
System.Collections.Generic
IComparer
Compares two specified values
IDictionary
System.Collections.Generic
IDictionary
Interface for a collection of key/value pairs
IEnumerable
System.Collections.Generic
IEnumerable
Returns an IEnumerator object
IEnumerator
System.Collections.Generic
IEnumerator
Iterating over a collection
IEqualityComparer
System.Collections.Generic
IEqualityComparer
(.NET 2.0 only)
Equates two specified values.
IList
System.Collections.Generic
IList
Implemented by list collections or access by index
KeyedCollection
System.Collections.ObjectModel
-
Base class for keyed collections
KeyValuePair
System.Collections.Generic
-
Container for key/value pair
LinkedList
System.Collections.Generic
-
A true linked list
LinkedListNode
System.Collections.Generic
-
Used by LinkedList, but can be used by custom lists as well.
List
System.Collections.Generic
ArrayList
Impalements IList over an array
Queue
System.Collections.Generic
Queue
A queue
ReadOnlyCollection
System.Collections.ObjectModel
ReadOnlyCollectionBase
Base class for read-only collections
SortedDictionary
System.Collections.Generic
SortedList
Implements IDictionary over a sorted collection
SortedList
System.Collections.Generic
SortedList
A sorted linked list over an array and a hash table.
Stack
System.Collections.Generic
Stack
A stack

11. What Are the Generic Delegates?
The System namespace defines five new generic delegates. The first is EventHandler defined as:
[C#]
public delegate void EventHandler(object sender,E e) where E : EventArgs
EventHandler can be used wherever an event handling method expects an object and an EventArgs-derived class as parameters. Obviously, that is the case wherever the non-generic EventHandler was used in .NET 1.1:
[C#]
public delegate void EventHandler(object sender, EventArgs e)
But in addition, EventHandler can be employed instead of all the other delegates that used EventArgs-derive class, such as MouseEventHandler:
[C#]
public class MouseEventArgs : EventArgs {...}
public delegate void MouseEventHandler(object sender,MouseEventArgs e);
void OnMyMouseEvent(object sender,MouseEventArgs e) {...}
//Instead of:
MouseEventHandler handler += OnMyMouseEvent;
//You can write:
EventHandler handler += OnMyMouseEvent;
The other four generic delegates found in the System namespace are designed to be used in conjunction with the static generic methods of Array or the List type, but you can easily use them in other contexts:
[C#]
public delegate void Action(T t); public delegate int Comparison(T x, T y); public delegate U Converter(T from); public delegate bool Predicate(T t);
generic
public delegate void Action(T t);
generic
public delegate int Comparison(T x, T y);
generic
public delegate U Converter(T from);
generic
public delegate bool Predicate(T t);
For example, here is using the Action delegate to trace every value in a given array:
[C#]
string[] cities = {"New York","San Francisico","London"};
Action trace = delegate(string text) { Trace.WriteLine(text); }; Array.ForEach(cities,trace);
12. What Are the Generic Methods of System.Array?
The System.Array type is extended with many generic static methods. The generic static methods are designed to automate and streamline common tasks of working with arrays, such as iterating over the array and performing an action on each element, scanning the array looking for a value that matches a certain criteria (a predicate), converting and sorting the array, and so on. Below is a partial listing of these static methods:
[C#]
public abstract class Array
{
//Partial listing of the static methods:
public static ReadOnlyCollection AsReadOnly(T[] array);
public static int BinarySearch(T[] array,T value);
public static int BinarySearch(T[] array,T value, IComparer
comparer);
public static U[] ConvertAll(T[] array, Converter converter); public static bool Exists(T[] array,Predicate match);
public static T Find(T[] array,Predicate match);
public static T[] FindAll(T[] array,Predicate match);
public static int FindIndex(T[] array,Predicate match);
public static void ForEach(T[] array,Action action);
public static int IndexOf(T[] array,T value);
public static void Sort(T[] array,IComparer comparer);
public static void Sort(T[] array,Comparison comparison);
}
Most of these static generic methods work with the four generic delegates defined in the System namespace:
[C#]
public delegate void Action(T t);
public delegate int Comparison(T x, T y);
public delegate U Converter(T from);
public delegate bool Predicate(T t);
For example, suppose the array roles contains all the roles a user plays at your application, and you would like to find out if the user is a member or a specified role.
[C#]
bool IsInRole(string role)
{
string[] roles = GetRoles();
Predicate exists = delegate(string roleToMatch)
{
return roleToMatch == role;
};
return Array.Exists(roles,exists);
}
string[] GetRoles() {...}
The Array.Exists() method defined as:
[C#]
public static bool Exists(T[] array,Predicate match);
takes a single type parameter (the type of the array). The compiler can infer the type automatically, so there is no need to specify that. The second parameter is a generic delegate of type Predicate(), which returns a Boolean value. The Array.Exists() method iterates over the array, and invokes the predicate delegate on each item in the array. If the predicate returns true, it stops the iteration and returns true. If all the items in the array return false from invoking the predicate on them, Array.Exists() returns false. In C#, you can initialize the predicate using an anonymous method, and have Array.Exists() invoke that method on every item in the array until the predicate is satisfied or there are no more items.
To demystify how those various methods work, here is how Array.Exist() could be implemented:
[C#]
public abstract class Array
{
public static bool Exists(T[] array,Predicate match)
{
if(array == null)
{
throw new ArgumentNullException("array");
}
if(match == null)
{
throw new ArgumentNullException("match");
}
foreach(T t in array)
{
if(match(t))
{ return true; }
}
return false;
} //Rest of the methods }
13. What Are the Generic Methods of List?
Besides implementing IList, the List type contains many generic helper methods. These methods are designed to automate and streamline common tasks of working with the list, such as iterating over the list and performing a task on each element, scanning the list looking for a value that matches a certain criteria (a predicate), or just searching for a particular value, converting and sorting the list, and so on. Below is a partial listing of these generic methods:
[C#]
public class List : IList,
{
//Partial listing of the generic helper methods:
public List ConvertAll(Converter converter);
public bool Exists(Predicate match);
public T Find(Predicate match);
public List FindAll(Predicate match);
public int FindIndex(Predicate match);
public T FindLast(Predicate match);
public void ForEach(Action action);
public int LastIndexOf(T item);
public void Sort(Comparison comparison);
public T[] ToArray(); //More members
}
Most of these helper generic methods works with the four generic delegates defined in the System namespace:
[C#]
public delegate void Action(T t);
public delegate int Comparison(T x, T y);
public delegate U Converter(T from);
public delegate bool Predicate(T t);
The List helper methods are used much the same way as the generic static methods of System.Array. For example, the following code initializes a list with all the numbers from 1 to 20. Then, using the Action delegate, the code traces these numbers using the List.ForEach() method. Using the Predicate delegate, the code finds all the prime numbers in the list by calling the List.FindAll() method, which returns another list of the same type. Finally, the prime numbers are traced, using the same Action delegate.
[C#]
int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
List list = new List(numbers);
Action trace = delegate(int number)
{
Trace.WriteLine(number);
};
Predicate isPrime = delegate(int number)
{
switch(number)
{
case 1:case 2:case 3:case 5:case 7:
case 11:case 13:case 17:case 19:
return true;
default:
return false;
}
};
list.ForEach(trace);
List primes = list.FindAll(isPrime);
primes.ForEach(trace);
14. What Are Nullable Types?
Unlike reference types, you cannot assign a null into a value type. This is often a problem when interacting with code that interprets a null as having no value, rather than no-reference. The canonical example is database null values in columns that have representation as types such as int or DateTime. To address that, the System namespace provides the structure Nullable defined as:
[C#]
public interface INullableValue
{
bool HasValue{get;}
object Value{get;}
}
[Serializable] public struct Nullable : INullableValue,IEquatable nullable,... where T : struct
{
public Nullable(T value);
public bool HasValue{get;}
public T Value{get;}
public T GetValueOrDefault();
public T GetValueOrDefault(T defaultValue);
public bool Equals(Nullable other);
public static implicit operator Nullable(T value);
public static explicit operator T(Nullable value);
//More members
}
Because the Nullable struct uses a generic type parameter, you can use it to wrap a value type, and assign null into it:
[C#]
Nullable number = 123;
Debug.Assert(number.HasValue);
number = null;
Debug.Assert(number.HasValue == false);
Debug.Assert(number.Equals(null));
Once a null is assigned to a nullable type, you can still access it to verify if it has a value, via the HasValue property, or just equate it to null.
In C# and Visual Basic, you can even use the underlying value type's operators on a nullable type:
[C#]
Nullable number = 0; number++;
The reason this is possible is because the compiler is capable of verifying that the underlying type supported the operator, and applying it on the value stored in the structure. This is called lifted operators.
The Nullable struct also provides conversion operators, so you can convert a nullable type to and from a real value type:
[C#]
Nullable nullableNumber = 123;
int number = (int)nullableNumber;
Debug.Assert(number == 123);
number = 456;
nullableNumber = number;
Debug.Assert(nullableNumber.Equals(456));
Note that using Nullable on Nullable is disallowed, and the compiler will issue an error:
[C#]
//This will not compile: Nullable nullable number = 123;
You can use the overloaded methods GetValueOrDefault() of Nullable to defensively obtain either the value stored in the nullable type or it its default, if it does contain a null:
[C#]
Nullable time = null;
DateTime value = time.GetValueOrDefault();
Debug.Assert(value.ToString() == "1/1/0001 12:00:00 AM");
The System namespace also defines the static helper class Nullable and the helper class NullableConverter, but those are not needed usually.
The C# 2.0 compiler supports shorthand for Nullable. You can use the ? modifier on value types to actually construct a Nullable around it:
int? number = 123;
Debug.Assert(number.HasValue);
number = null;
Debug.Assert(number.HasValue == false);
Note that the type declared by the ? modifier is identical to that created using Nullable directly:
Debug.Assert(typeof(int?) == typeof(Nullable));
As with using Nullable directly, the compiler supports lifted operators. Whenever you combine nullable types using operators, if any one of them is null, then the resulting expression will be null too:
int? number1 = 123;
int? number2 = null;
int? sum = number1 + number2;
Debug.Assert(sum == null);
Using the ? modifier is the common way of declaring and using nullable variables in C#. You can even pass nullable types as type arguments for generic types:
IList list = new List();
list.Add(3);
list.Add(null);
C# 2.0 also provides the null coalescing operator via the ?? operator.
c = a ?? b;
The result of applying the ?? operator on two operands returns the left hand side operand (a) if it is not null, and the right operand (b)otherwise. While b can of course be null too, you typically use the ?? operator to supply a default value in case a is null.
15. How Do I Reflect Generic Types?
Like most other things done with reflection, you use the class Type. Type can represent generic types with specific type arguments (called bounded types), or unspecified (unbounded) types.
[C#]
Both typeof and GetType() can operate on type parameters:
public class MyClass
{
public void SomeMethod(T t)
{
Type type = typeof(T);
Debug.Assert(type == t.GetType());
}
}
In addition the typeof operator can operate on unbound generic types (generic types that do not have yet specific type arguments). For example:
public class MyClass
{}
Type unboundedType = typeof(MyClass<>);
Trace.WriteLine(unboundedType.ToString());
//Writes: MyClass`1[T]
The number 1 being traced is the number of generic type parameters of the generic type used. Note the use of the empty <>. To operate on an unbound generic type with multiple type parameters, use a , in the <>:
public class LinkedList
{...}
Type unboundedList = typeof(LinkedList<,>);
Trace.WriteLine(unboundedList.ToString());
//Writes: LinkedList`2[K,T]
[Visual Basic]
Both GetType() and Object.GetType() can operate on type parameters:
Public Class SomeClass(Of T) Public Sub SomeMethod(ByVal t As T) Dim theType As Type = GetType(T) Debug.Assert((theType Is t.GetType)) End Sub End Class
To support generics, Type has special methods and properties designed to provide reflection information about the generic aspects of the type:
[C#]
public abstract class Type : //Base types
{
public virtual bool ContainsGenericParameters{get;}
public virtual GenericParameterAttributes GenericParameterAttributes{get;}
public virtual int GenericParameterPosition{get;}
public virtual bool IsGenericType{get;}
public virtual bool IsGenericParameter{get;}
public virtual bool IsGenericTypeDefinition{get;}
public virtual Type[] GetGenericArguments();
public virtual Type[] GetGenericParameterConstraints();
public virtual Type GetGenericTypeDefinition();
public virtual Type MakeGenericType(params Type[] typeArguments);
//Rest of the members
}
The most useful of these new members are the IsGenericType property, the GetGenericArguments() and GetGenericTypeDefinition() methods. As its name indicates, IsGenericType is set to true if the type represented by the Type object uses generic type parameters. GetGenericArguments() returns an array of types corresponding to the type arguments used. GetGenericTypeDefinition() returns a Type representing the generic form of the underlying type. The following example demonstrates using these generic-handling Type members to obtain generic reflection information on a generic linked list.
[C#]
public class LinkedList
{...}
LinkedList list = new LinkedList();
Type boundedType = list.GetType();
Trace.WriteLine(boundedType.ToString());
//Writes:
LinkedList`2[System.Int32,System.String] Debug.Assert(boundedType.IsGenericType);
Type[] parameters = boundedType.GetGenericArguments();
Debug.Assert(parameters.Length == 2);
Debug.Assert(parameters[0] == typeof(int));
Debug.Assert(parameters[1] == typeof(string));
Type unboundedType = boundedType.GetGenericTypeDefinition(); Trace.WriteLine(unboundedType.ToString());
//Writes: LinkedList`2[K,T]

Wednesday, September 19, 2007

What;s New in .Net 3.0 ?

A glance at .NET Framework 3.0Introduction:In the programming field, .NET is the most successful development platform..Net Framework 2.0 is enough to satisfy for most of us. .NET Framework 3.0 came with many new and useable features. With .NET Framework 3.0, developers feel more easy when develops. In the new version of .NET, there is nothing new with CLR (Common Language runtime) but it introduces four new technologies. Are we not apprehensive about accepting anything newer, especially if that is going to deprecate the existing one? The latest versions of .NET are .NET Framework 3.0. Programming with .NET Framework 3.0 become more advance. It is built with all the advantage of .NET framework 2.0, and is all set to bring in a paradigm shift in the way we write our applications today. When we go to develop any application then the main goal we set is, to create the Best application in least amount of time. The .NET Framework 3.0 will still ship with Windows Vista, and will be available down-level for Windows XP and Windows Server 2003 as planned.This newly released framework was earlier named as WinFx! .NET Framework 3.0 , compromise of familiar .NET Framework2.0 components (ASP.NET, ADO.NET, Window Forms etc).There are four new technologies in .NET Framework 3.0. These technologies are added to face the new challenge of software development. These new complementary technologies are added to address some of the most arduous challenges of contemporary software development.The New in .NET Framework 3.0Here .NET Framework 3.0 is same like as .NET Framework 2.0, but with some new technology and feature. The entire features are same in new framework, which was in .NET Framework 2.0.The .NET 3.0 introducing four new foundation technologies:Windows Presentation Foundation (WPF)Windows Communication Foundation (WCF)Windows Workflow Foundation (WWF)Windows Card Space (WCS)While the .NET Framework 2.0 class library is partially superseded by the new components (WF, WCF, and WPF) added in version 3.0, many portions of the original class library are still crucial to developers. The technologies of version 2.0 (ASP.NET, WinForms, ADO.NET, XML etc.) largely remain the elementary part of the new release; however, the developer of .NET Framework 3.0, mostly use WPF over windows Forms.Figure 1: NET Framework 3.0Windows Workflow Foundation (WF): Windows Workflow Foundation (WWF) is a Microsoft technology for defining, executing, and managing workflows. Workflow as it name implies. It shows the flow of work; mean how the work is going, how activities are performing. WF provides such a common workflow technology for Windows. If we have to make workflow enabled application on windows then we use Windows Workflow Foundation.System.Workflow is the namespace of Windows Workflow Foundation in Microsoft .NET Framework version 3.0. Windows Workflow Foundation provides full support for Visual Basic .NET and C#, debugging, a graphical workflow designer and the ability to develop our workflow completely in code. A workflow is a set of activities stored as a model that describe a real world process. Each Activity can be represented as a class. By using this we can reuse that activity easily. With WF, we can understand with our flow of operation. We can easily understand with our all activity.Windows Presentation Foundation (WPF): The Windows Presentation Foundation (WPF), also named Avalon, is the graphical subsystem feature of the .NET Framework 3.0. WPF is a consistent programming model for building solutions, and enables the use of richer controls, design, and development in Windows programs. In most windows application user interface play an important role .A developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. Developer's job become tough here when he go to, building a coherent user interface for different kinds of clients using diverse technologies isn't a simple job. WPF provide consistent platform for these entire user interface aspects to solve the problem. WPF support video, animation, 2/3D graphics, and various kinds of documents.Windows Communication Foundation (WCF): WCF means programmers can communicate between each other either they are on same computer or in networking .Windows Communication Foundation is a communications infrastructure built around the Web services architecture. When the application becomes built then most of the application need to communication between each other. This was a big problem in last few years, so all vendors becomes agreed to support SOAP based web services, which make interoperability between application, either they are from same platforms or different platforms. The WCF programming model unifies web services, .NET Remoting, distributed transactions, and message queues into a single service-oriented programming model for distributed computing. However, instead of requiring developers to use a different technology with a different application programming interface for each kind of communication, WCF provides a common approach and API. WCF provides strong support for interoperable communication through SOAP. Windows CardSpace (WCS):Windows CardSpace (InfoCard) is a Digital Identity to online services. Digital Identity means how user will electronically represent them. Like as a debit/credit card each card has digital identity and password. If any user go to use the site on internet then he enter their username and password, for identity, but this is not secure. To reduce these types of problems WCS works. WCS (originally called Info Card) helps people keep track of their digital identities as distinct information cards. If a Web site accepts WCS logins, users attempting to log in to that site will see a WCS selection. By choosing a card, users also choose a digital identity that will be used to access this site. CardSpace and the new supporting technologies will change how you authenticate into an application, whether it sits on the Web, your phone, or your desktop.

Monday, September 17, 2007

Remoting in .NET

Remoting in .NET
Introduction:
Distributed computing is an integral part of almost every software development. Before .Net Remoting, DCOM was the most used method of developing distributed application on Microsoft platform. Because of object oriented architecture, .NET Remoting replaces DCOM as .Net framework replaces COM.
Benefits of Distributed Application Development:
Fault Tolerance: Fault tolerance means that a system should be resilient when failures within the system occur.
Scalability: Scalability is the ability of a system to handle increased load with only an incremental change in performance.
Administration: Managing the system from one place.
In brief, .NET remoting is an architecture which enables communication between different application domains or processes using different transportation protocols, serialization formats, object lifetime schemes, and modes of object creation. Remote means any object which executes outside the application domain. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. This is called marshalling (This is the process of passing parameters from one context to another.), and there are two basic ways to marshal an object:
Marshal by value: the server creates a copy of the object passes the copy to the client.
Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.
Comparison between .NET Remoting and Web services:
For performance comparison between .Net Remoting and ASP.Net Web Services Click.
Architecture:
Remote objects are accessed thro channels. Channels are Transport protocols for passing the messages between Remote objects. A channel is an object that makes communication between a client and a remote object, across app domain boundaries. The .NET Framework implements two default channel classes, as follows:
HttpChannel: Implements a channel that uses the HTTP protocol. TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control Protocol). Channel take stream of data and creates package for a transport protocol and sends to other machine. A simple architecture of .NET remoting is as in Fig 1.
As Fig.1 shows, Remoting system creates a proxy for the server object and a reference to the proxy will be returned to the client. When client calls a method, Remoting system sends request thro the channel to the server. Then client receives the response sent by the server process thro the proxy.
Example:
Let us see a simple example which demonstrates .Net Remoting. In This example the Remoting object will send us the maximum of the two integer numbers sent.
Creating Remote Server and the Service classes on Machine 1: Please note for Remoting support your service (Remote object) should be derived from MarshalByRefObject.
using System;using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinksusing System.Runtime.Remoting;using System.Runtime.Remoting.Channels.Http; //For HTTP channelusing System.IO;namespace ServerApp{public class RemotingServer{public RemotingServer(){//// TODO: Add constructor logic here//}}//Service classpublic class Service: MarshalByRefObject {public void WriteMessage (int num1,int num2) {Console.WriteLine (Math.Max(num1,num2));}}//Server Classpublic class Server{public static void Main () {HttpChannel channel = new HttpChannel(8001); //Create a new channelChannelServices.RegisterChannel (channel); //Register channelRemotingConfiguration.RegisterWellKnownServiceType(typeof Service),"Service",WellKnownObjectMode.Singleton); Console.WriteLine ("Server ON at port number:8001");Console.WriteLine ("Please press enter to stop the server.");Console.ReadLine ();}}}
Save the above file as ServerApp.cs. Create an executable by using Visual Studio.Net command prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ServerApp.cs
A ServerApp.Exe will be generated in the Class folder.
Run the ServerApp.Exe will give below message on the console
Server ON at port number:8001
Please press enter to stop the server.
In order to check whether the HTTP channel is binded to the port, type http://localhost:8001/Service?WSDL in the browser.You should see a XML file describing the Service class.
Please note before running above URL on the browser your server (ServerApp.Exe should be running) should be ON.
Creating Proxy and the Client application on Machine 2
SoapSuds.exe is a utility which can be used for creating a proxy dll.
Type below command on Visual studio.Net command prompt.
soapsuds -url:http://<>:8001/Service?WSDL -oa:Server.dll
This will generates a proxy dll by name Server.dll. This will be used to access remote object.
Client Code:
using System;using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinksusing System.Runtime.Remoting;using System.Runtime.Remoting.Channels.Http; //For HTTP channelusing System.IO;using ServerApp;namespace RemotingApp{public class ClientApp{public ClientApp(){}public static void Main (string[] args) {HttpChannel channel = new HttpChannel (8002); //Create a new channelChannelServices.RegisterChannel (channel); //Register the channel//Create Service class objectService svc = (Service) Activator.GetObject (typeof (Service),"http://:8001/Service"); //Localhost can be replaced by //Pass Messagesvc.WriteMessage (10,20); }}}
Save the above file as ClientApp.cs. Create an executable by using Visual Studio.Net command prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ClientrApp.cs
A ClientApp.Exe will be generated in the Class folder. Run ClientApp.Exe , we can see the result on Running ServerApp.EXE command prompt.
In the same way we can implement it for TCP channel also.
---- Prabhakar Thallapalli

Multi Threading

Multithreading in .NET
Introduction
Asynchronous processing and background processing was always a must for serious programs serving complex user needs. The Windows NT platform offers a great way to accomplish this, but the implementation was sometimes tedious and always labor intensive. It is the reason why I first studied multithreading options offered by the .NET framework.
This article shows three different ways of creating (and using) threads, without communication and synchronization between them.
Before you start writing multithreaded programs, bear in mind some guidelines (from MSDN – Threading design guidelines):
Avoid providing static methods that mutate static state
Design for server environment
Instances do not need to be thread safe
Static states must be thread safe
Simple threading
Let’s first try the simplest way to create a new thread. The starting point for such a thread is void method with no parameters. Thread creation is done in two steps:
Create a delegate object, initialized with our method
Use this object as an initialization parameter when creating a new Thread object.
When our Thread object is created, call the Start method and background processing will commence.
public class MainClass{
public void threadMethod(){
...
}
public static void Main(){
...
ThreadStart entry = new ThreadStart(threadMethod ) ;
Thread thread1 = new Thread( entry ) ;
thread1.Start() ;
...
}
}
This sample hides the fact that using C# we do not have a global function, and usually you will start the thread on static class method.
public class Tester{
public static void Test(){
...
}
}
public class MainClass{
public static void Main()
...
ThreadStart entry = new ThreadStart( Tester.Test ) ;
Thread thread1 = new Thread( entry ) ;
thread1.Start() ;
...
}
}
Now we came to the first beautiful part of the .NET framework. We can start threads on class instances and create real living objects.
public class Tester{
public void Test(){
...
}
}
public class MainClass{
public static void Main()
...
Tester testObject = new Tester() ;
ThreadStart entry = new ThreadStart( testObject.Test ) ;
Thread thread1 = new Thread( entry ) ;
thread1.Start() ;
...
}
}
Timer threads
A common use of threads is for all kinds of periodical updates. Under Win32 we have two different ways: window timers and time limited waiting for events. .NET offers three different ways:
Windows timers with the System.WinForms.Timer class
Periodical delegate calling with System.Threading.Timer class (works on W2K only)
Exact timing with the System.Timers.Timer class
For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking. Be careful with stopping, because stopped timers are disabled and are subject to garbage collection. That means that stopped timers can not be started again.
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. Currently it works on Windows 2000 only. Documentation for this class is not finished yet (beta 1). To use it you must perform several steps:
Create state object which will carry information to the delegate
Create TimerCallback delegate with a method to be called. You can use static or instance methods.
Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don’t work that way)
Change the Timer object settings with the Change method (same remark on parameters apply)
Kill the Timer object with the Dispose method
If we put this in code we get:
Collapse
using System;
using System.Threading;

// class for storing current state
public class StateObj{
...
}

// class that will work on timer request
public class TimerClass{
public void TimerKick( object state ){
StateObj param = (StateObj)state ;
// do some work with param
}
}

// usage block
{
...
// prepare state object
StateObj state = new StateObj() ;
// prepare testing object – not necessary when cb is static
TimerClass testObj = new TimerClass() ;
// prepare callback delegate – careful on static methods
TimerCallback tcb = new TimerCallback( obj.TimerKick ) ;
// make timer
long waitTime = 2000 ; // wait before first tick in ms
long periodTime = 500 ; // timer period
Timer kicker = new Timer( tcb, state, waitTime, periodTime ) ;
// do some work
...
kicker.Change( waitTime, periodTime ) ;
// do some more work
...
kicker.Dispose() ;
...
}
For waitTime and periodTime you can use TimeSpan types if it makes more sense. In the supplied sample you can see that the same state object is used on both timers. When you run the sample the state values printed are not consecutive. I left it like this to show how important synchronization is in a multithread environment.
The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the sameSystem.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.
System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.
Create the Timer object. You can a use constructor with interval setting.
Add your event handler (delegate) to the Tick event
Set the Interval property to the desired number of milliseconds (default value is 100 ms)
Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)
Start the ticking with a call to the Start() method, or by setting Enabled property to true.
Stop the ticking with call to the Stop() method or by setting the Enabled property to false.
using System.Timers ;

void TickHandler( object sender, EventArgs e ){
// do some work
}

// usage block
{
...
// create timer
Timer kicker = new Timer() ;
kicker.Interval = 1000 ;
kicker.AutoReset = false ;

// add handler
kicker.Tick += new EventHandler( TickHandler ) ;

// start timer
kicker.Start() ;

// change interval
kicker.Interval = 2000 ;

// stop timer
kicker.Stop() ;

// you can start and stop timer againg
kicker.Start() ;
kicker.Stop() ;
...
}
I should mention a few things about using the Timers.Timer class:
In VS Beta 1 you must add a reference to System.Timers namespace by hand.
Whenever you use the Timers namespace together with System.WinForms or System.Threading, you should reference the Timer classes with the full name to avoid ambiguity.
Be careful when using Timers.Timer objects. You may find them a lot faster than the old windows timers approach (think why). Do not forget synchronize data access.

Thread pooling
The idea for making a pool of threads on the .NET framework level comes from the fact that most threads in multithreaded programs spend most of the time waiting for something to happen. It means that thread entry functions contain endless loops which calls real working functions. By using the ThreadPool type object preparing working functions is simpler and for bonus we get better resource usage.
There are two important facts relating to ThreadPool object.
There is only one ThreadPool type object per process
There is only one working thread per thread pool object
The most useful use of a ThreadPool object is to add a new thread with a triggering event to the thread pool. i.e.. "when this event happens do this". For using ThreadPool this way you must perform following steps:
Create event
Create a delegate of type WaitOrTimerCallback
Create an object which will carry status information to the delegate.
Add all to thread pool
Set event
In C#:
// status information object
public class StatusObject{
// some information
}

// thread entry function
public void someFunc( object obj, bool signaled ){
// do some clever work
}

// usage block
{
...
// create needed objects
AutoResetEvent myEvent = new AutoResetEvent( false ) ;
WaitOrTimerCallback myThreadMethod = new WairOrTimerCallback( someFunc ) ;
StatusObject statusObject = new StatusObject() ;

// decide how thread will perform
int timeout = 10000 ; // timeout in ms
bool repetable = true ; // timer will be reset after event fired or timeout

// add to thread pool
ThreadPool.RegisterWaitForSingleObject( myEvent, myThreadMethod,
statusObject, timeout, repetable ) ;
...
// raise event and start thread
myEvent.Set() ;
...
}
A less common use of a thread pool will be (or at least should be, be aware of misuse) adding threads to be executed when the processor is free. You could think of this kind of usage as "OK, I have this to do, so do it whenever you have time". Very democratic way of handling background processing which can stop your program quickly. Remember that inside the thread pool you have only one thread working (per processor).
Using thread pool this way is even simpler:
Create a delegate of type WaitCallback
Create an object for status information, if you need it
Add to thread pool
// status information object
public class StatusObject{
// some information
}

// thread entry function
public void someFunc( object obj, bool signaled ){
// do some clever work
}

// usage block
{
...
// create needed objects
WaitCallback myThreadMethod = new WairOrTimerCallback( someFunc ) ;
StatusObject statusObject = new StatusObject() ;

// add to thread pool
ThreadPool.QueueUserWorkItem( myThreadMethod, statusObject ) ;
...
}
Some notes on thread pool:
Don’t use a thread pool for threads that perform long calculations. You only have one thread per processor actually working.
System.Thread.Timer type objects are one thread inside thread pool
You have only one thread pool per process
Conclusion
This article shows the way I used to find out secrets of .NET multithreading. When you try using this, be careful on thread synchronization. This is also subject of my next article, where I will show all different ways of synchronization that .NET offers.
For more information read articles in MSDN library:
.NET framework design guidelines
Threading design guidelines
Asynchronous execution
--------- Prabhakar Thallapalli

Generics in .Net 2.0

Generics
Generics are simply placeholders for actual types. Generics are defined with left and right brackets: In other words Generics allow you to define type-safe data structures, without committing to actual data types. .Net 2.0 provides number of generic collection classes for lists, stacks, queues, dictionaries.Generics Benefits:
Generics in .NET let you reuse code and the effort you put into implementing it. The types and internal data can change without causing code bloat, regardless of whether you are using value or reference types. You can develop, test, and deploy your code once, reuse it with any type, including future types, all with full compiler support and type safety. Because the generic code does not force the boxing and unboxing of value types, or the down casting of reference types, performance is greatly improved. With value types there is typically a 200 percent performance gain, and with reference types you can expect up to a 100 percent performance gain in accessing the type (of course, the application as a whole may or may not experience any performance improvements). The source code available with this article includes a micro-benchmark application, which executes a stack in a tight loop. The application lets you experiment with value and reference types on an Object-based stack and a generic stack, as well as changing the number of loop iterations to see the effect generics have on performance.
Let us create console application to have actual understanding.

In visual studio 2005 create new project >>Console Application Name it as "GenericsLists".

We will add class called as "Customer" to this console application as below:

public class Customer
{
private int custId;
public Customer(int Id)
{
this.custId = Id;
}
public override string ToString()
{
return custId.ToString();
}
}

With any of the console application we will have something called as "Program.cs"
Which will be some thing like this:

public class Program
{
static void Main()
{
//Type safe list (of Customer objects)
List custList = new List();
//Type safe list (of integers)
List intList = new List();
//Populate the Lists
for (int i = 0; i < 5; i++)
{
custList.Add(new Customer(i + 100));
intList.Add(i * 5);
}
//Integer list
foreach (int i in intList)
{
Console.Write("{0} ", i.ToString());
}
Console.WriteLine("\n");
//Print the Customer List
foreach (Customer Customer in custList)
{
Console.Write("{0} ", Customer.ToString());
}
Console.WriteLine("\n");
}
}

The Customer class contains a single private field (custId), a constructor, and an override of ToString to return the custId field as a string.

First you create an instance of List that will hold Customer objects. The type of custList is "List of customer Objects" and is declared as:

List custList = new List();

The definition List, the T is a placeholder for the actual type you'll place in that list.

if you try to add an integer to the list of Customer ie. custList.Add (i * 5);
In this case you will get two erros as:

The best overloaded method match for 'System.Collections.Generic.List.Add(ListCollection.Customer)' has some invalid arguments.

Argument '1': cannot convert from 'int' to 'ListCollection.Customer'.

Here it is not possible to implicit conversion of int to collection of Customer object or subtype one type implicit conversion to another type is not legal.

You can store types in a type sage collection. Thus collection of customer will hold "Sales" object if Sales derived from Customer.
Prabhakar Thallapalli.