Saturday, May 17, 2008

.Net Remoting Sample

DownLoad The Source Code

See Clip

Remoting is a technology that helps you to communicate between different applications regardless of whether they reside on the same computer or on different computers. Even these applications can have different operation systems.

Remoting needs:

1. A server object that expose the functionality to callers outside its boundary

2. A client that makes calls to the server object

3. A transportation mechanism to pass the calls from one end to the other

.Net Remoting system provides a number of services:

1. to activate objects

2. control the lifetime of each object

3. Transport message to and from remote objects using communication channels from client application to server application.

All objects in .Net divide to 2 groups

1. Remotable objects

2. NonRemotable objects

Remotable Objects:

There are two types of Remotable objects:

1. Marshal by Value objects: when these objects are created actually a copy of these objects will be send to client so actually object is sent to client. In .Net if you have a class that is serializable then it is marshal by value. To make a class serializable you should just add an attribute to the class [Serializable].

2. Marshal by Reference objects: When these objects are created they are actually stay in Server and client will connect to these objects. So a reference to server object exists in the client. In fact client application has another object which is called proxy. Proxy object is like server object. However, when proxy method is called it will pass that request to server object. Still client assumes that it is working with real object. In .Net classes that are inherited from MarshalByRefObject are in this category.

Other objects apart from these two categories are NonRemotable.

In .net Remoting marshal value objects are simple one because they are in context of client. Sometimes you cannot send copy of object to client and you need client call server object like applying business rule. Generally data objects (like dataset or business entities) have to be marshal by value and business objects have to be marshal by reference.

In .net Remoting Marshal by reference objects are more complicated since these objects are created in server. There are some concerns about them for instance When objects are created in server, When objects will be deleted, how long objects can leave in server so on so forth.

So let's have a look to marshal by reference concept and see different types of marshal by ref objects.

Activation

Before an object instance of a remotable type can be access it must be created and initialized by a process known as activation.

Different types of marshal by ref objects:

1- Server activation (in .net Remoting code it is called Wellknown)

2- Client activation (in .net Remoting code it is called Activated)

There are two types of server activation

1- Singleton: it means that there is just one object in server serving all clients and all requests. (if you understand web applications this kind of objects are like Application object in web)

2- SingleCall :it means that for each call from each client an object will be created and afterwards that object will be deleted immediately. (it is like webforms in web)

Client activation: for each instance of client and each instance that client create from server object there is a separate object in server (like session in web)

What is passed in Remoting between server and client?

1- URI : When Remoting activate an object give that object a URI to reference for all requests. For server activated the URI is in server application. On the other hand, for client activated Remoting will generate a GUID for the URI and maps it to remote object. So for client activation it is handled by Remoting.

2- Metadata: Remoting has to pass type information (it means it has to pass type of class)

3- Channel Information: Remoting needs to know from which channel can access the object.

Basics for coding .net Remoting

In .Net Remoting we have different types of channels (I will get back to this concept in next lessons) as you know in .Net Remoting we need a server application and a client application and a channel we usually register channel in server. There is a class named Remotingconfiguration that we use to register objects. This class has 4 type of Register

1-RegisterActivatedClientType

2-RegisterActivatedServiceType

3-RegisterWellKnownClientType

4-RegisterWellKnownServiceType

In these methods Activated means client activation and WellKnown means server activation and Service implies you are registering in server and Client implies you are registering in Client application

Time to Write Remoting code (Download the source Code)

Please follow these steps to write a Remoting code:

1- Create a class library name it Service : in class library you just have a class named Test

namespace Service

{

public class Test:MarshalByRefObject

{

public Test()

{

Console.WriteLine("New Object!");

}

public string PrintYourAddress()

{

string myaddress = AppDomain.CurrentDomain.BaseDirectory;

Console.WriteLine("This is myaddress " + myaddress);

return myaddress;

}

public void WriteInServer()

{

Console.WriteLine("I wrote time in server " + DateTime.Now.ToShortTimeString());

}

}

}

2- Create a console application name it Server: you have to write some code in Main method. You need to add System.Runtime.Remoting to your references. Furthermore you need to add Service library to this project.

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Http;

namespace Server

{

class Program

{

static void Main(string[] args)

{

HttpChannel ch = new HttpChannel(4000);

ChannelServices.RegisterChannel(ch);

//because this is written in server so we need to use Service type methods

RemotingConfiguration.RegisterWellKnownServiceType(typeof(Service.Test), "ServiceURI", WellKnownObjectMode.Singleton);

Console.WriteLine("Server is Started...");

Console.ReadLine();

}

}

}

3- Create a windows application name it Client: First of all you need to add reference service. Add two buttons and in button clicks add these code also you need to add some code in FormLoad event

Test t;

private void Form1_Load(object sender, EventArgs e)

{

System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownClientType(typeof(Test), "http://localhost:4000/ServiceURI");

t= new Test();

}

private void button1_Click(object sender, EventArgs e)

{

t.WriteInServer();

}

private void button2_Click(object sender, EventArgs e)

{

string str = t.PrintYourAddress();

MessageBox.Show(str);

}

4- First run client application if you click on any of buttons you should see an error because the server is not running. So you need run server then client that should be fine for more detail information please see the movie

See Clip

Learn more about .Net Remoting (Activator sample)

13 comments:

Nahid said...

It was EXCELLENT!
Thanks for time dedicated for clips, they are big helps.
I'm eagerly waiting for more articles on remoting.

AMirAli said...

Dear Emad

You make it really simple, and cause of that there is a problem in code.
You destroyed the meaning of remoting object in your example.
What is the reason of having remot object when you create direct access to Assembly. I mean, when serve and service Dll site in a same place, to me there is no reason to have remoting. you add "Service" assembly as a referenc to server and to me this destroy the meaning of remoting.

I kbnow, it happen because you would like to make it easy to understand.

AMirAli said...

My Writting Mistake
Correction: Change "Server" word to "Client"

Cheers

Emad Yazdanpanah said...

Hi Amirali,

Remoting allows you to create objects in different application. remoting goal is just creating object in another Application domain. If our architecture implies that our client should not be allowed to see metadata of business this is completely different to what Remoting offers. However in most cases as you mentioned we really need to offer an interface to client not the whole business metadata. This is the first example of Remoting if you listen to clip I mentioned that this is a good start. To answer your question I should mention that there are 3 ways to restrict client.
1- Having a library between client and server that does not have the business rule but just call the business rule (I do not suggest this approach)
2- having 2 libraries that are exactly the same but in one of them all methods return an exception even constructor (it takes time implementing this way also it is highly error porn)
3- Using Activator object that I am going to discus about this approach in next lesson of Remoting.

It seems that you are really in hurry!

Emad Yazdanpanah said...

Dear Amir Ali,
I forgot to mention that in remoting even when the service is in client space when you create an object the object is created in server so you need the service metadata not to create object!
I hope you understand this otherwise you are mixing up metadata with objects!

Anonymous said...

Hi Emad. You have Valuable experiences in development.
Im a big fan of your blog.
thanks emad.

AMirAli said...

Thanks Emad for quick response.
I know what you mean, but my objective was about having DIRECT reference to Service Assembly in client application “When you can create object directly what is the reason of REMOTING”. Regards to things you taught me couple years ago actual class is not a good idea to role as a metadata. Instead we can use interfaces and etc.
Cheers

Emad Yazdanpanah said...

You asked me "When you can create object directly what is the reason of REMOTING"

the reason is that we want that object in server. Remoting is just for this. If we need to hide business logic from client it is nothing to do with Remoting concept. However, I explained before that this is the first sample of delegate and I make this always my first sample because of exactly this question that you raised. I want you understand remoting means that even you have the service library in client it will not use this library to create object just it will be used as metadata then client based on that metadata will create proxey object.
So I hope you understand not only this sample did not destroy the remoting concept but also it cleared what is remoting for which is creating object in server.
In next lessons as I said before you will learn how you can deal with this issue. you will see that we do not allow client to see the real service we will give client just an interface or a fake library.
Again I hope you understand we are going to create object in server. Not in client. The main purpose of Remoting is creating object in server rather than hiding libraries!

AliBZ said...

salam agha emad
vaghean dastetoon dard nakone. aali bood. ham clip, ham sample code.
thanx alot ;)

Anonymous said...

hi dude,

it's really help for me thanx dude.....................

Phan Duy Anh said...

You wrote all I need. Thank you a lot!!!

Bismark said...

That one really put everything in order. Thanks.

Anonymous said...

Thanks for the tutorial, I don't know how you managed to explain remoting concept in very lucid way. Your code works too. Thanks a lot