Remoting
Application Architecture’s: Every
application contains 3 different parts in it like:
1. UI Part 2. Logic Part (BL + DL) 3. Data Source Part
-Organizations
as per their requirement adopts diff architecture's for execution of their
applications those are:
1.
Single Tier Architecture: in this model all the
3 parts (UI + Logic + DB) will reside on the same machine to execute, so as the
DB is also present on every machine changes made on 1 machine will not be
reflected to the other.
2.
2-Tier
Architecture: in this model the (UI+Logic) sits on all the client
machines, moving the DB to a centralized location, so all the clients connect
with the same DB Server to store & access data. In this model changes made
on 1 machine reflects to the other.
3.
3-Tier or N-Tier Architecture: in this model all
the 3 parts will sit on 3 diff. machines to execute, on the client machine what
we have is only light weight client (UI) which will connect with the logic part
residing on server machine that will in turn connect with the DB Server.
Maintainance of the software becomes easier in this model when there were more
no. of client accessing the application.
To develop a
3-Tier application in desktop model we have various distributed technologies
like:
-RPC (Remote Procedure Call)
-CORBA
(Common Object Request Broker Architecture)
-RMI
(Remote Method Invocation (Java))
-DCom
(Distributed Component Object Model)
-Remoting
(.Net Languages)
Remoting
is a technology from Microsoft for developing distributed applications
replacing traditional DCOM available under COM. -All the distributed
technologies speak about the same i.e. consuming of libraries present on remote
machines. In .Net libraries were implemented as Assemblies, where we can
consume an assembly residing on local machine by adding its reference. We can
now consume Assemblies residing on remote machines also using Remoting.
Developing Remoting
Application: To develop a Remoting
Application first we need to understand various things regarding the process of
communication, those are:
1. Serialization
De-Serialization:
-To exchange information between both the parties they make use of a
process known as Serialization and De-serialization. As applications represent
the data in High Level (Object Format) which are not free flowable, needs to be
converted into Low Level (Binary or Text) and then transferred to the other
system where on the target machine Low Level data has to be converted back into
High Level.
-Serialization is a process of converting high level data to low level
and De-Serialization is in opposite of serialization that converts low level
data to high level.
-To perform serialization & deserialization remoting provides
Formatter Classes, those are:
-Binary
Formatters: -TCPServerChannel -TCPClientChannel
-Soap Formatters: -HttpServerChannel -HttpClientChannel
-Binary Formatters are used for binary serialization and
de-serialization & Soap Formatters are used for text serialization and
de-serialization.
Note: traditional DCOM supports only binary.
2. Marshalling and UnMarshalling:
-After serializing the data which has to be sent to the target machine
it packages the data into packets this is what we call as marshalling, at this
time it associates the IP Address of the target machine where the information
has to be sent. UnMarshalling is in opposite to Marshalling which opens the
packets of data for de-serializing.
IP-Address: Every system in a network is
identified by using a unique id known as IPAddress. It is a 4 part numeric
value where each part will be ranging between 0-255. eg:
0-255.0-255.0-255.0-255
-We can mask IP Address of a system by specifying an alias name to it
known as HostName. Systems under a network will be configured as following:
IPAddress HostName
192.168.26.0 (nit0)
......
192.168.26.24 (nit24)
3. Activation Models:
-In execution of Remoting application clients needs object of remote
class to invoke methods under it. Activation Models decide where the remote
class objects resides in execution of the application.
-Remoting supports 2 different activation models:
-Server Activated
Objects (SAO) -Client
Activated Objects (CAO)
-In SAO model object of remote class resides on server Machine and a
reference of this object is maintained on the client machine using which
clients can invoke the methods of remote class.
-In CAO model the object of remote class resides on client machine
using which clients can invoke the methods of remote class.
Server Activated Objects: in SAO model we were again provided with 2 types
like singleton & singlecall.
- SingleTon:
-In this case whenever a first request comes from a client an object
of remote class gets created and it's reference is given to the client, from
then every new request coming from a new client, server provides the reference
of same object which is already created, so changes made by 1 client gets
reflected to the other. Used in the development of application like public
chat, cricket scores, share prices etc.
- SingleCall:
-In this mode whenever a request comes from a client 1 object of
remote class gets created and it's reference is given to client, once the
request is served immediately object gets destroyed without allowing him to
make any other requests on that object, for a new request a new object gets created
again and destroyed. Used in the development of single request app like
"Railway PNR Status Enquiry", "ATM Machines" &
"Examination Results".
Note: this
is very highly secured model used in app development.
Client Activated Objects:
-In this case whenever the first request
from a client an object of remote class is created and provided using which the
client can make any no. of requests. Here a separate object will be given for
each client so changes made by 1 client will never reflect to the other. Used
in the development of applications that requires multiple requests for a single
client like "Traditional ATM Machines", where we can perform multiple
transactions once we insert the card.
4. Server:
-When we want to develop an application to be consumed from remote
machines we require someone to take the request from clients. To take a request
from client we use server software’s, which works on the principles request and
response. We can install multiple server software’s on a machine, but each server
should be running on a separate logical address known as port.
-In process of developing remoting application it is our
responsibility to develop a server that takes requests of clients to the Remote
Class, because a class is not capable of taking the request. The server should be
running on a unique port of the OS. By default every machine has port's that
are ranging between 0-65535 in which 0-1023 were OS reserved ports, rest can be
used by any application.
-After developing a Remote Server every Remote
Class on the machine has to be registered under the Server with an alias name,
so that clients can send their request to required class.
5. Remote Interface:
-In remoting the methods what we want to define under Remote Class,
that are accessible to clients should be first declared under an interface
& then implemented in remote class which was a rule.
-The same interface will also be provided to clients that act as a
Proxy to Remote Class on client machine, which will be used in 2 ways:
1. Using it clients can recognize
methods of remote class.
2.
Using it we can hold reference of remote class on client machines.
Execution of a Remoting
Application:
1. Client sends a request to server.
2. Server creates object of Remote Class.
3. Sends reference of that object to client which has to be captured
under interface variable.
4. After capturing, the variable gets converted into reference pointing
to the object on Server.
5. Now UI can invoke methods on the reference.
6. Methods get executed on server machine as
the reference points to object on server.
-To develop a Remoting Application we
require the following:
1. Interface (Class Library) 2.
Remote Class (Class Library)
3. Remote Server (Windows Service) 4. Client (UI) (Windows or Console
Application)
Developing an Interface:
-Open a new project of type class library & name it as
InterfaceProject. Delete the Class1.cs file under the project and add an
Interface to the project naming it IRemoteApp.cs, and write the following code:
public interface IRemoteApp { string
Get_Sname(int sno); decimal Get_Bal(int custid); string SayHello();
}
-Now
open solution explorer and build the project which generates an assembly
InterfaceProject.dll.
Developing a Remote Class:
-The RemoteClass needs to be inherited from the predefined class
MarshalByRefObject & implement all the methods that were declared under
interface.
MarshalByRefObject should be the base class for objects that communicate
across application domain boundaries by exchanging messages using a proxy in
applications that support remoting.
-Open a new project of type class library and name it as ClassProject,
rename the class Class1.cs as ClsRemoteApp.cs using Solution Explorer. Add
reference of InterfaceProject.dll we have created previously & write the
following code:
using
InterfaceProject; using System.Data.SqlClient;
public class
ClsRemoteApp : MarshalByRefObject, IRemoteApp {
SqlConnection con; SqlCommand cmd; int x = 0;
public
ClsRemoteApp() {
con =
new SqlConnection("<con str>“); cmd = new SqlCommand(); cmd.Connection
= con;
}
public
string Get_Sname(int sno) { string
name = null;
try {
cmd.CommandText = "Select Sname
From Students Where Sno=" + sno;
con.Open();
name = cmd.ExecuteScalar().ToString();
}
catch
(Exception ex) { ex = null; } finally { con.Close(); } return name;
}
public decimal Get_Bal(int custid) { decimal bal = 0;
try { cmd.CommandText = "Select Balance From Customer
Where Custid=" + custid;
con.Open();
bal = Convert.ToDecimal(cmd.ExecuteScalar());
}
catch
(Exception ex) { ex = null; } finally { con.Close(); } return bal;
}
public string SayHello() { x += 1; return "Hello: "
+ x;
}
public
string Demo() { return "Not
accessible to remote clients";
}
}
-Now
open solution explorer and build the project to generate an assembly
ClassProject.dll
Process to develop a RemoteServer:
-If you want to develop a remote server that
should be started along with OS, develop it as a windows service. A Windows
Service is an application which runs in the background process without any
knowledge to end users they will be under control of OS and gets started when
OS is started & stopped when we shutdown the system. DB’s & Web Servers
will be implemented as Windows Services only. Every system by default has no.
of services installed on it; you can view the Services that are present on a
machine making use of Services Window as following: Start -> Settings ->
Control Panel -> Administrative Tools -> Services.
-Every service will have 4 attributes to it, those are:
1. Display Name: It is the name for identification.
2. Description: It is brief information about the
service.
3. Startup Type: It decides how a service gets
started on the machine, which can be set with 3 options:
-Automatic starts the services at system logon.
-Manual starts a service as required or when
called from an application.
-Disabled completely disable the service and prevent
it and its dependencies from running.
4. LogOnAs (Account): Indicates the account type under which the
service runs, can be set with 3 options like User, Local System and Network
Service.
Note: While developing an windows service it
is our responsibility to set all the above 4 attributes.
-How to develop a Windows Service?
-If we want to develop a windows service we can make use of
"Windows Service" Project template under VS. To choose Windows
Service project template, under new project Window expand the Language node i.e.
Visual C# in the LHS panel and select the option Windows which displays Windows
Service template on RHS panel.
-Every Windows Service Class is a sub class of pre-defined class
ServiceBase present under the namespace System.ServiceProcess. In a Windows
Service code has to be written under few overridden methods like OnStart,
OnStop, OnPause, OnContinue etc., which were declared as virtual under parent
class ServiceBase. Code under OnStart executes when service is started, OnStop
executes before the service is getting stopped, OnPause executes when the
service is paused, OnContinue executes when the service is resumed.
-After writing code in a service class we
need to set the 4 attributes discussed previously, for this, under the project
we are given with "Add Installer" option using which we can set the
attributes. Once we build the project it will generate an exe assembly that
should be installed on a machine by using "installutil" tool. Once
the service is installed we can view this under Services Window.
Developing Remote Server:
-Open a New
Project of type Windows Service and name it as RemoteServer.
-Add
reference of 3 assemblies to the project:
1. System.Runtime.Remoting.dll (.net)
2. ClassProject.dll (browse) 3. InterfaceProject.dll (browse)
Write the following code in Code View:
using
System.Runtime.Remoting; using System.Runtime.Remoting.Channels;
using
System.Runtime.Remoting.Channels.Tcp;
Under OnStart Method:
TcpServerChannel
chan = new TcpServerChannel(5000);
ChannelServices.RegisterChannel(chan,
true);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(ClassProject.ClsRemoteApp),
“XXX", WellKnownObjectMode.Singleton);
-Now go to design view of the project, right
click on it & select Add Installer which adds 2 components
ServiceInstaller1 & ServiceProcessInstaller1 using which u need to set the
4 attributes of service. Under
serviceInstaller1 Properties set following: 1.
DisplayName: RemoteServer 2. Description: Takes request from remote clients 3.
StartupType: Automatic and under serviceProcessInstaller1 Properties set Account
property as “Local System” & build the Project which creates an assembly
RemoteServer.exe.
Installing the service on your
machine: To Install the service on a machine we were given with a command
line utility "installutil", which has to be used as following: Installutil [-u] <service exe name>
Note: To un-install an
installed service use the “–u” option.
-Open VS Command Prompt and go into the location where
RemoteServer.exe is present and write the following: C:\<folder>\RemoteServer\RemoteServer\bin\Debug>installutil
RemoteServer.exe
-Now we can find our service under Services
Window, right click on it & select start which will start the server. To
check server running or not, open VS Command Prompt and use the statement "netstat
-a".
To develop remote server we
follow the below process:
Step 1: Create an object of
TcpServerChannel or HttpServerChannel by passing port no as argument to the
constructor.
System.Runtime.Remoting.Channels.Tcp.TcpServerChannel(int port)
System.Runtime.Remoting.Channels.Http.HttpServerChannel(int port)
Step 2: Register the channel
under OS using RegisterChannel static method of ChannelServices class.
System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(Channel
obj, bool security)
true - secured; false - unsecured
Step 3: Register the remote
class under remote server with an alias name using the static method
RegisterWellKnownServiceType of the class RemotingConfiguration.
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(
Type type, string alias, Mode mode)
Note:
Mode can be SingleTon or SingleCall
Developing the Client (UI): under client
application we perform the following:
Step 1: Create object of appropriate
client channel class which doesn't require any port no.
Step 2: Register the channel under OS.
Step 3: Send request from client
to remote server requesting for reference of Remote Class using the static
method GetObject of Activator class present under System namespace.
Activator.GetObject(Type type, string url) -> Object
URL: Uniform Resource Locator Format:
<protocol>://<hostname>:<port>/<requestfor>
e.g.: http://www.yahoo.com:80/index.htm tcp://<server name>:5000/XXX
Step 4: Server takes
request & provides reference of RemoteClass to client in object format as
return type of GetObject method is object. eg: Object obj = Activator.GetObject(<type>,
<url>)
Step 5: Now client needs to
convert reference of Remote Class present in object format to Interface format. eg: IRemoteApp ira = (IRemoteApp)obj;
Step 6: Now using the reference invoke
methods of Remote Class that executes on server machine only.
Developing Client Application (UI):
-Open a new
project of type windows, name it as RemoteClient & create the form as
following:
Write the below code by adding reference of
following assemblies:
1.
System.Runtime.Remoting.dll (.net) 2. System.Configuration.dll (.net) 3.
InterfaceProject.dll (Browse)
-Add an "Application Configuration File" under the project
using "Add New Item" window and write the following between
<configuration> & </configuration> tags:
<appSettings> <add key
="URL" value ="tcp://server:5000/XXX"/> </appSettings>
using
InterfaceProject; using System.Configuration;
using System.Runtime.Remoting.Channels; using
System.Runtime.Remoting.Channels.Tcp;
_____________________________________________________________________________________
Declarations:
IRemoteApp ira;
Under Form Load:
string url = ConfigurationManager.AppSettings.Get("URL");
TcpClientChannel chan = new TcpClientChannel(); ChannelServices.RegisterChannel(chan,
true);
Object obj = Activator.GetObject(typeof(IRemoteApp), url); ira
= (IRemoteApp) obj;
Under Call SayHello Button: button1.Text = ira.SayHello();
Under Call Get_Sname Button: button2.Text = ira.Get_Sname(int.Parse(textBox1.Text));
Under Call Get_ESal Button: button3.Text = ira.Get_Bal(int.Parse(textBox2.Text)).ToString();
Execution of the Application:
-As our Remote Server is a windows service
it gets started automatically when ever OS is started.
-Now run the Remote Client application we
have developed & test it. Once it was working perfectly prepare a set-up
for the application which includes RemoteClient.exe, ConfigFile &
InterfaceProject.dll which can be carried & installed on any systems in the
network. To run client application on a machine, first open the config file,
edit the "URL" and then start the application.
Singleton Vs Singlecall:
-Right now remote class is registered under remote server in singleton
mode, in this mode whenever the first request comes from first client an object
of remote class is created and it's reference is provided to the client, from
then for any new request coming from a new client, server provides reference of
same object that is already created, so all clients share same object memory because
of this changes made by 1 client gets reflected to others. To change mode of
application from Singleton to Singlecall follow the below process:
- Open visual studio command prompt, go into the folder
where RemoteServer.exe was present & Un-install it using installutil
tool. Eg: installutil -u
RemoteServer.exe
- Now open RemoteServer project in VS & under it change the mode from Singleton to Singlecall with in the 3rd statement of OnStart method and rebuild the project.
- Re-install RemoteServer from VS Command Prompt again. Eg: installutil RemoteServer.exe
- Open the service's window and start the server for first time.
- Now run the client application again to check the difference in results.
------------------------------------------------------------------------------------------------------------------------------------------
Developing a COM Component:
COM Components can be developed using various languages like classical
VB, C++ & VCPP. To develop a COM Component in Classical VB go to Start Menu
-> Programs -> Microsoft Visual Studio 6.0 -> Microsoft Visual Basic
6.0 -> click on it which shows "New Project" window -> select
ActiveX Dll (Class Library in .Net) project template -> click on open which
displays the code window. Goto View Menu -> select "Project
Explorer" which launches the explorer on RHS -> right click on the node
Project1 -> select properties which opens a window -> under that change
the "Project Name" as COMProject -> click Ok. Now right click on
Class1 node -> select properties -> change the name as "Test".
Now in code window write the following:
Public
Function SayHello() As String
SayHello = "Hello from COM"
End Function
Note: classical VB language doesn't support return stmt so the value
which has to be returned should be assigned to name of the function which will
return the value.
-Go to File Menu -> select Save Project -> specify a location to
save the project. E.g.: C:\CSharp9\VB
-Go to File Menu -> select Make
'COMProject.dll', which will compile, generate a dll and registers it under
windows registry because COM Components were not functional unless they were
registered under windows registry. Close the Studio.
Consuming COM Components from .Net Applications:
If we want to consume a COM Component from .Net Applications first it
should be converted into RCW which can be done in 2 ways:
-Using Visual Studio.Net -Using tlbimp utility
Using Visual
Studio.Net:
-Open a new .Net project of type Windows & name it is as TestCom,
place 3 buttons on the form & set Text as "Call SayHello of
COM1", "Call SayHello of COM1", & "Call SayHello of
COM1". Now open "Add Reference" window, select COM tab &
under it we can find our Component COMProject.dll we have created, select it
and write the following code under click of first button:
COMProject.Test obj = new COMProjec.TestClass();
MessageBox.Show(obj.SayHello());
-Run the
project, test it & then go into debug folder of current project where
we can find the RCW created by VS as
"Interop.COMProject.dll". The above process is simple & easy but
the RCW created here is private which maintains multiple copies if used under
multiple projects.
Using tlbimp Utility:
-VS is
capable of generating RCW of type private only where as tlbimp is capable of
generating both private & shared RCW's. To create an RCW Or CCW we were provided
with 2 command line utilities:
1. tlbimp (Type Library Importer): for converting a COM component into
RCW
2. tlbexp (Type Library
Exporter): for converting a .net assembly into CCW
-These were
command line utilities which should be used from VS Command Prompt as
following:
tlbimp <name of com dll>
/out: <name of .net dll> [/keyfile: <name of key file>]
Creating a Private RCW:
C:\CSharp9\VB> tlbimp COMProject.dll /out:ComToNetP.dll
Creating a Shared RCW:
Step 1: Generate a key file
Eg: C:\CSharp9\VB>
sn -k Key.snk
Step 2: Convert to Shared RCW
Eg: C:\CSharp9\VB>
tlbimp COMProject.dll /out:ComToNetS.dll /keyfile: Key.snk
Step 3: Add the RCW to GAC
Eg: C:\CSharp9\VB> gacutil -i
ComToNetS.dll
-Now add the
reference of both the RCW's we have created (ComToNetP.dll & ComToNetS.dll)
from their physical location, then write the following code under remaining 2
buttons:
Under Second Button:
ComToNetP.Test obj = new ComToNetP.Test();
MessageBox.Show(obj.SayHello());
Under Third Button:
ComToNetS.Test obj = new ComToNetS.Test();
MessageBox.Show(obj.SayHello());
Using tlbexp utility:
This is used to converts a .Net assembly into CCW,
which is in opposite to tlbimp.
tlbexp <name of .net dll>
/out:<name of com dll>
Note: after
creating CCW it cannot be used directly under any system as it was a COM
component, it first requires registration on windows OS which has to be done
using regsvr32 stmt as following:
syntax: regsvr32 <name of com
dll>
No comments:
Post a Comment