WCF Ping

This is my latest article on Code Project. This is a simple utility to ping WCF Services. You can find the article here.


Applying Decorator To Control Menus

This article of mine on code project talks about one of the applications of Decorator pattern. Any GUI based application that are menu driven would have some logic to turn on / off the menu items based on different set of attributes like ( Licensing policies, user roles, application state etc ). Decorator comes handy on keeping this implementation extensible and maintainable. Here is the link to the article. Happy reading!


.Net Generics – 2

Generic Singleton Type

We have all writen Singleton implementations in our code sometime or the other. The basic code structure is the almost the same.  Have a static member of a type, check for null before initialization and return the instance. Additionally, lock the object if you need to have synchronization logic.  The same boiler plate code can be re-written using Generics so that it can be re-used.

public class TSingleton<TType>
        where TType:new()
        private static TType _instance;

        public static TType Instance
                if (_instance == null)
                    _instance = new TType();

                return _instance;

For example, let say we have classes called DBService and Logger which you would like to be a singleton’s. Using the above type, you can your singleton’s as,

DBService dbService = TSingleton<DBService>.Instance;
Logger logger = TSingleton<Logger>.Instance;

Thats TSingleton!

.Net Generics – 1

Parsing an Enum:

Generally for converting a value to a type of Enum, we use the Enum.Parse method. Let’s take the following Enum for example and see how a value is converted.

enum Colour : int
  Red = 1,
  Blue = 2,
  Orange = 3

// Value read from the a source e.g., database.
int colourValue = 2;
//Convert the value to the type of Colour.
Colour colour = (Colour)Enum.Parse(typeof(Colour), 

All places where a value needs to be converted would have the above statement, where type of enum needs to be provided and the result needs to be casted back to the actual type. Using a simple Generics construct the same piece of code could be re-written as,

//Convert to the type of colour.
Colour colour = TEnum.Parse<Colour>(colourValue.ToString());


Here is the definition of TEnum

public struct TEnum
  public static T Parse<T>(string value)
    return Parse(value, true);

  public static T Parse<T>(string value, bool ignoreCase)
    return (T)Enum.Parse(typeof(T), value, ignoreCase);

That’s TEnum!