WCF Service Method Overloading

You all may have found this one out even earlier, but I found this out just a few days before. A WCF Service doe not allow normal method overloading , which is supported by .NET. It throws InvalidOPerationException.

As for the reasons to why this happens is becasue WSDL is not a object orinted language and does not support these features of OOP. However overloading can be performed in WCF service in a roundabout way.

[ServiceContract]
interface ICalculator
{
 [OperationContract(Name="AddIntegers")]
 int Add(int a,int b)

 [OperationContract(Name="AddDouble")]
 double Add(double a,double b)
}

The Name property in the OperationContract attribute enables the WSDL to make the difference between to same named methods here.

 

Cheers

 

 

 

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

I Am Back

Could post for a long time becuase of some personal problems... Sorry for that ..... Hoping to make some new posts pretty soon.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Usng List.Exists<>

List ss = new List();

ss.Add(1);

ss.Add(3);

ss.Add(5);

ss.ForEach(delegate(int x)

{ if (x < 4) Console.WriteLine(x); });

 Console.ReadKey();

Also checked out that this is probably the best in compared to Foreach and For loops

 

Cheers

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Eror while loading assemblies dynamically

I was trying to load PropertyInfo object using Reflection , when I came accross a very strange thing. I was loading the Assembly using 1) Asembly.LoadFile() and then 2) did a GetTypes() Unfortunately it was throwing an exception that it was unable to load all properties while performing the GetTypes(). However the Assembly.Load() was performing as expected. Digging into the details of the root cause of exception I found out that the assembly that I was trying to load dynamically was dependent on other types, which it could not load. I found a roundabout in working with this I did a 1) Asembly.LoadFrom() and then 2) did a GetTypes() and it worked.. Still trying to figure out why the previous one did not work. Any ideas??? Cheers
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Unity Application Block

I started working with the Unity Application Block just the other day. It is the Dependency Injection Block that has recently been introduced in the Enterprise Library Block 4.1. Personally speaking I found it much easier to understand and work with compared to the other standard DI tools like Castle Windsor and Structure map.

Some very useful links regarding Unity are :

http://www.codeplex.com/unity

Also you can check Scot ha's blog , whci contains a few number of podcasts which were very helpful to me.


Cheers...


  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Adding Custom Search Conditions in your List.Exists() method.

In one of my previous article (October 2006) on this topic , I’ve shown how to use the Exists() method of a list in order to find an object in the list that matched a certain value. However there I also mentioned about one disadvantage
 
            “the value to be checked needs to be more or less predetermined (hardcoded) as the delegate method does not take any other parameters.”
 
Therefor it meant that an Exists method can only find an object in a lIst , if it contained on perdetermined serach condition, it will however fail to find if the search condition changes . And I found no good way of getting around this limitiaton then. Here I’ll be presenting a way to perform a cutomised find, such that the search criteria need not be hard-coded. (ref method CheckIfExists() in the October2006 article) . If you have ever used any method that a .net generic list exposes and has a Predicate<> as a parameter (for e.g. Exists()), the above mentioned disadvantage is there. The predictate is a delegate declared in the .Net framework. Because of this this delegate , your methods need to match the signature of this delegate in order to be used in a method like Exists(), which takes . As a result you won’t be able to add any other parameter to your method , like customsearchCondition in your method as this voilates the signature of the Predicate<> delegate.
So I first overloaded the Predicate<> delegate to have my own Signature
 
public delegate bool Predicate<T>(T obj, string customsearchCondition);
 
Once this is done , I created a class of my own , ListBase<T> which inherits from List<T> , so that I can use all the existing facilitis that a .net List<> provides without adding any more code.
 
public class ListBase<T>:List<T>
 
Now I add the following method to my class
 

 

 private bool TryFindFirstWhere<T>(IEnumerable<T> collection, Predicate<T> predicate, out T foundItem, RequestId matchVal)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");
            if (predicate == null)
                throw new ArgumentNullException("predicate");

            foreach (T item in collection)
            {
                if (predicate(item,matchVal))
                {
                    foundItem = item;
                    return true;
                }
            }

            // didn't find any item that matches.
            foundItem = default(T);
            return false;
        }

 
 
This method ensures that I have to pass my search condition along with the Predicate<> and returns a boolean value if the object is found in the list. In order to actually get the object from the list, I also add one out parameter, which will assigned the object once it is found. If the object is not found, I’m returning the default value of the data type.
Any better suggestions would always be appreciated...........
Cheers
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SkyDrive

Windows Live has  a great feature integrated to itself, known as SkyDrive, where you can manage files and keep them on the web. The max size is 1 GB . But it's really a great feature..

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Design patterns - Part 4-Builder Pattern in .NET

Object creation as you might remember was done using the Factory Pattern (as mentioned in an blog previously “Design patterns - Part 1-Factory Pattern in .NET”. But not always creating involves a single process. Sometimes it takes more than one processes to create a full product, and then creation of these separate objects in a particular way needs the Builder pattern. But Builder pattern will not be suffice in the scenario, that I’m going to present now. A factory along with a builder will do the trick for us.
 
Let us consider , we are making a Computer.. We need a keyboard, mouse also to give the computer a full sense. So our creation process is not limited to making only the computer(read CPU ) itself, you also need to create the Mouse,Keyboard and many other accessories.
 
Lets assume we have classes for Mouse,Keyboard etc.. like as follows….
 
 
public class KeyBoard
    {
        public KeyBoard() { Console.WriteLine("This is a good Keyboard"); }
 
        public KeyBoard(bool isremote) { if (isremote) { Console.WriteLine("This is a remote Keyboard "); } else { Console.WriteLine("Good Silver Keyboard"); } }
    }
 
 
public class Mouse
    {
       public Mouse() { Console.WriteLine("This is a optical mouse"); }
    }
 
public class WebCam
    {
        public WebCam() { Console.WriteLine("This is a 2 MP Camera"); }
    }
 
 
Just like the “Factory Pattern” (ref. Design patterns - Part 1-Factory Pattern in .NET) we will still be having an abstract class (Computer class here) . The only addition is that ,because a full computer needs to have a “KeyBoard” and “Mouse” , the Computer class here has two memebers for these corresponding objects.
The code follows
 
public abstract class Computer
    {
       KeyBoard keyBoard;
       Mouse mouse;
 
      
       public KeyBoard KeyBoard
       {
           get { return keyBoard; }
           set { keyBoard = value; }
       }
 
      
       public Mouse Mouse
       {
           get { return mouse; }
           set { mouse = value; }
       }
     
     
    }
 
 
Now just as in the the “Factory Pattern” (ref. Design patterns - Part 1-Factory Pattern in .NET) we will create the individual computers. In our sample we’re creating three type sof computers..lets see
 
 
public class Brand1Computer:Computer
    {
 
    }
 
public class Brand2Computer:Computer
    {
    }
 
public class CustomAssembledComputer:Computer
    {
        private WebCam webCam;
 
        public WebCam WebCamera
        {
            get { return webCam; }
            set { webCam = value; }
        }
     
    }
 
Now take a close look in the abobe three classes . While the first two just inheris the abstract class, the last one adds another functionality to itself, i.e. the WebCamera and thus have a property for that.
 
Now we need to create the builder, in order to create the whole assembly.
 
public abstract class Builder
    {
       public abstract void CreateFullComputer(ref Computer computer);
    }
 
The Builder as you might see is an abstract class. The individual builder classes still needs to be put in place. In each of these individual classes we will create the whole assembly in the order we want.
 
 
 
 
public class Brand1ComputerBuilder : Builder
    {
       public override void CreateFullComputer(ref Computer computer)
       {
          
           Brand1Computer brand1 = (Brand1Computer)computer;
           brand1.KeyBoard = null;
           brand1.Mouse = new Mouse();
 
       }
    }
 
 
 
public class Brand2ComputerBuilder:Builder
    {
        public override void CreateFullComputer(ref Computer computer)
        {
              
            Brand2Computer brand2 = (Brand2Computer)computer;
            brand2.KeyBoard = new KeyBoard();
            brand2.Mouse = new Mouse();
 
        }
    }
 
 
public class CustomAssembledComputerBuilder:Builder
    {
       public override void CreateFullComputer(ref Computer computer)
       {
           
           CustomAssembledComputer customComp = (CustomAssembledComputer)computer;
           customComp.KeyBoard = new KeyBoard(true);
           customComp.Mouse = new Mouse();
           customComp.WebCamera = new WebCam();
       }
    }
 
 
 
So we have our individual builders. Just take a closer look first at  “Brand1ComputerBuilder” where I have opted that this assembly will not have a mouse. “Brand2ComputerBuilder” however is a more general assembly in all respects. “CustomAssembledComputerBuilder” however , adds a webcamera to its accessories list during creation. So you might see that , what I mentioned during my first few lines , that a builder is more necessary when multiple creational steps are the present.
 
We have not finished yet…. !! Where is the actual factory that creates the computer ( as in the Factory Pattern” )
 
 
 
We will create that now..
 
public enum ComputerType
    {
        BrandOne,
        BrandTwo,
        Custom
    }
 
   public class ComputerFactory
    {
        Hashtable _registered = new Hashtable();
        Hashtable _loaded = new Hashtable();
       Hashtable _builders = new Hashtable();
 
       public void Register(ComputerType computerType,Type type,Builder builder)
       {
           _registered.Add(computerType, type);
           _builders.Add(computerType, builder);
       }
 
       public Computer CreateComputer(ComputerType computerType)
       {
           if (_loaded[computerType] == null)
                  LoadComputer();
          
 
           Computer computer = (Computer)_loaded[computerType];
 
           if (_builders[computerType] != null)
           {
               Builder builder = (Builder)_builders[computerType];
               builder.CreateFullComputer(ref computer);
           }
 
           return computer;
       }
 
       private void LoadComputer()
       {
           foreach (DictionaryEntry obj in _registered)
           {
               Type type = (Type)obj.Value;
               ConstructorInfo cinfo = type.GetConstructor(new Type[] { });
               _loaded.Add(obj.Key, (Computer)cinfo.Invoke(new object[] { }));
           }
       }
 
    }
 
 
 
If you take a close look in the factory class here and the factory class in the “Factory Pattern” (ref. Design patterns - Part 1-Factory Pattern in .NET) you will find a few subtle differences. Lets analyse them a bit…
 
Now we have a new Hashtable declared
 
         
Hashtable _builders = new Hashtable();
 
The Register method now takes in a new parameter along with the old parameters.
 
public void Register(ComputerType computerType,Type type,Builder builder)
 
The builder is getting passed as a parameter now during registration. Let’s see how that helps. Within the “Register” method we have a new line
_builders.Add(computerType, builder);
 
 What this does is that, this maps the enum type with a corresponding builder object in the Hash table.
 
The “CreateComputer” method has also changed a bit. Along with the usual factory code we have the following code block added to it.
 
 
if (_builders[computerType] != null)
           {
               Builder builder = (Builder)_builders[computerType];
               builder.CreateFullComputer(ref computer);
           }
 
 
 
Therefore , unlike the Factory pattern, we now check the builders hashtable for null and actually load the corresponding builder from the _builders hashtable. And once we have this object we will call the “CreateFullComputer” method of the builder. This method takes in a computer and creates the full assembly , as mentooned in its builder and retuns the Computer object.
 
 
The “LoadComputer” method is still same as it was before.
 
Now its time to actually create these objects and see
 
static void Main(string[] args)
        {
            ComputerFactory cFactory = new ComputerFactory();
 
            cFactory.Register(ComputerType.BrandOne, typeof(Brand1Computer), new Brand1ComputerBuilder());
            cFactory.Register(ComputerType.BrandTwo, typeof(Brand2Computer), new Brand2ComputerBuilder());
            cFactory.Register(ComputerType.Custom, typeof(CustomAssembledComputer), new CustomAssembledComputerBuilder());
 
            Console.WriteLine("Brand 1 :");
            Computer computer = cFactory.CreateComputer(ComputerType.BrandOne);
            Console.WriteLine("Brand 2 :");
            computer = cFactory.CreateComputer(ComputerType.BrandTwo);
            Console.WriteLine("Custom :");
            computer = cFactory.CreateComputer(ComputerType.Custom);
 
            Console.ReadKey();
 
        }
 
 
 
 
The output is as follows
 
Brand 1 :
This is a optical mouse
Brand 2 :
This is a good Keyboard
This is a optical mouse
Custom :
This is a remote Keyboard
This is a optical mouse
This is a 2 MP Camera
 
 
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Design patterns - Part 3 - The Prototype Pattern

The Prototype pattern helps us in creating objects from existing ones. There can be any of the two following situations that may occur .
CASE 1:
Sometimes you may need to create an object of a certain class, but you do not have all the parameters that the constructor of that object need to create that object .
CASE 2:
You need to capture the present state of an object and create another object.
In either of the two above cases , we can clone the  existing object to create the new one.
Cloning(copying) in .net can be of two types, Deep Copy and Shallow Copy.   [you can easily find the difference between the two googling in the internet. J ] .
While performing shallow copy we ususally use obj.MemberWiseClone() feature of .net. Here the cloned object has the structure and the basic properties(value types ) from which the it is cloned. But using this method, we cannot have the data that persisted deeper in the source object, i.e you might have an object that houses an ArrayList with some other object instance. Now performing shallow copy will copy the ArrayList for you in the cloned object , but will not copy the object instances in the ArrayList. You need to do a deep copy to achieve that. One of the popular methods of deep copying is by implementing System.Iclonable .
Suppose we want to clone (shallow) an existing Car object to create another Car.
                                abstract class Car
{
                public abstarct Car CloneCar();
// other methods and code
}
class MyDreamCar : Car
{
//other code
 
 
 
public override Car CloneCar()
                {
                return (MyDreamCar)this.MemberwiseClone();
 
                }
}
               
 
 
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Design patterns-part 2- Abstract Factory Pattern

In the Factory Pattern we were creating objects of different types (viz. different car types Ambassador, Ford etc.) using the pattern. But sometimes we may need to create same object , but each having a different creational process, i.e. though they are objects of the same type they may have different attributes initialized when they are created based on our requirement. There comes the need of Abstract Factory Pattern.
 
Here we design an interface which acts as the contract for the AbstractFactory
 
interface IAbstractfactory
            {
                  Hashtable Carattributes();
            }
 
We are creating two types of the same car , but with different initialized attributes. These classes implement the interface IAbstractfactory.
 
      class EconomicCAR:IAbstractfactory
            {
                  public Hashtable Carattributes()
                  {
                        Hashtable eco = new Hashtable();
                        eco["Price"]="1000";
                        eco["colorsAvailable"]=3;
                        return eco;
 
                  }
            }
 
            class BusinessCAR:IAbstractfactory
            {
                  public Hashtable Carattributes()
                  {
                        Hashtable business = new Hashtable();
                        business["Price"]="20000";
                        business["colorsAvailable"]=2;
                        business["isAvailableinCountry"]=true;
                        return business;
 
                  }
 
 
 
You can clearly see that both car types have different attributes. But as mentioned before
Both of these actually are same type of projects.
 
Now we create the CarBase class as the base class of the cars.
 
class CarBase
            {
                  IAbstractfactory _abstractfactory;
                  Hashtable _carattributes;
 
                  public IAbstractfactory Factory
                  {
                        get
                        {
                              return _abstractfactory;
                        }
                        set
                        {
                              _abstractfactory=value;
                        }
                  }
 
                  public Hashtable CarAttributes
                  {
                        get
                        {
                              _carattributes=Factory.Carattributes();
                              return _carattributes;
                        }
                       
                  }
            }
 
This class contains the a get/set property of type interface IAbstractFactory. This enables us to send any type of class at runtime, that implements the interface IAbstractFactory. The CarAttributes property enables only a get and gets the Carattributes of the passed-in _abstractfactory object. This way we do not need to have any if-else constructs while creating an object.
 
Now we come to the cars that actually inherit from the CarBase class.
 
class CarEconomic:CarBase
            {
                  public CarEconomic()
                  {
                        Factory= new EconomicCAR ();
                  }
            }
 
            class CarBusiness:CarBase
            {
                  public CarBusiness()
                  {
                        Factory= new BusinessCAR ();
                  }
            }
 
CarEconomic and CarBusiness are two class we would actually need to create at runtime. Both of these inherit from CarBase. In their corresponding constructors they pass the required object(that implements IAbstractFactory) to the Factory property of the CarBase class.
 
 
 
 
In main
 
static void Main(string[] args)
            {
                  CarBusiness _business= new CarBusiness();
                 
            foreach(DictionaryEntry e in _business.CarAttributes )
                  {
                        Console.WriteLine(e.Key + ": " + e.Value);
                       
                  }
                 
                  Console.WriteLine();
 
                  CarEconomic _economic = new CarEconomic();
 
            foreach(DictionaryEntry e in _economic.CarAttributes )
                  {
                        Console.WriteLine(e.Key + ": " + e.Value);
                  }
 
                  Console.ReadLine();
            }
 
 
As seen from the code above, we are passing either CarBusiness or CarEconomic to create the corresponding object at runtime..
 
 
 
 Cheers...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

My First Few Days @ a BIG BRAND

It was quite a thrilling experience when a bigbrand gave me the offer as a .net developer after my 3yrs of experience. I was thrilled to bits being a part of the big league , that too with such a  big company . I was coming from relatively medium level company,  with nice people (at least in my project and the HR guys, don't kow about the rest of them) . The induction meeting continued for 2 days @ the Park Hotel. Made some new freinds there. It was all going nice and fine UNTILL I was allocated in a project that had ms-access, excell as the programming interfaces in it. In my previous project I was working with technology and frameworks that belonged to the top of the stack in MS-Techologies. like asp.et 2.0, C# 3.0, Windows WorkFlow Foundation,Ajax 1.0 and now I cannot even install .net as my project does ot require it. That is really frustrating , isn't it??? Is this the price one needs to  pay to join a so called BIG BRAND.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Enterprise Library 3.0 -April 2007

Guys Enterprise Library 3.0--April 2007 is out .

This release of Enterprise Library includes: Caching Application Block, Cryptography Application Block, Data Access Application Block, Exception Handling Application Block, Logging Application Block, Policy Injection Application Block, Security Application Block and Validation Application Block.

Download it from :

http://www.microsoft.com/downloads/details.aspx?familyid=62ef5f79-daf2-43af-9897-d926f03b9e60&displaylang=en

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

To Find a control that has caused the postback

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

 

The above code is taken from http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx ... A beautiful example...

 

Cheeers..

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Generic EventHandler a new way of handling events

I was surprised to see the syntax of the new Generic Eventhandler... Using the .net 1.1 way we can declare events using the following steps..

STEP 1: declare a delegate

public delegate void DivThreeHandler(object ,DivByThreeEventArgs e);

The abobe delegate declares the parameters to be sent to the event handlers.Any class that wants to handle this event needs to have a method that mathces this signature.

STEP 2: define the EventArgs derived class

public class DivByThreeEventArgs:EvetArgs
{
   ...........code.......
}

STEP3: define the class that want to be notified of the event.

public class DivByThreeListener
{
 public void Display(object o,DivByThreeEventArgs e)
  {
  ...............
  }
}

As you can see that the signature of Display mathces with the delegate.

STEP4: Declare the event and notify the intended class.

in event generating class ....declare the event
 
 public static event DivByThreeEventHndler EventThree;

 public static void Main()
     {
         DivByThreeListener dbl = new DivByThreeListener();
         EventThree += new DivByThreeHandler(dbl.Display);
         GenerateNumbers();
     }

 Now the function(in the same class) that invokes the event and thus notifies all  clients..........

 public static void OnEventThree(DivByThreeEventArgs e)
  {
       if(EventThree!=null)
          EventThree(new object(),e);
  }

 EventThree is null if no client is hooked to the delegate..

This was the C# 1.1 way . As C# 2.0 was introduced generics came in and so did Generic EventHandler.

=================================================================================================================

The foll. is taken from MSDN library :-

 EventHandler is a predefined delegate that represents an event handler method for an event, regardless of whether the event generates event data. If your event does not generate event data, substitute EventArgs for the generic type parameter; otherwise, supply your own custom event data type and substitute it for the generic type parameter.

The advantage of using EventHandler is that you do not need to code your own custom delegate if your event generates event data.

==================================================================================================================

namespace GenericEvnetHandler
{
    //---------------------------------------------------------
    public class MyEventArgs : EventArgs
    {
        private string msg;

        public MyEventArgs(string messageData)
        {
            msg = messageData;
        }
        public string Message
        {
            get { return msg; }
            set { msg = value; }
        }
    }
    //---------------------------------------------------------
    //---------------------------------------------------------
    public class ListenEvent
    {

        public static void SampleEventHandler(object src, MyEventArgs mea)
        {
            Console.WriteLine(mea.Message);
            Console.ReadKey();
        }

      
    }
    //---------------------------------------------------------
    class Program
    {
        // Declare an event of delegate type EventHandler of
        // MyEventArgs.


      


        public static event EventHandler<MyEventArgs> SampleEvent;
        public static void Main()
        {
            ListenEvent le = new ListenEvent();
            SampleEvent += new EventHandler<MyEventArgs>(ListenEvent.SampleEventHandler);
            OnDemoEvent("Hey there, Bruce!");
            OnDemoEvent("How are you today?");
            OnDemoEvent("I'm pretty good.");
            OnDemoEvent("Thanks for asking!");
        }

        public static void OnDemoEvent(string val)
        {
            // Copy to a temporary variable to be thread-safe.
            EventHandler<MyEventArgs> temp = SampleEvent;
            if (temp != null)
                temp(null , new MyEventArgs(val));
        }
       
    }
}

 

Cheers...

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

A problem with the Accordian control

The Accordian Control of  the Atlas Control Toolkit RC1 has a starnge behaviour. Any server control placed within it does not fire their server-side events. However I found out a way around to this problem.

Did an AccordianPane.FindControl() of that control , and attched the eventhandler manually to that...

and it was rocking.....

Cheers

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati