Tuesday, November 27, 2007

WCF

Windows Communication Foundation? WCF? Waatzeet?
I will discuss about what WCF is a little later on. But now we will have to summarise how two different Applications can interact with each other. We have remoting which allows two different applications in different application domains to interact with each other. We have MSMQ using which two different applications can pass messages between them. We have WebServices using which we can make two applications interact.but all these have some shortcomings. For exampleMSMQ will be able to run on only windows machines.two applications have to conform to some specific standards if they have to use web services. Remoting will be possible only if both the applications are written in dot net.so to over come all these shortcomings, microsoft has come up with a new set of APIs to enable communication. This is Windows Communication Framework.
This is similar to web services (Service Oriented Architecture) , but WCF is flexible and its core serivices can be extended to suit our needs.so as industry standards grow, we can extend the WCF core.
WCF can operate with various things like MSMQ,Pipes, HTTP etc. This will be released with dot net framework 3.0 and orcas.
So without further delay we will develop a sample to enable us to understand better.
Create a new project of type “WCF service Library”
A class and a interface are created by default, delete them off. Also we have to add the following two “using statements” and references to “System.ServiceModel”
Using System.ServiceModel
Using System.Runtime.Serialization

Now we will start coding our custom interface and then implement taht interface.
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Add(int val1,int val2);

}
Here, the ServiceContract attribuite specifies that the interface is the contract for the service. Not getting it? Ok ,WCF works on 3 basic principles : ABC, address,binding ,contract. If you know COM, you will know that we have an interface to specify the service provided. And then we use QueryInterface on the Factory class to get that interface (type casted object). This is nothing but contract. So IMathLIB is the service contract which we will be exposing (C of WCF). Now the other Attribute is “OperationContract”- this signifies that the operation is being exposed by the service.now we have to implement this interface :
public class MathService : IMathLIB
{
public int Addint(int val1,int val2)
{
return val1+val2;
}
}

Now we have a MathService class which implements IMathLIB.build this , a DLL is generated..lets name it as MathService.
Now is this enuf? No not at all..all we have doen is just created a service. Now we have to host that service in some other application and run that host application. This forms the server part of WCF. Then we have t ocraete a client to consume this service.
Creating the server is simple :
Create a simple cnsole application projecct and name it as MathServiceHost, add a refrence to “System.ServiceModel”, “System.IdentityModel”, and “System.Runtime.Serialization”. now add a reference to “MathService.dll”.
Now we will start coding for the host
internal class MathServiceHost
{
internal static ServiceHost myServiceHost = null;

internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8000/MathService");

//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(MathService), new Uri( "http://localhost:8000/MathService"));

//Open myServiceHost
myServiceHost.Open();
}

internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
Now add config file :




address="http://localhost:8000/MathService"
contract="MathServiceLIB.IMathLIB"
binding="basicHttpBinding"/>






Look at the address, binding and contract in the config file.it completes the jigsaw puzzle,does i t not?

Build this and it builds without any errors. So this is fine.
Now to develop a client :
Just create a simple console application named “MathClient” and then add a “service refrence “ this the URL specified in the address in the config file (shown above) and then we can use the service just like we use web services.  bingo-- that does it.
But what if we want to add a new class in the service ? can we have operations on that class?
Well, we can!!!!
How? I will tell you .
Change your IMathLIB as shown below
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Addint(int val1,int val2);
[OperationContract]
DataContract1 Add(DataContract1 dataContractValue,DataContract1 dataContractValue2);
}
And then ad the new class type which you want

[DataContract]
public class DataContract1
{
string firstName;
string lastName;

[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}

public DataContract1 Add(DataContract1 data)
{
DataContract1 dc = new DataContract1();
dc.FirstName = this.firstName + data.FirstName;
dc.LastName = this.LastName + data.LastName;
return dc;
}
}

The attribute DataContract specifies that it is a datatype and the atribute “Datamember” specifies that it is a field.
Now w can code for our MathService class and implement the IMathLIB interface.
The rest is all as we did before 

Hope this helps u.
Happy Coding !!!
Regards,
nandan

Sunday, November 18, 2007

Command Pattern

hi,
we will discuss about command pattern today !!!

scenario :
i am developing a game where i have my main character running,sitting and standing.
for now , will print "sit" when he sits,"stand" when he stands,"run" when he runs.
how do we go about this?
simple solution which falshes on to our mind right now is
1)develop and enum haveing its members as run,sit and stand.
2) in the user class,have this enum.
3) when any command is performed on the user handle it in a function called ExecuteCommand. In this function have an if loop and check for the enum.

voila, we get the output !!!!
so where is the problem?
well, my character is still evolving in the game. so now i identify a new scenario where the character has to sleep.so, i have to modify the user class by adding a new new enum "sleep" and then modify the if condition.....dont you think this is bad????
tomorrow i can identify some new user actions, then again i have to modify this?
naaah..this will not do...
how can we do a proper design for this?
this is where we use the command pattern.
in this pattern we make each and every user action as a class.and this class will handle its own command and perform the action necessary.
i mean " encapsulate a command into an object".

see the example below

public interface ICommand
{
void Execute();
}

public class RunCommand : ICommand
{
#region ICommand Members

public void Execute()
{
Console.WriteLine("Run Command executed");
}

#endregion

}

public class StandCommand : ICommand
{
#region ICommand Members

public void Execute()
{
Console.WriteLine("Stand Command executed");
}

#endregion

}

public class User
{
public void Action(ICommand cmd)
{
cmd.Execute();
}
}

and when i call this:

User Character = new User();
ICommand cmd = new RunCommand();
Character.Action(cmd);

so i create an instance of the command needed and pass it on to the Action function.
and then the class (command class) performs the necessary action.

now of i want to add a new command - sleep?
all i need to do is create a new class called Sleep,implement ICommand.
then implement the function Execute.
a new action has been introduced.
not if i want the user ot perfrom this :

ICommand SleepCmd = new SleepCommand();
Character.Action(SleepCmd);

this will perform the necessary action.

HAPPY CODING!!!!

regards,
nandan

Thursday, November 15, 2007

FacadePattern - a centralised controller

hi,
been a long time since my last post eh?
sorry for that.
we shall discuss about a new design patter ntoday - Facade pattern
what exactly is a facade pattern?
technically speaking, it is a class which controls many other classes.something like a manager class.
let us take up a simple scenario :
i want to watch a movie at home..what all do i do?
1) i turn on the TV.
2) i turn on the speakers.
3) i turn on the DVD player
4) i turn off the lights

ok..so i have a class called user (that is me) which has to create instances of TV,DVD,Speakers,Lights and then on each of them call the start method. to switch off also its exactly same- we call the stop method. this is fine..no issues with this manner. but think of the user class, it has to maintain object references to the 4 classes. the user class may be very huge in itself. so we are increasing the burden on the user class. now if i have to have another class which has to perform the same 4 steps, tehn i have to have instances of these 4 classes again. and any new step included will change all the classes which perform these 4 steps.
so how can we make this more easier to manage? we will introduce a manager class in between..in this case "Remote" class.this will handle all the other 4 classes and perform the necessary steps.This is teh facade class.


advantages of using facade pattern are
1) the class (user class) which had to perform all the steps is not overloaded.
2) all the steps are maintained in a central location (Remote class).
look at the code sample below :

public interface IFacadeObject
{
void Start();
void Stop();
}

public class Remote : IFacadeObject
{
IFacadeObject DVDobj,SpeakerObj,LightObj,TVObj;
public Remote()
{
DVDobj = new DVD();
SpeakerObj = new Speakers();
LightObj = new Lights();
TVObj = new TV();
}
#region IFacadeObject Members

public void Start()
{
Console.WriteLine("Remote switched on");
TVObj.Start();
DVDobj.Start();
LightObj.Start();
SpeakerObj.Start();
}

public void Stop()
{
Console.WriteLine("Remote switched off");
TVObj.Stop();
DVDobj.Stop();
LightObj.Stop();
SpeakerObj.Stop();
}

#endregion
}




public class TV : IFacadeObject
{
public TV()
{

}

public void Start()
{
Console.WriteLine("TV switched on");
}

public void Stop()
{
Console.WriteLine("TV switched off");
}

}

public class AirCondition : IFacadeObject
{
public AirCondition()
{

}

public void Start()
{
Console.WriteLine("AirCondition switched on");
}

public void Stop()
{
Console.WriteLine("AirCondition switched off");
}
}

public class Speakers : IFacadeObject
{
public Speakers()
{

}

public void Start()
{
Console.WriteLine("Speakers switched on");
}

public void Stop()
{
Console.WriteLine("Speakers switched off");
}
}

public class DVD : IFacadeObject
{
public DVD()
{

}

public void Start()
{
Console.WriteLine("DVD switched on");
}

public void Stop()
{
Console.WriteLine("DVD switched off");
}
}

public class Lights : IFacadeObject
{
public Lights()
{

}

public void Start()
{
Console.WriteLine("Lights switched off");
}

public void Stop()
{
Console.WriteLine("Lights switched on");
}
}

This is our classes.
so when we call the "Remote" class instance, it will be doing all the necessary steps.
the call is made from the user class in this manner :

IFacadeObject RemoteObj = new Remote();
RemoteObj.Start();
Console.WriteLine("Things are working now ");
RemoteObj.Stop();

the output for this is

Remote switched on
TV switched on
DVD switched on
Lights switched off
Speakers switched on
Things are working now
Remote switched off
TV switched off
DVD switched off
Lights switched on
Speakers switched off


happy coding !!!!

regards,
nandan