The strategy pattern is typically used when your programmer's algorithm should be interchangeable with different variations of the algorithm. For example, if you have code that sorts array, under certain circumstances, you might want to create QuickSort and under other circumstances, you might want to create Merge Sort.

The strategy pattern is usually implemented by declaring an abstract base class with an algorithm method, which is then implemented by inheriting concrete classes. At some point in the code, it is decided what concrete strategy is relevant; it would then be instantiated and used wherever relevant.

Following example shows how a ArrayList with diffrent sort algorithms.


using System;
using System.Collections;
using NUnit.Framework;

namespace DesignPatterns
{
    // Strategy class: SortStrategy
    // Define the general interface common to all supported algorithms
    public abstract class SortStrategy
    {
        public abstract void Sort(ArrayList list);
    }

    // Concrete class QuickSort
    public class QuickSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            // Sort the list using a quicksort algorithm
        }
    }

    // Concrete class MergeSort
    public class MergeSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            // Sort the list using a mergesort algorithm
        }
    }

    // Context class
    public class SortedList
    {
        private ArrayList list = new ArrayList();
        private SortStrategy sortstrategy;

 public SortedList(SortStrategy sortstrategy)
        {
            this.sortstrategy = sortstrategy;)
   
 }
       
        public void Add(string name)
        {
            list.Add(name);
        }

        public void Sort()
        {
            sortstrategy.Sort(list);
        }
    }

    [TestFixture]
    public class StrategyClassTestFixture
    {
        [Test]
        public void TestSortedList()
        {
            SortedList sortedList = new SortedList(new QuickSort());

            sortedList.Add("mitchel");
            sortedList.Add("gregg");
            sortedList.Add("steve");
            sortedList.Add("rob");

        }
    }
}

since i have already posted basic ContraVariance in delegate, i am not going to go thru the same again, those of you who had missed my earlier post can refer here

here is an example of using generics with contravariance

namespace ContravarianceWithGenerics
{
    public interface IEquity
    {
        string ToString();
        string Save();
    }

    //base class
    abstract class Equity : IEquity
    {
        int _price;

        public Equity(int Price)
        {
            _price = Price;
        }
        public override string ToString()
        {
            return GetType().Name + " : " + _price;
        }

        #region IEquity Members


        public virtual string Save()
        {
            return "Called from Base Class";
        }

        #endregion
    }
    //derived
    class Stock : Equity
    {
        public Stock(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Stock Class";
        }
    }

    //derived
    class Bond : Equity
    {
        public Bond(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Bond Class";
        }
    }

    class EquityBusinessImplementation<T> where T: Equity, IEquity
    {
        public delegate void SellNotify(T b);

        public void EquitySaleReport(Equity e)
        {
            Console.WriteLine("Report of sale is " + e);
            Console.WriteLine(e.Save() );
        }
        public SellNotify sellNotifyDlg;

        public void Sell(T s)
        {
            if (null != sellNotifyDlg)
            {
                sellNotifyDlg(s);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EquityBusinessImplementation<Stock> s =
                new EquityBusinessImplementation<Stock>();
            s.sellNotifyDlg += s.EquitySaleReport;
            s.Sell(new Stock(100));

            EquityBusinessImplementation<Bond> b =
                new EquityBusinessImplementation<Bond>();
            b.sellNotifyDlg += b.EquitySaleReport;
            b.Sell(new Bond(1000));
        }
    }
}

Happy programming !!!

A generic class that uses parameterized types, like MyBase<T>, is called an open-constructed generic. A generic class that uses no parameterized types, like MyBase<int>, is called a closed-constructed generic.

You may derive from a closed-constructed generic; that is, you may inherit a class named MyDerived from another class named MyBase, as in:


public class MyDerived<T> : MyBase1<int>

You may derive from an open-constructed generic, provided the type is parameterized.

For example:

public class MyDerived<T> : MyBase<T> is valid, but


public class MyDerived<T> : MyBase<Y> is not valid since Y is also a parameterized type.

Note: Non-generic classes may derive from closed-constructed generic classes, but not from open-constructed generic classes. That is,

public class MyDerived : MyBase<int> is valid, but


public class MyDerived : MyBase<T> is not valid.

-------

A generic class allows you to write your class without committing to any type, yet allows the user of your class, later on, to indicate the specific type to be used. While this gives greater flexibility by placing some constraints on the types that may be used for the parameterized type, you gain some control in writing your class. Let's look at an example:

Example 1. The need for constraints: code that will not compile


public static T Max<T>(T op1, T op2)
{
        if (op1.CompareTo(op2) < 0)
                return op1;
        return op2;
}


The code in Example 1 will produce a compilation error:

Error 1 'T' does not contain a definition for 'CompareTo'

Assume I need the type to support the CompareTo() method. I can specify this by using the constraint that the type specified for the parameterized type must implement the IComparable interface. Example 2 has the code:

Example 2. Specifying a constraint


public static T Max<T>(T op1, T op2) where T : IComparable
{
        if (op1.CompareTo(op2) < 0)
                return op1;
        return op2;
}

In Example 2, I have specified the constraint that the type used for parameterized type must inherit from (implement) IComparable. The following are some of the other constraints may be used:


where T : struct                   type must be a value type (a struct)
where T : class                   type must be reference type (a class)
where T : new()                  type must have a no-parameter constructor
where T : class_name      type may be either class_name or one of its
                                              sub-classes (or is below class_name
                                              in the inheritance hierarchy)

where T : interface_name  type must implement the specified interface
You may specify a combination of constraints, as in: where T : IComparable, new(). This says that the type for the parameterized type must implement the IComparable interface and must have a no-parameter constructor.

------

Delegate inference allows you to make a direct assignment of a method name to a
delegate variable, without wrapping it first with a delegate object.

The oldwayclass shows implementation in C# 1.1

class OldWayClass
{
   delegate void notifyDelegate();
   public void InvokeMethod()
   {
      notifyDelegate del = new notifyDelegate(SomeMethod);
      del();
   }
   void SomeMethod()
   {...}
}


and the NewWayClass is the sample implementation in C# 2.0

class NewWayClass
{
   delegate void notifyDelegate();
   public void InvokeMethod()
   {
      notifyDelegate del = SomeMethod;
      del();
   }
   void SomeMethod()
   {...}
}

When you assign a method name to a delegate, the compiler first infers the delegate's type. Then the compiler verifies that there is a method by that name and that its signature matches that of the inferred delegate type. Finally, the compiler creates a new object of the inferred delegate type, wrapping the method and assigning it to the delegate. The compiler can only infer the delegate type if that type is a specific delegate type—that is, anything other than the abstract type Delegate. Delegate inference is a very useful feature indeed, resulting in concise, elegant code.

Covariance and contravariance provide a degree of flexibility when you match method signatures with delegate types. Covariance permits a method to have a more derived return type than what is defined in the delegate. Contravariance permits a method with parameter types that are less derived than in the delegate type.

contravariance example:

This example demonstrates how delegates can be used with methods that have parameters of a type that are base types of the delegate signature parameter type. With contravariance, you can now use one handler in places where, previously, you would have had to use separate handlers. For example both sellNotifyDlg and sellBondNotify delegates are using the same handler - EquitySaleReport since both stock and bond derive from Equity base class

using System;
using System.Collections.Generic;
using System.Text;

namespace ContraVariance
{
    //base class
    class Equity
    {
        int _price;

        public Equity(int Price)
        {
            _price = Price;
        }
        public override string ToString()
        {
            return GetType().Name + " : " + _price;
        }
    }
    //derived
    class Stock : Equity
    {
        public Stock(int Price)
            : base(Price)
        {

        }
    }

    //derived
    class Bond : Equity
    {
        public Bond(int Price)
            : base(Price)
        {

        }
    }

    class Program
    {
        delegate void StockSellNotify(Stock s);
        delegate void BondSellNotify(Bond b);

        static void EquitySaleReport(Equity e)
        {
            Console.WriteLine("Report of sale is " + e);
        }

        static StockSellNotify sellNotifyDlg;
        static BondSellNotify sellBondNotify;

        static void Sell(Stock s)
        {
            if (null != sellNotifyDlg)
            {
                sellNotifyDlg(s);
            }
        }

        //overload
        static void Sell(Bond  b)
        {
            if (null != sellBondNotify)
            {
                sellBondNotify(b);
            }
        }
      

        static void Main(string[] args)
        {
            sellNotifyDlg += EquitySaleReport;
            Sell(new Stock(100));

            sellBondNotify += EquitySaleReport;
            Sell(new Bond(101));

            //both sellNotifyDlg and sellBondNotify are using the same handler - EquitySaleReport

           
        }
    }
}

In my next post i will put a sample for Covariance and try to refine the contravariance sample with generics ...

Happy programming !!!

When we generate (WCF) service proxy class for a service by using svcutil.exe, it creates a proxy that derives from System.ServiceModel.ClientBase<TChannel>. The proxy implements IDisposable and the client code can be wraped inside using statement and guaranteed clean-up in the face of exceptions.

However, the System.ServiceModel.ClientBase<TChannel> class can throw exceptions from its Dispose method, because it internally invokes Close() method which might lead t0 a faulted state. In that case you have to call Abort for clean-up. Most times you are not interested in knowing whether the Dispose fails or not and you just want to have guaranteed clean up of any resources held by the proxy.

Check out this discussion on the WCF forum for why Microsoft implemented the dispose in this way.

To prevent you from writing a lot of code to accomplish this clean-up, I have written a generic GenericServiceProxyAgent class that does it for you.

The idea is that you derive a class from my GenericServiceProxyAgent<TProxy, TChannel> class. Insert your proxy class (that should derive from ClientBase<TChannel>) name for TProxy, and the service interface name for TChannel. The helper class wraps the proxy and doesn't directly expose its methods. From your derived class you can use the protected Proxy property to get access to the service proxy. You should add methods to your derived class that delegate to the proxy.

Create a convenience method to the derived helper that create request messages and unpack response messages. So our helper methods have a different signature than the methods on the proxy class itself.

here is the code snippet.

 

 


using System;
using System.Collections.Generic;
using System.ServiceModel;

namespace xxx.Net.Services
{
    /// <summary>
    /// Generic proxy class for a WCF services.
    /// </summary>
    /// <typeparam name="TProxy">The type of WCF service proxy to wrap.</typeparam>
    /// <typeparam name="TChannel">The type of WCF service interface to wrap.</typeparam>
    public class GenericServiceProxyAgent<TProxy, TChannel> : IDisposable
        where TProxy : ClientBase<TChannel>, new()
        where TChannel : class
    {
        /// <summary>
        /// variable to hold proxy instance
        /// </summary>
        private TProxy _proxy;

        /// <summary>
        /// Gets the WCF service proxy wrapped by this instance.
        /// </summary>
        protected TProxy Proxy
        {
            get
            {
                if (_proxy != null)
                {
                    return _proxy;
                }
                else
                {
                    throw new ObjectDisposedException("GenericServiceProxyAgent");
                }
            }
        }

        /// <summary>
        /// default constructor.
        /// </summary>
        protected GenericServiceProxyAgent()
        {
            _proxy = new TProxy();
        }

        /// <summary>
        /// Disposes the current instance.
        /// </summary>
        public void Dispose()
        {
            try
            {
                if (_proxy != null)
                {
                    if (_proxy.State != CommunicationState.Faulted)
                    {
                        _proxy.Close();
                    }
                    else
                    {
                        _proxy.Abort();
                    }
                }
            }
     catch (FaultException unknownFault)
     {
       System.Diagnostics.Debug.WriteLine("An unknown exception was received. " + unknownFault.Message);
       _proxy.Abort();
     }

            catch (CommunicationException)
            {
  System.Diagnostics.Debug.WriteLine("Service proxy encountred a communication exception and aborted");
                _proxy.Abort();
            }
            catch (TimeoutException)
            {
  System.Diagnostics.Debug.WriteLine("Service proxy encountred a timeout exception and aborted");
                _proxy.Abort();
            }
            catch (Exception)
            {
  System.Diagnostics.Debug.WriteLine("Service proxy encountred a unknown exception and aborted");
                _proxy.Abort();
                throw;
            }
            finally
            {
                _proxy = null;
            }
        }
    }
}

 

 

Note: Always check the "CommunicationState" before invoking any method on them, this is certainly an additional line of code but certainly a best practise

Happy programming !!!

 

i just finished writing Windows service host for my WCF services, there were no crash or exceptions thrown either by client or server,

I was just browing event log to check things were fine, then noticed at end of each call to WCF service, there was a log message with the following exception

System.ServiceModel.CommunicationException occurred
  Message="The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:02:00'."
  Source="System.ServiceModel"

ok here is the solution: when using netTcpBinding the service client has to call the close() method of the service in order to relase the instance back to the pool

Agile way to fix this is by change the binding type to WSHttp or BasicHttp. it will work

Happy Programing !!!

I guess most of us know what a static class is, you can't instiantiate, cannot have any instancing members etc.

This might sound funny but the truth is Static class are "Abstract and Sealed", never understood why ?

If you dont agree with me, use reflector or ILDASM and view your static Class .

Happy Programming !!!

----