Sunday, June 24, 2012

 

This tutorial—Interface-Based Programming—is from Programming .NET Components, by Juval Lowy. Copyright © 2005 O'Reilly Media, Inc. All rights reserved. Read the book review!

While going through the web, I came to know about this article. It found to be best article I ever seen which explains about Interface in very easy language. I appreciate the author for explaining most complex concept in .Net with very easy language.  This article compelled me to purchase this book.

Interface-Based Programming

Separation of interface from implementation is a core principle of component-oriented programming. When you separate interface from implementation, the client is coded against an abstraction of a service (the interface), not a particular implementation of it (the object). As a result, changing an implementation detail on the server side (or even switching to a different service provider altogether) doesn’t affect the client. This chapter starts by presenting .NET interfaces and describing what options are available to .NET developers when it comes to enforcing the separation of interface from implementation. It then addresses a set of practical issues involving the definition and use of interfaces, such as how to implement multiple interfaces and how to combine interfaces and class hierarchies. After a detailed look at generic interfaces, the chapter ends with a discussion of interface design and factoring guidelines.

Separating Interface from Implementation

In both C# and Visual Basic 2005, the reserved word interface defines a CLR reference type that can’t have any implementation, can’t be instantiated, and has only public members. Saying that an interface can’t have implementation means that it’s as if all the interface’s methods and properties were abstract. Saying it can’t be instantiated means the same as if the interface were an abstract class (or MustInherit in Visual Basic 2005). For example, this interface definition:
public interface IMyInterface
{
   void Method1( );
   void Method2( );
   void Method3( );
}
is almost equivalent to this class definition:
public abstract class MyInterface
{
   public abstract void Method1( );
   public abstract void Method2( );
   public abstract void Method3( );
}
In traditional object-oriented programming, you typically use an abstract class to define a service abstraction. The abstract class serves to define a set of signatures that multiple classes will implement after deriving from the abstract class. When different service providers share a common base class, they all become polymorphic with that service abstraction, and the client can potentially switch between providers with minimum changes. There are a few important differences between an abstract class and an interface:
  • An abstract class can still have implementation: it can have member variables or non-abstract methods or properties. An interface can’t have implementation or member variables.
  • A .NET class can derive from only one base class, even if that base class is abstract. However, a .NET class can implement as many interfaces as required.
  • An abstract class can derive from any other class or from one or more interfaces. An interface can derive only from other interfaces.
  • An abstract class can have nonpublic (protected or private) methods and properties, even if they are all abstract. In an interface, by definition, all members are public.
  • An abstract class can have static methods and static members and can define constants. An interface can have none of those.
  • An abstract class can have constructors. An interface can’t.
These differences are deliberately in place, not to restrict interfaces, but rather to provide for a formal public contract between a service provider (the classes implementing the interface) and the service consumer (the client of the classes). Disallowing any kind of implementation details in interfaces (such as method implementations, constants, static members, and constructors) enables .NET to promote loose coupling between the service providers and the client. Because there is nothing in the contract that even hints at implementation, by definition the implementation is well encapsulated behind the interface, and service providers are free to change their implementations without affecting the client. You can even say that the interface acts like a binary shield, isolating each party from the other.
Because interfaces can’t be instantiated, .NET forces clients to choose a particular implementation to instantiate. Having only public members in an interface complements the contract semantics nicely: you would not want a contract with hidden clauses or "fine print." Everything the contract implies should be public and well defined. The more explicit and well defined a contract is, the less likely it is that there will be conflicts down the road regarding exactly what the class providing the service is required to do. The class implementing the interface must implement all the interface members without exception, because it has committed to providing this exact service definition. An interface can extend only other interfaces, not classes. By deriving a new interface from an existing interface, you define a new and specialized contract, and any class that implements that interface must implement all members of the base interface(s). A class can choose to implement multiple interfaces, just as a person can choose to commit to multiple contracts.

Interface Implementation

To implement an interface, all a class has to do is derive from it. Example 3-1 shows the class MyClass implementing the interface IMyInterface.
Example 3-1. Defining and implementing an interface
public interface IMyInterface
{
   void Method1( );
   void Method2( );
   void Method3( );
}
 
public class MyClass : IMyInterface
{
   public void Method1( )
   {...}
   public void Method2( )
   {...}
   public void Method3( )
   {...}
   //other class members
}
As trivial as Example 3-1 is, it does demonstrate a number of important points. First, interfaces have visibility—an interface can be private to its assembly (using the internal access modifier) or it can be used from outside the assembly (with the public access modifier), as in Example 3-1. Second, even though the methods the interface defines have no access modifiers, they are by definition public, and the implementing class has to declare its interface methods as public. Third, there is no need to use new or override to qualify the method redefinition in the subclass, because an interface method by its very nature can’t have any implementation and therefore has nothing to override. (If you aren’t familiar with the new or override keywords, see the sidebar "C# Inheritance Directives" later in this chapter.) Finally, the class must implement all the methods the interface defines, without exception. If the class is an abstract class, it can redefine the methods without providing concrete implementation.
Example 3-2 shows how to define and implement an interface in Visual Basic 2005. In Visual Basic 2005, you need to state which interface method a class method corresponds to. As long as the signature (i.e., the parameters and return value) matches, you can even use a different name for the method. In addition, because the default accessibility in Visual Basic 2005 is public, unlike in C#, adding the Public qualifier is optional.
Example 3-2. Defining and implementing an interface in Visual Basic 2005
Public Interface IMyInterface
   Sub Method1( )
   Sub Method2( )
   Sub Method3( )
End Interface
 
Public Class SomeClass
   Implements IMyInterface
   Public Sub Method1( ) Implements IMyInterface.Method1
   ...
   End Sub
 
   Public Sub Method2( ) Implements IMyInterface.Method2
   ...
   End Sub
 
   Public Sub Method3( ) Implements IMyInterface.Method3
   ...
   End Sub
End Class
To interact with an object using an interface, all a client has to do is instantiate a concrete class that supports the interface and assign that object to an interface variable, similar to using any other base type. Using the same definitions as in Example 3-1, the client code might be:

IMyInterface obj;
obj = new MyClass( );
obj.Method1( );
 
Interfaces promote loose coupling between clients and objects. When you use interfaces, there’s a level of indirection between the client’s code and the object implementing the interface. If the client wasn’t responsible for instantiating the object, there is nothing in the client code that pertains to the object hidden behind the interface shield. There can be many possible implementations of the same interface, such as:

public interface IMyInterface
{...}
public class MyClass : IMyInterface
{...}
public class MyOtherClass : IMyInterface
{...}
 
When a client obtains an interface reference by creating an object of type MyClass, the client is actually saying to .NET "give me MyClass’s interpretation of the way IMyInterface should be implemented."
Treating interfaces as binary contracts, which shields clients from changes made to the service providers, is exactly the idea behind COM interfaces, and logically, .NET interfaces have the same semantics as COM interfaces. If you are an experienced COM developer or architect, working with interfaces is probably second nature to you, and you will feel right at home with .NET interfaces.
However, unlike COM, .NET doesn’t enforce separation of the interface from the implementation. For example, using the definitions in Example 3-1, the client’s code can also be:
MyClass obj;
obj = new MyClass( );
obj.Method1( );
Because of the way the server in Example 3-1 implements the interface (as public members), nothing prevents the client from programming directly against the object providing the service, instead of the interface. I believe this is because .NET tries to make component-oriented programming accessible to all developers, including those who have trouble with the more abstract concepts of interface-based programming (see the section “.NET Adherence to Component Principles” in Chapter 1). The fact that something is possible, of course, doesn’t mean you should go ahead and do it. Disciplined .NET developers should always enforce the separation, to retain the benefits of interface-based programming.

Explicit Interface Implementation

The way of implementing an interface shown in the previous section is called implicit interface implementation, because a public method with a name and signature that match those of an interface method is implicitly assumed to be an implementation of that interface method.
Example 3-3 demonstrates a simple technique that allows server developers to enforce the separation of the interface from the implementation. The server implementing the interface can actually prevent clients from accessing the interface methods directly by using explicit interface implementation. Implementing an interface explicitly means qualifying each interface member name with the name of the interface that defines it.
Example 3-3. Explicitly implementing an interface
public interface IMyInterface
{
   void Method1( );
   void Method2( );
}
 
public class MyClass : IMyInterface
{
   void IMyInterface.Method1( )
   {...}
   void IMyInterface.Method2( )
   {...}
   //Other methods and members
}
Note that the interface members must be implicitly defined as private at the class’s scope; you can’t use any explicit access modifiers on them, including private. The only way clients can invoke the methods of explicitly implemented interfaces is by accessing them via the interface:
IMyInterface obj;
obj = new MyClass( );
obj.Method1( );
To explicitly implement an interface in Visual Basic 2005, you need to explicitly set the method access to Private, as in Example 3-4.
Example 3-4. Explicitly implementing an interface in Visual Basic 2005
Public Interface IMyInterface
   Sub Method1( )
   Sub Method2( )
End Interface
 
Public Class SomeClass
   Implements IMyInterface
   Private Sub Method1( ) Implements IMyInterface.Method1
   ...
   End Sub
   
   Private Sub Method2( ) Implements IMyInterface.Method2
   ...
   End Sub
End Class
You should avoid mixing and matching explicit and implicit interface implementations, as in the following fragment:
//Avoid mixing and matching:
public interface IMyInterface
{
   void Method1( );
   void Method2( );
}
 
public class MyClass : IMyInterface
{
   void IMyInterface.Method1( )
   {...}
   public void Method2( )
   {...}
   //Other methods and members
}
Although .NET lets you mix and match implementation methods, for consistency, you should avoid it. Such mix and match forces the client to adjust its references depending on whether a particular method is accessible via an interface or directly via the object.
Assemblies with Interfaces Only
Because interfaces can be implemented by multiple components, it’s good practice to put them in a separate assembly from that of the implementing components. Maintaining a separate assembly that contains only interfaces allows concurrent development of the server and the client, once the two parties have agreed on the interfaces. Such assemblies also extend the separation of interface from implementation to the codepackaging units.

Working with Interfaces

Now that you have learned the importance of using interfaces in your componentbased application, it’s time to examine a number of practical issues regarding working with interfaces and tying them to the rest of your application. Later in this chapter, you will also see the support Visual Studio 2005 offers component developers when it comes to adding implementation to your classes for predefined interfaces.
When you name a new interface type, you should prefix it with a capital I and capitalize the first letter of the domain term, as in IAccount, IController, ICalculator, and so on. Use the I prefix even if the domain term itself starts with an I (such as in IIDentity or IImage). .NET tries to do away with the old Windows and C++ Hungarian naming notations (that is, prefixing a variable name with its type), but the I prefix is a direct legacy from COM, and that tradition is maintained in .NET.


Interfaces and Type Safety

Interfaces are abstract types and, as such, can’t be used directly. To use an interface, you need to cast into an interface reference an object that supports it. There are two types of casting—implicit and explicit—and which type you use has an impact on type safety.
Assigning a class instance to an interface variable directly is called an implicit cast, because the compiler is required to figure out which type to cast the class to:
IMyInterface obj;
obj = new MyClass( );
obj.Method1( );
When you use implicit casts, the compiler enforces type safety. If the class MyClass doesn’t implement the IMyInterface interface, the compiler refuses to generate the code and produces a compilation error. The compiler can do that because it can read the class’s metadata and can tell in advance that the class doesn’t derive from the interface. However, there are a number of cases where you cannot use implicit casting. In such cases, you can use explicit cast instead. Explicit casting means casting one type to another type:
IMyInterface obj;
/* Some code here */
obj = (IMyInterface)new MyClass( );
obj.Method1( );
However, bear in mind that explicit casts to an interface are made at the expense of type safety. Even if the class doesn’t support the interface, the compiler will compile the client’s code, and .NET will throw an exception at runtime when the cast fails.
An example where implicit cast is unavailable is when dealing with non-generic class factories. In object-oriented programming, clients often don’t create objects directly, but rather get their instances from a class factory—a known object in the system that clients ask to create objects they require, instead of creating them directly.* The advantage of using a class factory is that only the factory is coupled to the actual component types that provide the interfaces. The clients only know about the interfaces. When you need to switch from one service provider to another you only need to modify the factory (actually, instantiate a different type of a factory); the clients aren’t affected. When using a class factory that returns some common base type (usually object), you can use an explicit cast from the returned object to the interface type:
public interface IClassFactory
{
   object GetObject( );
}
IClassFactory factory;
/* Some code to initialize the class factory */
IMyInterface obj;
obj = (IMyInterface)factory.GetObject( );
obj.Method1( );

When using generics (where the type parameter is defined at the factory or the method level), there is no need for the cast:
public interface IClassFactory<T>
{
   T GetObject( );
}
IClassFactory<IMyInterface> factory;
/* Some code to initialize the class factory */
IMyInterface obj;
obj = factory.GetObject( );
obj.Method1( );
 
Generic interfaces are discussed in more detail later in this chapter.
Another example where implicit cast is impossible is when you want to use one interface that the class implements to get a reference to another interface that the class also supports. Consider the code in Example 3-5. Even when the client uses an implicit cast to get hold of the first interface, it needs an explicit cast to obtain the second.
Example 3-5. Defining and using multiple interfaces
public interface IMyInterface
{
   void Method1( );
   void Method2( );
}
 
public interface IMyOtherInterface
{
   void Method3( );
}
 
public class MyClass : IMyInterface,IMyOtherInterface
{
   public void Method1( )
   {...}
   public void Method2( )
   {...}
   public void Method3( )
   {...}
}
 
//Client-side code:
IMyInterface obj1;
IMyOtherInterface obj2;
 
obj1 = new MyClass( );
obj1.Method1( );
 
obj2 = (IMyOtherInterface)obj1;
obj2.Method3( );
In all these examples that use explicit casts, you must incorporate error handling, in case the type you are trying to cast from doesn’t support the interface, and use try and catch statements to handle any exceptions.
There is, however, a safer, defensive approach to explicit casting-the as operator. The as operator performs the cast if it’s legal and assigns a value to the variable. If a cast isn’t possible, instead of throwing an exception, the as operator assigns null to the interface variable. Example 3-6 shows how to use the as operator to perform a safe cast that doesn’t result in an exception in case of an error.
Example 3-6. Using the as operator to cast safely to the desired interface
SomeType obj1;
IMyInterface obj2;
 
/* Some code to initialize obj1 */
 
obj2 = obj1 as IMyInterface;
if(obj2 != null)
{
   obj.Method1( );
}
else
{
   //Handle error in expected interface
}
Interestingly enough, using the as operator to find out whether a particular object supports a given interface is semantically identical to COM’s QueryInterface( ) method. Both mechanisms allow clients to defensively obtain an interface from an object and handle the situation where the interface isn’t supported.
In general, you should always program defensively on the client side, using the as operator as shown in Example 3-6, instead of explicit casting. Never assume an object supports an interface—that leads both to robust error handling and to separation of the interface from the implementation, regardless of whether or not the server is using explicit interface implementation. Make it a habit on the client side to use the server via an interface and thus enforce the separation manually.

Interface Methods, Properties, and Events

An interface isn’t limited only to defining methods. An interface can also define properties, indexers, and events. Example 3-7 shows the syntax for defining all of these in an interface and the corresponding implementation.
Example 3-7. An interface can define methods, properties, indexers, and events
public delegate void NumberChangedEventHandler(int number);
public interface IMyInterface
{
   void Method1( ); //A method
   int SomeProperty{ get; set; }//A property
   int this[int index]{ get; set;}//An indexer
   event NumberChangedEventHandler NumberChanged;//An event
}
 
public class MyClass : IMyInterface
{
   public event NumberChangedEventHandler NumberChanged;
   public void Method1( )
   {...}
   public int SomeProperty
   {
      get
      {...}
      set
      {...}
   }
   
   public int this[int index]
   {
      get
      {...}
      set
      {...}
   }
}

Interfaces and Structs

An interesting use of interfaces with properties involves structs. In .NET, a struct (a Structure in Visual Basic 2005) can’t have a base struct or a base class, because it’s a value type. However, .NET does permit structs to implement one or more interfaces. The reason for this is that sometimes you want to define abstract data storage, and there are a number of possible implementations for the actual structure. By defining an interface (preferably with properties only, but it can have methods as well), you can pass around the interface instead of the actual struct and gain the benefits of polymorphism, even though structs aren’t allowed to derive from a common base struct. Example 3-8 demonstrates the use of an interface (with properties only) as a base type for structs.
Example 3-8. Using an interface as a base type for structs
public interface IMyBaseStruct
{
   int SomeNumber{ get; set; }
   string SomeString{ get; set; }
}
 
struct MyStruct : IMyBaseStruct
{
   public int SomeNumber
   { get{...} set{...} }
 
   public string SomeString
   { get{...} set{...} }
   //Rest of the implementation
}
 
struct MyOtherStruct : IMyBaseStruct
{
   public int SomeNumber
   { get{...} set{...} }
 
   public string SomeString
   { get{...} set{...} }
   //Rest of the implementation
}
 
//A method that accepts a struct, without knowing exactly the type
public void DoWork(IMyBaseStruct storage)
{...}
 

Interfaces and Partial Types

Partial types allow the component architect to define interface derivation for a class but have another developer implement it (similar to the old C++ distinction between header files and CPP files):
//In App.cs
public interface IMyInterface
{
   void Method1( );
   void Method2( );
}
 
public partial class MyClass : IMyInterface
{}
 
//In MyClass.cs
public partial class MyClass
{
   public void Method1( )
   {...}
 
   public void Method2( )
   {...}
} 


With a partial class, each part of the class can choose to add interface derivation, or interface derivation and implementation:

public partial class MyClass
{}
 
public partial class MyClass : IMyInterface
{
   public void Method1( )
   {...}
   
   public void Method2( )
   {...}
}
 
However, only a single part can implement an interface member. 

Implementing Multiple Interfaces

A class can derive from as many interfaces as required (see Example 3-5), but from at most one base class. When a class derives from a base class and from one or more interfaces, the base class must be listed first in the derivation chain (a requirement the compiler enforces):

public interface IMyInterface
{}
public interface IMyOtherInterface
{}
public class MyBaseClass
{}
public class MySubClass : 
   MyBaseClass,IMyInterface,IMyOtherInterface
{}

Even such a trivial example raises a number of questions. What if both interfaces define identical methods? What are the available ways to resolve such collisions? What if the base class already derives from one or more of the interfaces?
When a class derives from two or more interfaces that define an identical method, you have two options: the first is to channel both interface methods to the same actual method implementation, and the second is to provide separate method implementations. For example, consider two interfaces that define the identical method Method1( ):

public interface IMyInterface
{
   void Method1( );
}
 
public interface IMyOtherInterface
{
   void Method1( );
}
 
If you want to channel both interface methods to the same method implementation, all you have to do is derive from the interfaces and implement the method once:

 
public class MyClass : IMyInterface,IMyOtherInterface
{
   public void Method1( )
   {...}
   //Other methods and members
}
 
Regardless of which interface the client of MyClass chooses to use, calls to Method1( ) will be channeled to that single implementation: 
 
IMyInterface obj1;
IMyOtherInterface obj2;
 
obj1 = new MyClass( );
obj1.Method1( );
 
obj2 = obj1 as IMyOtherInterface;
Debug.Assert(obj2 != null);
obj2.Method1( );
 
To provide separate implementations, use explicit interface implementation by qualifying
the method implementation with the name of the interface that defines it: 
 
public class MyClass : IMyInterface,IMyOtherInterface
{
   void IMyInterface.Method1( )
   {...}
   void IMyOtherInterface.Method1( )
   {...}
   //Other methods and members
}
 
Now, when the client calls an interface method, that interface-specific method is called. You can even have separate explicit implementations for some of the common methods and channel the others to the same implementation. However, as mentioned before, for the sake of consistency it’s better to avoid mixing and matching.
If you want to both use explicit interface implementation and channel the implementation from one interface to the other, you will need to use the this reference to query for the desired interface and delegate the call:

public class MyClass : IMyInterface, IMOtherInterface
{
   void IMyInterface.Method1 ( )
   {...}
   void IMyOtherInterface.Method1 ( )
   {
      IMyInterface myInterface = this;
      myInterface.Method ( );
   }
   //Other methods and members
}
 

Using the this reference this way is the only way to call an explicit interface method by its own implementing class.
 

Interfaces and Class Hierarchies

In component-oriented programming, you focus on defining and implementing interfaces. In object-oriented programming, you model your solution by using class hierarchies. How do the two concepts interact? The answer depends on the way you override or redefine the interface methods at the different levels of the class hierarchy. Consider the code in Example 3-9, which illustrates that when defining an interface only at the root of a class hierarchy, each level must override its base-class declarations to preserve semantics.
Example 3-9. Overriding an interface in a class hierarchy

using System.Diagnostics;//For the Trace class
public interface ITrace
{
   void TraceSelf( );
}
 
public class A : ITrace
{
   public virtual void TraceSelf( )
   {
      Trace.WriteLine("A");
   }
}
 
public class B : A
{
   public override void TraceSelf( )
   {
      Trace.WriteLine("B");
   }
}
 
public class C : B
{
   public override void TraceSelf( )
   {
      Trace.WriteLine("C");
   }
}


In a typical class hierarchy, the topmost base class should derive from the interface, providing polymorphism with the interface to all subclasses. The topmost base class must also define all the interface members as virtual, so that subclasses can override them. Each level of the class hierarchy can override its preceding level (using the override inheritance qualifier), as shown in Example 3-9. When the client uses the interface, it then gets the desired interpretation of the interface. For example, if the client code is:

ITrace obj = new B( );
obj.TraceSelf( );

the object traces "B" to the output window, as expected.
{} |- | In C#, you are required to explicitly indicate the semantics of inheritance when you supply a method with a name and signature identical to those of a base-class method. If you wish to override the base-class method when instantiating a base-class type with a subclass reference, you need to use the override directive:


public class BaseClass
{
   public virtual void TraceSelf( )
   {
      Trace.WriteLine("BaseClass");
   }
}
 
public class SubClass : BaseClass
{
   public override void TraceSelf( )
   {
      Trace.WriteLine("SubClass");
   }
}
 
BaseClass obj = new SubClass( );
obj.TraceSelf( ); //Outputs "SubClass" 



If you want to provide the base-class behavior instead, use the new directive, with or without virtual, at the base class:


public class BaseClass
{
   public virtual void TraceSelf( )
   {
      Trace.WriteLine("BaseClass");
   }
}
 
public class SubClass : BaseClass
{
   public new void TraceSelf( )
   {
      Trace.WriteLine("SubClass");
   }
}
 
BaseClass obj = new SubClass( );
obj.TraceSelf( ); //Outputs "BaseClass" 

Things are less obvious if the subclasses use the new inheritance qualifier. The new modifier gives subclass behavior only when dealing with an explicit reference to a subclass, such as:
 
B obj = new B( ); 

In all other cases, the base class implementation is used. If the code in Example 3-9 was written as:


public class A : ITrace
{
   public virtual void TraceSelf( )//virtual is optional
   {
      Trace.WriteLine("A");
   }
}
 
public class B : A
{
   public new void TraceSelf( )
   {
      Trace.WriteLine("B");
   }
}
 
public class C : B
{
   public new void TraceSelf( )
   {
      Trace.WriteLine("C");
   }
}
 
then this client code:


ITrace obj = new B( );
obj.TraceSelf( );
 
would now trace "A" to the output window instead of "B." Note that this is exactly why the new inheritance modifier is available. Imagine a client that somehow depends on the base class’s particular implementation. If a new subclass is used instead of the base class, the new modifier ensures that the client will get the implementation it expects. However, this nuance makes sense only when you’re dealing with clients that don’t use interface-based programming but rather program directly against the objects:

A obj = new B( );
obj.TraceSelf( );   //Traces "A" 
 
You can support such clients and still provide interface-based services to the rest of the clients. To achieve that, each class in the hierarchy can reiterate its polymorphism with the interface by explicitly deriving from the interface (in addition to having the base class derive from the interface). Doing so (as shown in Example 3-10) makes the new modifier yield the same results as the override modifier for the interface-based clients:
 
ITrace obj = new B( );
obj.TraceSelf( );   //Traces "B" 

Note that using virtual at the base-class level is optional.
In general, you should use the override modifier, as in Example 3-9, with virtual interface members at the topmost base class. Such code is readable and straightforward. Code such as that in Example 3-10 makes for an interesting exercise but is rarely of practical use.
Example 3-10. Deriving from the interface explicitly at each level of the class hierarchy

using System.Diagnostics;//For the Trace class
public interface ITrace
{
   void TraceSelf( );
}
 
public class A : ITrace
{
   public virtual void TraceSelf( )//virtual is optional
   {
      Trace.WriteLine("A");
   }
}
 
public class B : A,ITrace
{
   public new void TraceSelf( )
   {
      Trace.WriteLine("B");
   }
}
 
public class C : B,ITrace
{
   public new void TraceSelf( )
   {
      Trace.WriteLine("C");
   }
}
 
If you want to combine explicit interface implementation and class hierarchy, you should do so in a way that allows a subclass to call its base-class implementation. Because with explicit interface implementation, the implementation is private, you will need to add at the topmost base class a protected virtual method for each interface method. Only the topmost base class should explicitly implement the interface, and its implementation should call the protected virtual methods. All the subclasses should override the protected virtual methods:

public class A : ITrace
{
   protected virtual void TraceSelf( )
   {
      Trace.WriteLine("A");
   }
   void ITrace.TraceSelf( )
   {
      TraceSelf( );
   }
}
 
public class B : A
{
   protected override void TraceSelf( )
   {
      Trace.WriteLine("B");
      base.TraceSelf( );
   }
}

Sunday, September 24, 2006

How to Edit Boot.ini File in Dual or multi booting System

This step-by-step article describes how to edit the Boot.ini file in a Windows 2000 environment. NTLDR displays the bootstrap loader screen, where you can select an operating system to start. This screen is based upon the information in the Boot.ini file. If you do not select an entry before the counter reaches zero, NTLDR loads the operating system that is specified by the default parameter in the Boot.ini file. Windows 2000 Setup places the Boot.ini file in the active partition. NTLDR uses information in the Boot.ini file to display the bootstrap loader screen from which you select the operating system.You should back up the Boot.ini file before you edit it. The first tasks include modifying your folder options so you can view hidden files, and then backing up the Boot.ini file.

Modifying Folder Options

1. Right-click Start, and then click Explore.
2. On the Tools menu, click Folder Options, and then click View.
3. In the Advanced Settings area, click to select the Show hidden files and folders check box, click to clear the Hide protected operation system files (Recommended) check box, click OK, and then click OK.
4. In the left pane, click to select the %systemroot%, right-click Boot.ini in the display pane, and then click Properties.
5. Click to clear the Read-only attribute check box, and then click OK.


Save a Backup Copy of Boot.ini
1. Right-click Start, and then click Explore.
2. In the left pane, click the %systemroot% drive, in the right pane, click the Boot.ini file, and then click Copy.
3. Open a temporary folder in the left pane, right-click in the right display pane, and then click Paste to create a copy of the Boot.ini file in that folder.

Sample Boot.ini File

This is a sample of a default Boot.ini file from a Windows 2000 Server-based computer: [boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(1)\WINNT
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINNT="Windows 2000 Server" /fastdetect
This is a sample of the preceding Boot.ini file after the addition of another partition that is running Windows XP Professional. [boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(1)\WINNT
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINNT="Windows 2000 Server" /fastdetect
multi(0)disk(1)rdisk(0)partition(2)\WINNT="Windows XP Professional" /fastdetect


Editing the Boot.ini File

1. Click Start, point to Programs, point to Accessories, and then click Notepad.
2. In Notepad, click Open on the File menu.
3. Click the %systemroot% drive in the Look in box, click the Boot.ini file, and then click Open.
Removing an Operating System from the Menu

1. In Notepad, select the line that contains information about the operating system you want to remove, and then press DELETE. Example of the line to select:
multi(0)disk(1)rdisk(0)partition(2)\Windows="Windows 98" /fastdetect
2. On the File menu, click Save.
Modifying the Operating System Menu Order

1. In Notepad, select the line that needs to be moved, press CTRL+C, press DELETE, click to place the cursor to where the line needs to be placed, and then press CTRL+V.
2. Repeat step 1 as needed for your configuration, and then click Save on the File menu.
Modifying the Default Operating System

The default represents the operating system that will be loaded if no selection is made before the time out occurs.
1. In Notepad modify the following line to reflect the operating system which is to be the default:
default=multi(0)disk(0)rdisk(0)partition(1)\WINNT For example, changing the default from Windows 2000 Server to Microsoft Windows 95
default=multi(0)disk(0)rdisk(0)partition(1)\WINNT would be modified to:
default=multi(0)disk(0)rdisk(1)partition(2)\Windows
2. On the File menu, click Save.
Modifying the Time Out

The time out represents the amount of seconds you are allowed to select an operating system from the menu before the default operating system is loaded.
1. In Notepad, edit the following line to reflect the amount of seconds needed.
timeout=30
2. On the File menu, click Save.

Tuesday, March 21, 2006

Design patterns

Design patterns have picked up a lot of importance off late and rightfully so. To define design patterns in simple words they are "popular solutions for common design problems". They are very helpful in designing architecture and they also increase ease of communication among the developers. I have practically applied few design patterns myself and would like to share my knowledge with you.

To start off GOF(Gang of Four) design patterns which are considered as the foundation of design patterns have been categorized into three sections namely creational which involves creation of objects, structural and behavioral patterns. I will cover all three sections by explaining one or more patterns from each individual section.

Creational Section:

Singleton Pattern:
This is a very popular creational pattern which restricts a class to have only one instance.

Example: "Prime Minister of India" is a singleton pattern as he/she has unique responsibilities and attributes.

Implementation: A singleton class can't have a public constructor and it has to be sealed. The entry point to get the singleton instance would be a static method or a static property.

public sealed class PrimeMinister
{
private static PrimeMinister instance = new PrimeMinister();
private PrimeMinister(){ }
public static PrimeMinister Instance
{
get { return instance; }
}
}

Abstract Factory Pattern:

Abstract Factory is commonly known as factory pattern. In this pattern all the classes involved implement/realize the same interface and the compiler only knows that the created object implements the specific interface but not the object's type. This is very flexible when you need to make a creation decision at runtime depending on some aspect of object's behavior rather than it's type.

Example: Imagine that there is a rental store of cars, bikes, trucks, etc but you want to deliver a vehicle depending on the customer's choice.

Implementation: Programmatically you can make a run time decision using a switch statement to return a new instance of a class which implements the specific interface depending on the customer's choice. As you can see in the constructor of "Journey" class we are getting vehicletype of the current customer and passing it to the VehicleSupplier class's static method "GetVehicle". VehicleSupplier relies on a switch statement to return the vehicle needed, so if you observe here compiler just knows that newly created object implements the "IVehicle" interface but not if it's a car, truck or a bike upfront.

public class Journey
{
public IVehicle rentedVehicle;
public Journey(string customerID)
{
VehicleType vType = Customer.GetVehicleType(customerID);
/*Here is the late binding. Compiler doesn't know the type of the object except that it implements the IVehicle interface*/
rentedVehicle = VehicleSupplier.GetVehicle(vType);
}
//Method for beginning the journey
public void BeginJourney()
{
if(rentedVehicle != null)
{
rentedVehicle.Drive();
}
}
//Method for parking the vehicle
public void ParkTheVehicle()
{
if(rentedVehicle != null)
{
rentedVehicle.Park();
}
}
}
//The class which returns the new vehicle instance depending on the //vehicle type
public class VehicleSupplier
{
public static IVehicle GetVehicle(VehicleType vType)
{
switch(vType)
{
case VehicleType.CAR:
return new Car();
case VehicleType.TRUCK:
return new Truck();
case VehicleType.BIKE:
return new Bike();
}
return null;
}
}
//The interface which will be implemented by Car, Truck and Bike //classes
public interface IVehicle
{
void Drive();
void Park();
}
//enum of the vehicle types
public enum VehicleType{CAR=1,TRUCK,BIKE};

Structural Section:

Structural patterns depend on the structure of the classes involved. There are many structural patterns like Adapter, Builder, Decorator, etc. I will explain adapter pattern with an example here.

Adapter Pattern:

By converting the interface of one class into another interface which is expected by the clients we can make incompatible classes work together and this is the adapter pattern.

Example: Consider that you bought a gadget which expects 110v power supply but you are getting 240v supply, you need to get a power adapter in this case for converting 110v to 240v. This is a perfect example for the adapter pattern. In the software context you may need to have adapters for converting data from legacy systems like AS400 to XML or some other format for export purposes.

Implementation: As you can see the "StepUpStepDownPowerAdapter" object is used for converting power supply of 240V to 110V in the "TestUSGadget" class. The "USGadget" class defines the required voltage of the gadget and other properties. The converted power supply is given to the instance of "USGadget".

/// Class for testing the gadget
public class TestUSGadget
{
public static void Test()
{
USGadget gadget = new USGadget();
//Indian or European power supply
PowerSupply supply = new PowerSupply(VoltageTypes.V240);
if(gadget.ExpectedVoltage != supply.Voltage)
{
StepUpStepDownPowerAdapter adapter = new StepUpStepDownPowerAdapter();
//Getting the converted power
supply = adapter.Convert(supply,gadget.ExpectedVoltage);
gadget.Power = supply;
gadget.Start();
}
}
}
public class StepUpStepDownPowerAdapter
{
public StepUpStepDownPowerAdapter()
{
}
//Method for coverting voltages
public PowerSupply Convert(PowerSupply supply,VoltageTypes convertToVoltage)
{
if(supply == null) return supply;
//Convert iff the voltage is not in expected way
if(supply.Voltage != convertToVoltage)
supply.Voltage = convertToVoltage;
return supply;
}
}
/// The power supply class
public class PowerSupply
{
VoltageTypes voltageType;
//There will be other properties as well
public PowerSupply(VoltageTypes vType)
{
voltageType = vType;
}
public VoltageTypes Voltage
{
get
{
return voltageType;
}
set
{
voltageType = value;
}
}
}
//Voltage Types enum
public enum VoltageTypes{V110,V240};
//Gadget which expects 110V
public class USGadget
{
VoltageTypes reqVoltage;
PowerSupply supply;
public USGadget()
{
reqVoltage = VoltageTypes.V110;
}
public VoltageTypes ExpectedVoltage
{
get
{
return reqVoltage;
}
}
public PowerSupply Power
{
get
{
return supply;
}
set
{
supply = value;
}
}
public void Start()
{
}
}

Behavioral Section:
Behavioral Patterns define the behavior of the classes involved. The popular behavioral patterns include Chain of Responsibilities,Interpreter, Mediator, Iterator, Observer, etc. I will explain Observer pattern here.

Observer pattern involves a one-many dependency between objects where a change in an object(subject) needs to be notified to all it's dependents(observers).

Example: Consider a scenario where a job posting at some company got multiple applications. Whenever the job status changes (filled, removed or suspended) all the applicants of the job should be notified. In this case job object is subject and all the applicants are observers.

Implementation: As you can see below "Job" is the subject class and all applicants of that particular job are observers. Job class has "Add" and "Remove" methods for adding and removing applicants to it's list. Whenever job status changes all the applicant objects would be notified through Notify method which in turn calls the "Update" method of the applicant object.

/// This the subject in the observer pattern.
public class Job
{
private ArrayList applicants;
private JobStatus statusOfJob;
public Job()
{
applicants = new ArrayList();
}
public void Add(Applicant candidate)
{
applicants.Add(candidate);
}
public void Remove(Applicant candidate)
{
applicants.Remove(candidate);
}
public void Notify()
{
foreach (Applicant candidate in applicants)
{
candidate.Update(this);
}
}
public JobStatus Status
{
get
{
return statusOfJob;
}
set
{
statusOfJob = value;
Notify();
}
}
}
//Jobstatus enumerator
public enum JobStatus{FILLED,SUSPENDED,REMOVED};
/// This is Observer.
public class Applicant
{
//declare variables
string fname;
string lname;
string emailID;
string phoneNo;
public Applicant()
{
//
// TODO: Add constructor logic here
//
}
#region Properties for exposing the member variables
#endregion
public void Update(Job appliedJob)
{
switch(appliedJob.Status)
{
case JobStatus.FILLED:
//Do something like sending email, //updating database, etc
break;
case JobStatus.REMOVED:
//Do something like sending email, //updating database, etc
break;
case JobStatus.SUSPENDED:
//Do something like sending email, //updating database, etc
break;
}
//Your own functionality
//End Of Functionality
}
}

Conclusion
All in all design patterns are really helpful in solving design issues. Having the knowledge of various design patterns will make things much simpler whenever you come across such design problems.

Monday, February 20, 2006

What Your Name Means.


Instructions : What you do is find out what each letter of your name
means.

Then connect all the meanings and it describes YOU. (Its TRUE) & (Is'nt it GREAT !!)


PS : If you have double or triple letters, just count the meaning
once.

For Example : RAMA

R - You are a social butterfly.

A - You can be very quiet when you have something on your mind.

M - Success comes easily to you.

----------------------------------------------------------------------------------

A = You can be very quiet when you have something on your mind.

B = You are always cautious when it comes to meeting newpeople.

C = You definitely have a partier side in you, don't be shy to show it.

D = You have trouble trusting people.

E =You are a very exciting person.

F = Everyone loves you.

G = You have excellent ways of viewing people.

H =You are not judgmental.

I =You are always smiling and making others smile.

J =Jealously

K =You like to try new things.

L = Love is something you deeply believe in.

M = Success comes easily to you.

N = You like to work, but you always want a break.

O = You are very open-minded.

P =You are very friendly and understanding.

Q = You are a hypocrite.

R =You are a social butterfly.

S = You are very broad-minded.

T = You have an attitude, a big one.

U = You feel like you have to equal up to people's standards.

V = You have a very good physique and looks.

W = You like your privacy.

X = You never let people tell you what to do.

Y = You cause a lot of trouble.

Z = You're always fighting with someone.



CHECK YOUR NAME MEANING AND YOU WILL FIND THAT THIS IS TRUE.............

What is Thread Pooling?

Thread pooling is the process of creating a collection of threads during the initialization of a multithreaded application, and then reusing those threads for new tasks as and when required, instead of creating new threads. The number of threads for the process is usually fixed depending on the amount of memory available, and the needs of the application. However, it might be possible to increase the number of available threads. Each thread in the pool is given a task and, once that task has completed, the thread returns to the pool and waits for the next assignment.

The Need for Thread Pooling

Thread pooling is essential in multithreaded applications for the following reasons.

  • Thread pooling improves the response time of an application as threads are already available in the thread pool waiting for their next assignment and do not need to be created from scratch

  • Thread pooling saves the CLR from the overhead of creating an entirely new thread for every short-lived task and reclaiming its resources once it dies

  • Thread pooling optimizes the thread time slices according to the current process running in the system

  • Thread pooling enables us to start several tasks without having to set the properties for each thread

  • Thread pooling enables us to pass state information as an object to the procedure arguments of the task that is being executed

  • Thread pooling can be employed to fix the maximum number of threads for processing a particular request

The Concept of Thread Pooling

One of the major problems affecting the responsiveness of a multithreaded application is the time involved in spawning threads for each task.

For example, a web server is a multithreaded application that can service several client requests simultaneously. Let's suppose that ten clients are accessing the web server at the same time:

  • If the server operates a one thread per client policy, it will spawn ten new threads to service these clients, which entails the overhead of first creating those threads and then of managing them throughout their lifetime. It's also possible that the machine will run out of resources at some point.

  • Alternatively, if the server uses a pool of threads to satisfy those requests, then it will save the time involved in the spawning of those threads each time a request from a client comes in. It can manage the number of threads created, and can reject client requests if it is too busy to handle them. This is exactly the concept behind thread pooling.

The .NET CLR maintains a pool of threads for servicing requests. If our application requests a new thread from the pool, the CLR will try to fetch it from the pool. If the pool is empty, it will spawn a new thread and give it to us. When our code using the thread terminates, the thread is reclaimed by .NET and returned to the pool. The number of threads in the thread pool is limited by the amount of memory available.

To recap then, the factors affecting the threading design of a multithreaded application are:

  • The responsiveness of the application

  • The allocation of thread management resources

  • Resource sharing

  • Thread synchronization

Responsiveness of the application and resource sharing are addressed by this chapter on thread pooling. The remaining factors have been covered in the previous chapters of this book.

The CLR and Threads

The CLR was designed with the aim of creating a managed code environment offering various services such as compilation, garbage collection, memory management, and, as we'll see, thread pooling to applications targeted at the .NET platform.

Indeed, there is a remarkable difference between how Win32 and the .NET Framework define a process that hosts the threads that our applications use. In a traditional multithreaded Win32 application, each process is made up of collections of threads. Each thread in turn consists of Thread Local Storage (TLS) and Call Stacks for providing time slices in the case of machines that have a single CPU. Single processor machines allot time slices for each thread to execute based on the thread priority. When the time slice for a particular thread is exhausted, it is suspended and some other thread is allowed to perform its task. In the case of the .NET Framework, each Win32 process can be sub-divided logically into what are known as Application Domains that host the threads along with the TLS and call stack. It's worthwhile to note that communication between application domains is handled by a concept called Remoting in the .NET Framework.

Having gained a basic understanding on concepts of thread pooling and the .NET process, let's dig into how the CLR provides us with thread pooling functionality for .NET applications.

The Role of the CLR in Thread Pooling

The CLR forms the heart and soul of the .NET Framework offering several services to managed applications, thread pooling being one of them. For each task queued in the thread pool (work items), the CLR assigns a thread from the pool (a worker thread) and then releases the thread back to the pool once the task is done.

Thread pools are always implemented by the CLR using a multithreaded apartment (MTA) model by employing high performance queues and dispatchers through preemptive multitasking. This is a process in which CPU time is split into several time slices. In each time slice, a particular thread executes while other threads wait. Once the time slice is exhausted, other threads are allowed to use the CPU based on the highest priority of the remaining threads. The client requests are queued in the task queue and each item in this queue is dispatched to the first available thread in the thread pool.

Once the thread completes its assigned task, it returns to the pool and waits for the next assignment from the CLR. The thread pool can be fixed or of dynamic size. In the former case, the number of threads doesn't change during the lifetime of the pool. Normally, this type of pool is used when we are sure of the amount of resources available to our application, so that a fixed number of threads can be created at the time of pool initialization. This would be the case when we are developing solutions for an intranet or even in applications where we can tightly define the system requirements of the target platform. Dynamic pool sizes are employed when we don't know the amount of resources available, as in the case of a web server that will not know the number of client requests it will be asked to handle simultaneously.

Caveats to Thread Pooling

There is no doubt that thread pooling offers us a lot of advantages when building multithreaded applications, but there are some situations where we should avoid its use. The following list indicates the drawbacks and situations where we should avoid using thread pooling:

  • The CLR assigns the threads from the thread pool to the tasks and releases them to the pool once the task is completed. There is no direct way to cancel a task once it has been added to the queue.

  • Thread pooling is an effective solution for situations where tasks are short lived, as in the case of a web server satisfying the client requests for a particular file. A thread pool should not be used for extensive or long tasks.

  • Thread pooling is a technique to employ threads in a cost-efficient manner, where cost efficiency is defined in terms of quantity and startup overhead. Care should be exercised to determine the utilization of threads in the pool. The size of the thread pool should be fixed accordingly.

  • All the threads in the thread pool are in multithreaded apartments. If we want to place our threads in single-thread apartments then a thread pool is not the way to go.

  • If we need to identify the thread and perform various operations, such as starting it, suspending it, and aborting it, then thread pooling is not the way of doing it.

  • Also, it is not possible to set priorities for tasks employing thread pooling.

  • There can be only one thread pool associated with any given Application Domain.

  • If the task assigned to a thread in the thread pool becomes locked, then the thread is never released back to the pool for reuse. These kinds of situations can be avoided by employing effective programmatic skills.

The Size of the Thread Pool

The .NET Framework provides the ThreadPool class located in the System.Threading namespace for using thread pools in our applications. The number of tasks that can be queued into a thread pool is limited by the amount of memory in your machine. Likewise, the number of threads that can be active in a process is limited by the number of CPUs in your machine. That is because, as we already know, each processor can only actively execute one thread at a time. By default, each thread in the thread pool uses the default task and runs at default priority in a multithreaded apartment. The word default seems to be used rather vaguely here. That is no accident. Each system can have default priorities set differently. If, at any time, one of the threads is idle then the thread pool will induce worker threads to keep all processors busy. If all the threads in the pool are busy and work is pending in the queue then it will spawn new threads to complete the pending work. However, the number of threads created can't exceed the maximum number specified. By default, 25 thread pool threads can be created per processor. However, this number can be changed by editing the CorSetMaxThreads member defined in mscoree.h file. In the case of additional thread requirements, the requests are queued until some thread finishes its assigned task and returns to the pool. The .NET Framework uses thread pools for asynchronous calls, establishing socket connections, and registered wait operations.