SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
3       DotNET Remoting
Lecture:             [Link]
Tutorial (Part 1):   [Link]



3.1 Introduction
.NET remoting is a technology which allows objects to be placed remotely across a
network, where the object can be activated, and communicate with local objects us-
ing a communications channel. A formatter is then used to encode and decode the
messages as they pass between the remote object and the application. The format of
these message can either be:

   Binary encoded. This is used where performance is a critical factor.
   XML encoded. This is used when interoperability is important, and uses the
    standardized SOAP protocol.

A key element of .NET remoting is that objects can check the messages that are to be
sent before they are sent to the channel, and the remote objects are activated in dif-
ferent ways, these are:

   Client-activated objects. These have a finite lease time, and once their lease has
    expired, they are deleted (using the garbage collector).
   Server-activated objects. These can either be defined with a single call or with a
    singleton. A single call accepts one request from a client, then performs the ac-
    tion, and is finally deleted (with the garbage collector). It is defined as stateless,
    as it does not hold onto parameters from previous calls. Singletons are stateful
    and can accept multiple calls, where they remember previous calls, and retain
    their information. They can thus communicate with multiple clients. Also the
    lifetime of singletons is controlled by lease-based lifetime.


3.2 Application boundaries
Microsoft Windows allows applications to run on virtual machines, where applica-
tions should not interfere with each other. Thus, a fault in one application should
not affect another one. Each application thus has its own code and data area, which
should not be accessed by other applications running on the machine. A process
boundary is one which isolates a process from others which are running. It is neces-
sary that each process can run in its own virtual space, and gain access to as much
memory that they require. Other processes should not be able to interfere with this.
If a process crashes, it should not affect other processes. .NET expands on this by
apply this managed environment onto applications. This is because .NET uses the
Common Language Runtime (CLR - Figure 3.1) which is a managed environment
for executing code, code access security, object management, debugging, cross-
language integration, and profiling support. In standard Windows applications it is
not possible to provide a degree of safety that an application does not step outwith
its boundaries, as Windows applies process control boundary, rather than an appli-
cation boundary. In .NET an application domain is created with the AppDomain
class with the System namespace. Thus the application boundary ensures that:

   Each application has its own code, data and configuration settings.
   No other application can interfere with any other applications.

It is thought that application switching for processor time is more efficient than
processor switching. Along with this, it is easier to monitor the operation of an ap-
plication than it is to monitor a number of processes.


                                                 VB .NET
                                                  VB .NET                C#
                                                                          C#



                                FCL
                                 FCL
                            (Framework
                             (Framework                                             CLS
                                                                                     CLS
                           Class Library)                   Compiler             (Common
                                                                                  (Common
                           Class Library)                   Compiler             Language
                                                                                  Language
                                                                               Specification)
                                                                                Specification)
                                 Web
                                  Web
                              component
                               component


                 CTS
                  CTS
               (Common
                (Common                                     MSIL (Microsoft
                 Type
                  Type                                      Intermediate Language)
                System)
                 System)


                                       CLR (Common Language Runtime)
                                       CLR (Common Language Runtime)
                      Allows the programs to run – similar to the Java Virtual Machine (JVM)
                      Allows the programs to run – similar to the Java Virtual Machine (JVM)



                                      Figure 3.1: .NET Framework



3.3 Distributed Systems
Distributed systems allows resources to be distributed around a network, rather
than tying them to a specific host. These resources could relate to hardware and
software resources. This allows for less centralized approach, and typically im-
proves the robustness of a system and also makes improved usage of network
traffic. For example an organisation might use a centralized Web server for their
document management. This has the advantage is that it is relatively easy to man-
age, but it becomes a centralized point of failure, also the network traffic is likely to
be relatively large towards the server. Along with this the CPU usage it likely to be
relatively large.
     An improved system would be to distribute Web servers around the network,
and for hosts to access them on a local level. This type of approach can be scaled
down to an object-level, where objects can be distributed around a network, either
outwith the application domain, or outwith the host. These objects could reside on




W.Buchanan                                                              Unit 3 - .NET Remoting 2
different types of operating systems or system types and thus allow applications to
run over heterogeneous systems.
     Another similar approach is to develop applications which is made of intercon-
nected components. These components make it easier to design software, where
tasks are split into elements. The distribution of components allows for the stan-
dardization of components, which could run remotely. For example a component
which does a grammar checker could be standardized and when an application re-
quires a grammar checker it calls it up remotely, and uses it.
     In general distributed systems are generally more scaleable, more robust, and
increase availability of services. The most common distributed protocols are RPC
(Remote Procedure Calls), Microsoft Distributed Object Model (DCOM), Common
Object Request Broker Architecture (CORBA) and Java Remote Invocation (RMI).
These are typically applied to certain types of environments, such as DCOM on
Windows-based systems and RPC in a UNIX environment. Some of these are legacy
type systems which were designed to be simple, and have never really kept up-to-
date with modern methods, especially related to security. The .NET framework
hopes to produce a new standard for distributed applications.
     The main namespaces used for .NET Remoting include:

   System.Net. This includes classes relating to the networking elements of the dis-
    tributed system.
   System.Runtime.Remoting. This includes classes for the remote aspects of the
    .NET framework, such as mechanisms for remote communication between ob-
    jects.
   System.Web.Services. This includes protocols relating to Web services, such as
    those relating to HTTP and SOAP. This is defined as the ASP.NET Web services
    framework.


3.4 Remote Objects
.NET remoting provides a simple mechanism to call remote objects, where a remote
object is any object which is outside the application domain, and can thus also be
local on the same machine. Within an application domain, the object is passed by
reference, whereas primitive data types are passed by value. Obviously it is not
possible to pass an object from a remote object by reference since the reference to the
object is only valid on the side which contains the object (that is, they only have lo-
cal significance). For an object to be passed over an application domain, they must
be passed by value, and also serialized (that is, send over a single communications
channel). This, thus, defines the structure of the object, and also its contents.
   The process of communicating between objects and transferring them over an
over application boundaries is known as marshalling. Objects are converted into
remote objects when they derive from MarshalByRefObject. Then, when a client
activates the remote object, it interfaces with a proxy for the remote object, as illus-
trated in Figure 3.2. The proxy object acts on behalf of the remote object, and, as
previously mentioned, is created when the client actives a remote object. Its main



W.Buchanan                                               Unit 3 - .NET Remoting 3
objective is to make sure that all the messages sent to the remote object are sent to
the correct instance of the object.

          Client application domain                     Server application domain




             Client object
                                                              Remoteable object
                                                                 (object.dll)

                                                               ShowCapital()
                Proxy




              Remoting                   Channel                 Remoting
               System                                             System



                                       Serialisation

                                  Figure 3.2: .NET remoting

On the remote machine, the remote object is initially registered into an application
domain. The MarshalByRefObject is then used to encapsulate all the information
required to locate and access the remote object, such as its class name, its class hier-
archy, its interfaces and its communication channels. Activation occurs using the
URL, and identifies the URI (Unique Reference Identifier) of the remote object.
   A MBR (Marshal-by-reference) always resides on the server, and the methods are
executed on the server, while the client communicates with the local proxy. The fol-
lowing shows an example of the ShowCapital class which derives from the
MashalByRefObject, and contains a show() method.

   public class ShowCapital : MarshalByRefObject
   {
      public ShowCapital()                                              Derive from
      {
      }                                                                 MarshalByRefObject
      public string show(string country)
      {
      }
   }


The MarshalByValue (MBV) involves serializing values on the server, and sending
them to the client. An MBV object is declared by a class with the Serializable attrib-
ute, such as:

[Serializable()]
public class NewMBVObject
{
}




W.Buchanan                                                    Unit 3 - .NET Remoting 4
3.4.1    Channels
Remote objects transfer messages between themselves using channels. These chan-
nels are thus used to send and receive objects, as well as sending information on the
methods that require to be called. Each object must have at least one channel set up
for this communication, and the channel must be registered before a remote object is
called. Once the object is deleted, the channel which it uses is also deleted. Also the
same channel cannot be used by different application domains on the same ma-
chine. These channels map onto TCP port numbers, and the application must be
sure that it does not use one which is currently being used.

3.4.2    HTTP and TCP channels
Messages which are transferred by the SOAP protocol use an HTTP channel,
whereas a TCP channel uses a binary format to serialize all message. In the HTTP
channel, all the messages are converted into an XML format, and serialised (along
with the required SOAP headers). The namespaces are:

System.Runtime.Remoting.Channels.HTTP           for HTTP
System.Runtime.Remoting.Channels.TCP            for TCP

For example to create a client connection to a server port of 1234:

         TcpChannel channel = new TcpChannel(1234);
         ChannelServices.RegisterChannel(channel);


The HTTPChannel can be used for a wide range of services which are hosted by a
Web server (such as IIS). It has security built into it, but has an overhead of extra
information (as it works at a higher level than TCP). The TCPChannel is more effi-
cient in its operation, but does not have any security built into it.

3.4.3    Activation
A key element of the .NET remoting framework is that it supports the activation of
remote objects as either a client or a server. Server activation is typically used when
remote objects do not required to maintain their state between method calls, or
where there are multiple clients who call methods on the same object instance
where the object maintains its state between function calls. In a client-activated ob-
ject, the client initiates the object and manages it for its lifetime.
   Remote objects have to be initially registered with the remoting framework be-
fore the clients can use them. This is normally done when a hosting application
starts up and then registers one or more channels and one or more remote objects. It
then waits until it is terminated. When the hosting application is terminated, the ob-
jects and channels are deleted. For an object to be registered into the .NET remoting
framework the following need to be set:

   Assembly name. This defines the assembly in which the class is contained in.
   Type name. This defines the data type of the remote object.
   Object URI. This is the indicator that clients use to locate the object.




W.Buchanan                                               Unit 3 - .NET Remoting 5
   Object mode. This defines the server activation, such as SingleCall or Singleton.

Remote objects are registered using the RegisterWellKnownServiceType, by passing
the required parameters into the method, such as:

         RemotingConfiguration.RegisterWellKnownServiceType
            (typeof(newclass.ShowCapital),
            "ShowCapital1", WellKnownObjectMode.SingleCall);


which defines a SingleCall remote object, and the ShowCapital object, which is
within the newclass namespace. ShowCapital is thus the name of the object, where
the ShowCapital1 is the object URI.
   It is also possible to store the parameters in a configuration file then using Con-
figure with the required configuration file, such as:

         RemotingConfiguration.Configure("myconfig.config");

where the configuration file could be in the form of:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.runtime.remoting>
      <application>
         <service>
            <wellknown mode="Singleton" type="newclass.ShowCapital, newclass"
                  objectUri="ShowCapital1" />
         </service>
         <channels>
            <channel ref="tcp server" port="1234" />
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>


This method has the advantage that it does not need to be compiled with the appli-
cation, and can therefore be edited as required, and will be read in as required. Thus
a change of parameters, such as a change of object name does not require a recom-
pilation.
   Once registered, the remote object will not instantiate itself, as this requires the
client to initiate it, or call a method. This is achieved by a client which knows the
URI of the remote object and by registering the channel it prefers using GetObject,
such as:

         TcpClientChannel channel = new TcpClientChannel();
         ChannelServices.RegisterChannel(channel);
         ShowCapital sh= (ShowCapital)
             Activator.GetObject(typeof(newclass.ShowCapital),
            "tcp://localhost:1234/ShowCapital1");


where:

 “tcp://localhost:1234/ShowCapital1”. Specifies that the end point is ShowCapital
   using TCP port 1234.




W.Buchanan                                              Unit 3 - .NET Remoting 6
Along with this, the compiler requires type information about the ShowCapital class
when this client code is compiled. This can be defined with one of the following:

    With a reference to the assembly where the ShowCapital class is stored.
    By splitting the remote object into an implementation and interface class and
     then use the interface as a reference when compiling the client.
    Using SOAPSUDS tool to extract metadata directly from the endpoint.
     SOAPSUDS connects to the endpoint, and extracts the metadata, and generates
     an assembly or souce code that is then used in the client compilation.

Another method is

          RemotingConfiguration.RegisterWellKnownClientType(
             typeof(ShowCapital),
             "tcp://localhost:1234/ShowCapital");


None of these calls actually initiates the remote object, as only a proxy is created
which will be used to contact the object. The connection is only made when a
method is called on the remote object. Once this happens, the remote framework
extracts the URI, and initiates the required object, and forwards the required
method to the object. If it is a SingleCall, the object is destroyed after the method has
completed.


3.5 Applying .NET Remoting
The following sections show a remote objects are initiated and then how they can be
used to communicate between a client and a server.

3.5.1     Creating a remotable class
The following steps shows how a remote class is created (Figure 3.3). These are:

1.      Create a new blank solution (named NetRemoting1).
2.      Add a new class library (for example, named newclass). Select Add New Pro-
        ject, then select Class Library, as illustrated in Figure 3.3.
3.      Add System.RunTime.Remoting.dll as a Reference (if required).
4.      Change the name of the class file to a new name (for example, ShowCapi-
        tal.cs).
5.      Add the following code:

       C# Code 3.1:
using System;
using System.Data;

namespace newclass
{
    public class ShowCapital : MarshalByRefObject
    {
        public ShowCapital()




W.Buchanan                                                Unit 3 - .NET Remoting 7
{
        }
        public string show(string country)
        {
            if (country.ToLower() == "england") return ("London");
            else if (country.ToLower() == "scotland") return ("Edinburgh");
            else return ("Not known");
        }
    }
}


and the results are shown in Figure 3.5. This produces a class named ShowCapital,
which has a method of show(). This class, once built, produces a remotable class in
the form of a DLL file, which is placed in the binDebug folder. In this case it will
create a DLL named newclass.dll, as this is the name of the namespace.


             Client application domain                            Server application domain



                                          Objects passed by
                                          reference or value
                                         for local objects. For
                Client object               remote it is not           Server object
                                          possible to pass by
                                           reference – they
                                         must be marshalled.

                   Proxy




                 Remoting                      Channel                   Remoting
                  System                                                  System



                                            Serialisation




                                 Figure 3.3: Remotable class




                                Figure 3.4: Adding a new class




W.Buchanan                                                            Unit 3 - .NET Remoting 8
Figure 3.5: Completed example

3.5.2      Create a server-activated object
This section shows how an application can be created which activates the remotable
object. As long as the application runs, the remotable object can be called by a client,
and invoked.

1.       Add a New Project, and select Console Application, and name it (for example
         newclass2, as shown in Figure 3.6).
2.       Next add the references to the first project (the DLL file), and to the Sys-
         tem.Runtime.Remoting (Figure 3.7).
3.       Next the following code can be added:

        C# Code 3.2:
using    System;
using    System.Runtime.Remoting;
using    System.Runtime.Remoting.Channels;
using    System.Runtime.Remoting.Channels.Tcp;
namespace newclass2
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            TcpServerChannel channel = new TcpServerChannel(1234);
                ChannelServices.RegisterChannel(channel,false);
                RemotingConfiguration.RegisterWellKnownServiceType
                    (typeof(newclass.ShowCapital), "ShowCapital",
                    WellKnownObjectMode.SingleCall);
                Console.WriteLine("Starting...");
                Console.ReadLine();
            }
     }
}




W.Buchanan                                               Unit 3 - .NET Remoting 9
Client application domain                         Server application domain




                  Client object
                                             Server                  Remoteable object
                                           innovation                   (object.dll)

                                                                      ShowCapital()
                     Proxy

                                             Channel=1234


                   Remoting                     Channel                 Remoting
                    System                                               System




                                                   Server-activation object



                           Figure 3.6: Server-activation object (SAO)

For this:

RemotingConfiguration.RegisterWellKnownServiceType
   (typeof(newclass.ShowCapital), "ShowCapital", WellKnownObjectMode.SingleCall);


defines a SingleCall activation mode (which means it will run once and then be de-
leted), on the ShowCapital object, which is within the newclass namespace.
ShowCapital is thus the name of the object, where the ShowCapital1 is the object
URI. This refers to a DLL file named after the namespace (in this case newclass.dll).
The channel used is 1234. Once the server-activated component has been started it
will wait for the client to connect to it. As it is a SingleCall it will call the remote ob-
ject once, and then it will be deleted. Thus every time it is called, it will not
remember the previous state. If the Singleton option is used the remote object will
stay active and will thus store its state.




                                    Figure 3.7: .NET remoting




W.Buchanan                                                            Unit 3 - .NET Remoting 10
Figure 3.8: .NET remoting referencing

3.5.3      Instantiating and invoking a server-activated object
This section shows how an application can invoke a server-activated object. This
runs on the client and calls the server to invoke the remotable class. The main steps
are:

1.      Add a New Project to the solution, using a Windows Application (Figure 3.9).
2.      Next a reference is added for a the System.Runtime.Remoting assembly (Fig-
        ure 3.10) and the remotable class (newclass), as shown in Figure 3.11.


        Client application domain                          Server application domain




           Client object
                                      Server                    Remoteable object
                                    innovation                     (object.dll)

                                                                 ShowCapital()
              Proxy

                                      Channel=1234


            Remoting                     Channel                   Remoting
             System                                                 System




                                            Server-activation object


                                Figure 3.9: Server invocation




W.Buchanan                                                  Unit 3 - .NET Remoting 11
Figure 3.10: .NET remoting




                              Figure 3.11: .NET remoting

3.      Add the following code:

       C# Code 3.3:
using   System;
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Text;
using   System.Windows.Forms;
using   System.Runtime.Remoting;
using   System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using newclass;
namespace WindowsFormsApplication1




W.Buchanan                                                 Unit 3 - .NET Remoting 12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
         ShowCapital sh;
         private void button1_Click(object sender, System.EventArgs e)
         {
             string country, cap;
              country = textBox1.Text;
              cap = sh.show(country);
              textBox2.Text = cap;
         }
         private void Form1_Load(object sender, System.EventArgs e)
         {
             TcpClientChannel channel = new TcpClientChannel();
              ChannelServices.RegisterChannel(channel,false);
              RemotingConfiguration.RegisterWellKnownClientType(
                  typeof(ShowCapital),"tcp://localhost:1234/ShowCapital");
              sh = new ShowCapital();
         }
    }
}


This then connects to server (in this case, with localhost, which has the IP address of
127.0.0.1), using TCP port of 1234.

3.5.4    Creating a control executable
It is possible to create an orderly start for the project, by selecting the properties of
the solution, and then selecting Multiple Startup Project. This can then be used to
create an orderly innovation of the programs, as the server must be started before
the client. Obviously the remotable class will not be started-up, thus its action is
None, as illustrated in Figure 3.12. A sample run is given in Figure 3.13.




                               Figure 3.12: .NET remoting




W.Buchanan                                                  Unit 3 - .NET Remoting 13
Figure 3.13: .NET remoting




W.Buchanan                                Unit 3 - .NET Remoting 14
3.6 Tutorial 1
Tutorial (Part 1):   [Link]

Q3.1     Implement the code in C# Code 3.1, C# Code 3.2 and C# Code 3.3, and
         prove that the application works. Next, complete the following:

Tutorial (Part 2):   [Link]

         (a)   Add a debug message within C# Code 3.1 so that it displays the
               country which is being searched for.

Tutorial (Part 3):   [Link]

         (b)   Add a counter within C# Code 3.1 so that the remoteable object
               returns a counter to show the number of times it has been called (as
               illustrated in Figure 3.14). Show thus, for the SingleCall that the
               counter will always show the same value.

         (c)   Next modify C# Code 3.2, so that is uses the Singleton method, and
               show that the counter will increment for every access.

Tutorial (Part 4):   [Link]

         (d)   Modify the application so that it uses HTTP rather than TCP.




                                Figure 3.14: Example



Q3.2     Contact a neighbour in the lab, and ask them to place your server compo-
         nent (dll and exe) from Tutorial Q3.1 onto their machine. Ask them to run



W.Buchanan                                              Unit 3 - .NET Remoting 15
the server component. Next run the Windows program to contact their
       server component, and prove that it works.
       Note: Make sure you use the IP address of your neighbour’s PC.

Q3.3   Modify the server C# Code 3.2 so that it listens on port 80 (or any other re-
       served ports), and, if you have a WWW server running on your machine,
       prove that the error message is:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred
in system.runtime.remoting.dll
Additional information: Only one usage of each socket address (proto-
col/network address/port) is normally permitted

Q3.3   From the Command Prompt, run netstat -a, and determine the TCP server
       ports which are open. Next run netstat -a -v, and observe the output. What
       does the 0.0.0.0 address identify?

Q3.4   Create a program which uses .NET remoting to implement the following:

       (a)   Returns the IP address for a specified domain name. An example is
             given in Figure 3.15.

       Note, to get the IP addresses the following can be used:

       if (strHostName=="") strHostName = Dns.GetHostName();
       IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
       IPAddress [] addr = ipEntry.AddressList;

       Where the first IP address can be return (addr[0]).

       (b)   Created another method which returns the hostname for a given
             IP address.




                               Figure 3.15: Example




W.Buchanan                                            Unit 3 - .NET Remoting 16
3.6.1    Client-activated object
The lifetime of server-activated objects (SAO) is directly controlled by the server,
whereas the lifetime of client-activated objects (CAO) is controlled by the calling
application program, just as if it were local to the client.

An SAO the remotable object is defined with:

    RemotingConfiguration.RegisterWellKnownServiceType
       (typeof(newclass.ShowCapital), "ShowCapital",
       WellKnownObjectMode.SingleCall);


A CAO the remotable object is defined with:

    RemotingConfiguration.RegisterActivatedServiceType
       (typeof(newclass.ShowCapital));


When initiating and invoking a SAO:

    RemotingConfiguration.RegisterWellKnownClientType(
       typeof(ShowCapital), "tcp://localhost:1234/ShowCapital");


When initiating and invoking a CAO:

    RemoteConfiguration.RegisterActivedClientType
       (typeof(newclass.ShowCapital),”tcp://localhost:1234”);



3.6.2    Tutorial 2
Q3.5     Modify Tutorial Q3.1 so that it uses CAO instead of SAO.

Q3.6     Modify Tutorial Q3.2 so that it uses CAO instead of SAO.

Q3.7     Implement a remote object which has the following methods:

   Square(x). Which determines the square of a number.
   SquareRoot(x). Which determines the square root of a number.
   Power(x,n). Which determines the power of a number (x) raised to another
    number (n).




W.Buchanan                                            Unit 3 - .NET Remoting 17
3.7 Configuration Files for remoting
In the previous examples the channel and the definitions for the remote object have
been defined within the program (programmatic configuration). Thus it is not pos-
sible to change them once the application has been compiled. An enhanced method
which allows the channel and remote object definition to be defined as an external
configuration is to use an XML file to define the parameters used in .NET remoting
(declarative configuration). This is achieved either at a machine-level with the ma-
chine.config file (which can be found in the config folder), or at an application level
with an application configuration file. In an ASP.NET application the name of the
configuration file is web.config. The general format is:

<configuration>
   <system.runtime.remoting>
      <application>
         <lifetime> </lifetime>
         <service>
            <wellknown/> <activated/>
         </service>
         <client>
            <wellknown/> <activated/>
         </client>
         <channels> </channels>
      </application>
   </system.runtime.remoting>
</configuration>


It includes the full name of the application, with a .config extension. Thus an appli-
cation named myapp.exe will have an associated configuration file of
myapp.exe.config.

3.7.1     Register server-activated object with configuration file
RemotingConfiguration.Configure is used to register a server-activated object, such
as:
        static void Main(string[] args)
        {
           RemotingConfiguration.Configure("..//..//dotnetremote1.exe.config");
          Console.WriteLine("Starting...");
          Console.ReadLine();


The file dotnetexample1.exe.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.runtime.remoting>
      <application>
         <service>
            <wellknown mode="Singleton" type="newclass.ShowCapital, newclass"
                 objectUri="ShowCapital1" />
         </service>
         <channels>
            <channel ref="tcp server" port="1234" />
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>




W.Buchanan                                              Unit 3 - .NET Remoting 18
This achieves the same as:

            RemotingConfiguration.RegisterWellKnownServiceType
               (typeof(newclass.ShowCapital),
               "ShowCapital1", WellKnownObjectMode.Singleton);


which defines a Singleton remote activation, and the ShowCapital object, which is
within the newclass namespace. ShowCapital is thus the name of the object, where
the ShowCapital1 is the object URI.

3.7.2       Register client-side configuration
The client-side configuration is similar, but uses the <client> element. An example of
the configuration file is:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.runtime.remoting>
      <application>
         <client>
            <wellknown type="newclass.ShowCapital, newclass"
            url="tcp://localhost:1234/ShowCapital" />
         </client>
      </application>
   </system.runtime.remoting>
</configuration>


and for the call:

        private void Form1_Load(object sender, System.EventArgs e)
        {
           RemotingConfiguration.Configure("app2.config");
           sh= new ShowCapital();
        }


Figure 3.16 shows an example of the output.




                              Figure 3.16: .NET remoting




W.Buchanan                                                 Unit 3 - .NET Remoting 19
3.7.3   Tutorial 3
Q3.8    Modify C# Code 3.1, C# Code 3.2 and C# Code 3.3, so that they use an XML
        configuration file for their remoting parameters.

        (a)   Set one port to 1234, and the other to 9999. Prove that the program
              will create an exception.
        (b)   Next, change both ports to 9999, and prove that the system works.

Q3.9    Run the program, and from the command prompt, run netstat, and deter-
        mine that a TCP connection has been made. Outline its details:




Q3.10   Set up the client and server to communicate on port 5555 (using the con-
        figuration file). Next, contact a neighbour in the lab, and ask them to place
        your server component (dll and exe) onto their machine. Ask them to run
        the server component, and run the windows program to contact their com-
        ponent, and prove that it works.

        Note: Make sure you use the IP address of your neighbours PC.

        Next, ask your neighbour to change the port to 8888 on the server side, and
        change the port on your machine. Prove that the system can still communi-
        cate.




W.Buchanan                                             Unit 3 - .NET Remoting 20
3.8 Interface assemblies to compile remote
    clients
An interface is an alternative method of creating an abstract class, and it does not
contain any implementation of the methods, at all. It provides a base class for all the
derived classes. This is useful in hiding the code from other developers, as, in the
previous examples, the assembly to the remotable class has been included in the cli-
ents project. In the following an interface named IDCapital is created, which has a
method of show():

       C# Code 3.4:
using System;
namespace IDCapital
{
   public interface IDCap
   {
      string show(string str);
   }
}


This is the interface assembly. Next we can define the remotable object which im-
plements the interface assembly:

       C# Code 3.5:
using System;
using System.Data;
using IDCapital;
namespace newclass
{
   public class ShowCapital : MarshalByRefObject, IDCapital.IDCap
   {
        public string show(string country)
        {
           if (country.ToLower()=="england") return("London");
           else if (country.ToLower()=="scotland") return("Edinburgh");
           else return("Not known");
        }
    }
}


After which a remoting server can be created to register the remotable object that
implements an interface assembly:

       C# Code 3.6:
using   System;
using   System.Runtime.Remoting;
using   System.Runtime.Remoting.Channels;
using   System.Runtime.Remoting.Channels.Tcp;
using   IDCapital;
namespace newclass2
{
   class Class1
   {
      [STAThread]




W.Buchanan                                              Unit 3 - .NET Remoting 21
static void Main(string[] args)
        {
           TcpServerChannel channel = new TcpServerChannel(1234);
            ChannelServices.RegisterChannel(channel);
            RemotingConfiguration.RegisterWellKnownServiceType
               (typeof(newclass.ShowCapital), "ShowCapital",
               WellKnownObjectMode.SingleCall);
            Console.WriteLine("Starting...");
            Console.ReadLine();
        }
    }
}


Finally a remote client is created which invokes the remotable object that imple-
ments the interface assembly:

       C# Code 3.7:
. . .
        IDCap sh;
        private void button1_Click(object sender, System.EventArgs e)
        {
           string country,cap;
            country=textBox1.Text;
            cap=sh.show(country);
            textBox2.Text= cap;
        }
        private void Form1_Load(object sender, System.EventArgs e)
        {
           TcpClientChannel channel = new TcpClientChannel();
            ChannelServices.RegisterChannel(channel);
            sh= (IDCapital.IDCap) Activator.GetObject(typeof(IDCap),
               "tcp://localhost:1234/ShowCapital");
        }



The references are added as defined in Figure 3.17.




                              Figure 3.17: .NET remoting



W.Buchanan                                                 Unit 3 - .NET Remoting 22
3.8.1    Soapsuds Tool for Interface Assembly Generation
Another method which can be used to generate an interface assembly rather than
the implementation assembly is to use the Soapsuds tool. For this the tool requires
the URL of the remotable object, of which Soapsuds automatically generates the in-
terface assemblies. An example, based on the previous sections is:

soapsuds -url:http://localhost:1234/ShowCapital?wsdl -oa:newclass.dll -nowp


which uses the required URL, and generates a DLL named newclass.dll. For exam-
ple:

> soapsuds -url:http://localhost:1234/ShowCapital?wsdl -oa:newclass.dll -nowp

and listing the directory gives:
>dir
15/01/2005    21:20                1,078 App.ico
15/01/2005    21:20                2,426 AssemblyInfo.cs
16/01/2005    18:11     <DIR>            bin
16/01/2005    17:55                  732 Class1.cs
16/01/2005    18:38                3,584 newclass.dll
16/01/2005    17:56                4,737 newclass2.csproj
16/01/2005    18:27                1,803 newclass2.csproj.user
16/01/2005    17:16     <DIR>            obj

The references are then added as Figure 3.18 and Figure 3.19.




                                   Figure 3.18: DLL




W.Buchanan                                             Unit 3 - .NET Remoting 23
Figure 3.19: References

3.8.2   Tutorial 4
Q3.11   Modify C# Code 3.1, C# Code 3.2 and C# Code 3.3, so it uses an interface
        assembly.




W.Buchanan                                             Unit 3 - .NET Remoting 24

Weitere ähnliche Inhalte

Was ist angesagt?

Interprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SInterprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SHussain Ala'a Alkabi
 
A presentation on WCF & REST
A presentation on WCF & RESTA presentation on WCF & REST
A presentation on WCF & RESTSanthu Rao
 
Characterization of communication.ppt
Characterization of communication.pptCharacterization of communication.ppt
Characterization of communication.pptAthira Ravindranathan
 
Minimum interference routing algorithm
Minimum interference routing algorithmMinimum interference routing algorithm
Minimum interference routing algorithmSankeerthanaS1
 
OOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptOOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptPtidej Team
 
ITFT_Inter process communication
ITFT_Inter process communicationITFT_Inter process communication
ITFT_Inter process communicationSneh Prabha
 
Chapter 5 slides
Chapter 5 slidesChapter 5 slides
Chapter 5 slideslara_ays
 
International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)ijceronline
 
Software architecture styles families_research_gssi_nov2013
Software architecture styles families_research_gssi_nov2013Software architecture styles families_research_gssi_nov2013
Software architecture styles families_research_gssi_nov2013Henry Muccini
 

Was ist angesagt? (12)

Interprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SInterprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.S
 
A presentation on WCF & REST
A presentation on WCF & RESTA presentation on WCF & REST
A presentation on WCF & REST
 
1844 1849
1844 18491844 1849
1844 1849
 
CS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMSCS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMS
 
Characterization of communication.ppt
Characterization of communication.pptCharacterization of communication.ppt
Characterization of communication.ppt
 
Minimum interference routing algorithm
Minimum interference routing algorithmMinimum interference routing algorithm
Minimum interference routing algorithm
 
OOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptOOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.ppt
 
ITFT_Inter process communication
ITFT_Inter process communicationITFT_Inter process communication
ITFT_Inter process communication
 
Chapter 5 slides
Chapter 5 slidesChapter 5 slides
Chapter 5 slides
 
Axis2
Axis2Axis2
Axis2
 
International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)
 
Software architecture styles families_research_gssi_nov2013
Software architecture styles families_research_gssi_nov2013Software architecture styles families_research_gssi_nov2013
Software architecture styles families_research_gssi_nov2013
 

Andere mochten auch

Andere mochten auch (17)

Session 9
Session 9Session 9
Session 9
 
Top 9 Features Of a Successful Android Application
Top 9 Features Of a Successful Android ApplicationTop 9 Features Of a Successful Android Application
Top 9 Features Of a Successful Android Application
 
14 Programación Web con .NET y C#
14 Programación Web con .NET y C#14 Programación Web con .NET y C#
14 Programación Web con .NET y C#
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
Session 6
Session 6Session 6
Session 6
 
Dot NET Remoting
Dot NET RemotingDot NET Remoting
Dot NET Remoting
 
Net remoting
Net remotingNet remoting
Net remoting
 
The .net remote systems
The .net remote systemsThe .net remote systems
The .net remote systems
 
Overview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technologyOverview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technology
 
C sharp
C sharpC sharp
C sharp
 
.Net framework
.Net framework.Net framework
.Net framework
 
Net remoting
Net remotingNet remoting
Net remoting
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
 
Evolution of wcf
Evolution of wcfEvolution of wcf
Evolution of wcf
 
Using Docker for Testing
Using Docker for TestingUsing Docker for Testing
Using Docker for Testing
 
Feb 2010 Intro To Remoteing Part1
Feb 2010 Intro To Remoteing Part1Feb 2010 Intro To Remoteing Part1
Feb 2010 Intro To Remoteing Part1
 
Remote Sensing PPT
Remote Sensing PPTRemote Sensing PPT
Remote Sensing PPT
 

Ähnlich wie NET Remoting Explained

Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system developmentektabhalwara
 
.NET TECHNOLOGIES
.NET TECHNOLOGIES.NET TECHNOLOGIES
.NET TECHNOLOGIESProf Ansari
 
Distributed Systems Architecture in Software Engineering SE11
Distributed Systems Architecture in Software Engineering SE11Distributed Systems Architecture in Software Engineering SE11
Distributed Systems Architecture in Software Engineering SE11koolkampus
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understandingBinu Bhasuran
 
Net Fundamentals
Net FundamentalsNet Fundamentals
Net FundamentalsAli Taki
 
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGY
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGYDistributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGY
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGYreginamutio48
 
.net Based Component Technologies
.net Based Component Technologies.net Based Component Technologies
.net Based Component Technologiesprakashk453625
 
An isas presentation on .net framework 2.0 by vikash chandra das
An isas presentation on .net framework 2.0 by vikash chandra dasAn isas presentation on .net framework 2.0 by vikash chandra das
An isas presentation on .net framework 2.0 by vikash chandra dasVikash Chandra Das
 
2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software conceptsPrajakta Rane
 
Software Engineering for Web Applications
Software Engineering for Web ApplicationsSoftware Engineering for Web Applications
Software Engineering for Web ApplicationsMoh'd Shakeb Baig
 
DS R16 - UNIT-3.pdf
DS R16 - UNIT-3.pdfDS R16 - UNIT-3.pdf
DS R16 - UNIT-3.pdfVarshaBaini
 
Online lg prodect
Online lg prodectOnline lg prodect
Online lg prodectYesu Raj
 
Cs556 section1
Cs556 section1Cs556 section1
Cs556 section1farshad33
 
Software architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideSoftware architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideMohammed Fazuluddin
 

Ähnlich wie NET Remoting Explained (20)

dot NET Framework
dot NET Frameworkdot NET Framework
dot NET Framework
 
Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system development
 
Ch12
Ch12Ch12
Ch12
 
.NET TECHNOLOGIES
.NET TECHNOLOGIES.NET TECHNOLOGIES
.NET TECHNOLOGIES
 
Distributed Systems Architecture in Software Engineering SE11
Distributed Systems Architecture in Software Engineering SE11Distributed Systems Architecture in Software Engineering SE11
Distributed Systems Architecture in Software Engineering SE11
 
.Net Session Overview
.Net Session Overview.Net Session Overview
.Net Session Overview
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understanding
 
Net Fundamentals
Net FundamentalsNet Fundamentals
Net Fundamentals
 
Net framework
Net frameworkNet framework
Net framework
 
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGY
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGYDistributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGY
Distributed OPERATING SYSTEM FOR BACHELOR OF BUSINESS INFORMATION TECHNOLOGY
 
.net Based Component Technologies
.net Based Component Technologies.net Based Component Technologies
.net Based Component Technologies
 
Kushal
KushalKushal
Kushal
 
An isas presentation on .net framework 2.0 by vikash chandra das
An isas presentation on .net framework 2.0 by vikash chandra dasAn isas presentation on .net framework 2.0 by vikash chandra das
An isas presentation on .net framework 2.0 by vikash chandra das
 
MIDELWARE TECH
MIDELWARE TECHMIDELWARE TECH
MIDELWARE TECH
 
2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts
 
Software Engineering for Web Applications
Software Engineering for Web ApplicationsSoftware Engineering for Web Applications
Software Engineering for Web Applications
 
DS R16 - UNIT-3.pdf
DS R16 - UNIT-3.pdfDS R16 - UNIT-3.pdf
DS R16 - UNIT-3.pdf
 
Online lg prodect
Online lg prodectOnline lg prodect
Online lg prodect
 
Cs556 section1
Cs556 section1Cs556 section1
Cs556 section1
 
Software architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideSoftware architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding Guide
 

Mehr von OPENLANE

MTA Certificate Path Microsoft
MTA Certificate Path MicrosoftMTA Certificate Path Microsoft
MTA Certificate Path MicrosoftOPENLANE
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overviewOPENLANE
 
Complete inet-phi-book-vol-1-2003-secure
Complete inet-phi-book-vol-1-2003-secureComplete inet-phi-book-vol-1-2003-secure
Complete inet-phi-book-vol-1-2003-secureOPENLANE
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorialOPENLANE
 
6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx
6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx
6_Issues in accented speech recognition for Gujarati and its role in E_TeachingxOPENLANE
 
Software Quality Managementx
Software Quality ManagementxSoftware Quality Managementx
Software Quality ManagementxOPENLANE
 
Oracle 10gx
Oracle 10gxOracle 10gx
Oracle 10gxOPENLANE
 
About .netx
About .netxAbout .netx
About .netxOPENLANE
 
WML-Tutorial
WML-TutorialWML-Tutorial
WML-TutorialOPENLANE
 
Naive Baysianx
Naive BaysianxNaive Baysianx
Naive BaysianxOPENLANE
 
Introduction to Protégéx
Introduction to ProtégéxIntroduction to Protégéx
Introduction to ProtégéxOPENLANE
 
Introduction to Protégé
Introduction to ProtégéIntroduction to Protégé
Introduction to ProtégéOPENLANE
 
E_commerce and trends in ICT_9thfebx
E_commerce and trends in ICT_9thfebxE_commerce and trends in ICT_9thfebx
E_commerce and trends in ICT_9thfebxOPENLANE
 
Unrestricted Simplex Protocolx
Unrestricted Simplex ProtocolxUnrestricted Simplex Protocolx
Unrestricted Simplex ProtocolxOPENLANE
 
3_Enhancing and Measuring students IQ and EQ levels using AIx
3_Enhancing and Measuring students IQ and EQ levels using AIx3_Enhancing and Measuring students IQ and EQ levels using AIx
3_Enhancing and Measuring students IQ and EQ levels using AIxOPENLANE
 
Asignment MCA - 640005 DWADM
Asignment MCA - 640005 DWADMAsignment MCA - 640005 DWADM
Asignment MCA - 640005 DWADMOPENLANE
 
Data Link Layer Protocolsx
Data Link Layer ProtocolsxData Link Layer Protocolsx
Data Link Layer ProtocolsxOPENLANE
 
ISTAR Abstractx
ISTAR AbstractxISTAR Abstractx
ISTAR AbstractxOPENLANE
 
Web ResarchAbstractx
Web ResarchAbstractxWeb ResarchAbstractx
Web ResarchAbstractxOPENLANE
 

Mehr von OPENLANE (20)

MTA Certificate Path Microsoft
MTA Certificate Path MicrosoftMTA Certificate Path Microsoft
MTA Certificate Path Microsoft
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Complete inet-phi-book-vol-1-2003-secure
Complete inet-phi-book-vol-1-2003-secureComplete inet-phi-book-vol-1-2003-secure
Complete inet-phi-book-vol-1-2003-secure
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorial
 
6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx
6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx
6_Issues in accented speech recognition for Gujarati and its role in E_Teachingx
 
Software Quality Managementx
Software Quality ManagementxSoftware Quality Managementx
Software Quality Managementx
 
Oracle 10gx
Oracle 10gxOracle 10gx
Oracle 10gx
 
About .netx
About .netxAbout .netx
About .netx
 
Doc1x
Doc1xDoc1x
Doc1x
 
WML-Tutorial
WML-TutorialWML-Tutorial
WML-Tutorial
 
Naive Baysianx
Naive BaysianxNaive Baysianx
Naive Baysianx
 
Introduction to Protégéx
Introduction to ProtégéxIntroduction to Protégéx
Introduction to Protégéx
 
Introduction to Protégé
Introduction to ProtégéIntroduction to Protégé
Introduction to Protégé
 
E_commerce and trends in ICT_9thfebx
E_commerce and trends in ICT_9thfebxE_commerce and trends in ICT_9thfebx
E_commerce and trends in ICT_9thfebx
 
Unrestricted Simplex Protocolx
Unrestricted Simplex ProtocolxUnrestricted Simplex Protocolx
Unrestricted Simplex Protocolx
 
3_Enhancing and Measuring students IQ and EQ levels using AIx
3_Enhancing and Measuring students IQ and EQ levels using AIx3_Enhancing and Measuring students IQ and EQ levels using AIx
3_Enhancing and Measuring students IQ and EQ levels using AIx
 
Asignment MCA - 640005 DWADM
Asignment MCA - 640005 DWADMAsignment MCA - 640005 DWADM
Asignment MCA - 640005 DWADM
 
Data Link Layer Protocolsx
Data Link Layer ProtocolsxData Link Layer Protocolsx
Data Link Layer Protocolsx
 
ISTAR Abstractx
ISTAR AbstractxISTAR Abstractx
ISTAR Abstractx
 
Web ResarchAbstractx
Web ResarchAbstractxWeb ResarchAbstractx
Web ResarchAbstractx
 

Kürzlich hochgeladen

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

NET Remoting Explained

  • 1. 3 DotNET Remoting Lecture: [Link] Tutorial (Part 1): [Link] 3.1 Introduction .NET remoting is a technology which allows objects to be placed remotely across a network, where the object can be activated, and communicate with local objects us- ing a communications channel. A formatter is then used to encode and decode the messages as they pass between the remote object and the application. The format of these message can either be:  Binary encoded. This is used where performance is a critical factor.  XML encoded. This is used when interoperability is important, and uses the standardized SOAP protocol. A key element of .NET remoting is that objects can check the messages that are to be sent before they are sent to the channel, and the remote objects are activated in dif- ferent ways, these are:  Client-activated objects. These have a finite lease time, and once their lease has expired, they are deleted (using the garbage collector).  Server-activated objects. These can either be defined with a single call or with a singleton. A single call accepts one request from a client, then performs the ac- tion, and is finally deleted (with the garbage collector). It is defined as stateless, as it does not hold onto parameters from previous calls. Singletons are stateful and can accept multiple calls, where they remember previous calls, and retain their information. They can thus communicate with multiple clients. Also the lifetime of singletons is controlled by lease-based lifetime. 3.2 Application boundaries Microsoft Windows allows applications to run on virtual machines, where applica- tions should not interfere with each other. Thus, a fault in one application should not affect another one. Each application thus has its own code and data area, which should not be accessed by other applications running on the machine. A process boundary is one which isolates a process from others which are running. It is neces- sary that each process can run in its own virtual space, and gain access to as much memory that they require. Other processes should not be able to interfere with this. If a process crashes, it should not affect other processes. .NET expands on this by apply this managed environment onto applications. This is because .NET uses the Common Language Runtime (CLR - Figure 3.1) which is a managed environment
  • 2. for executing code, code access security, object management, debugging, cross- language integration, and profiling support. In standard Windows applications it is not possible to provide a degree of safety that an application does not step outwith its boundaries, as Windows applies process control boundary, rather than an appli- cation boundary. In .NET an application domain is created with the AppDomain class with the System namespace. Thus the application boundary ensures that:  Each application has its own code, data and configuration settings.  No other application can interfere with any other applications. It is thought that application switching for processor time is more efficient than processor switching. Along with this, it is easier to monitor the operation of an ap- plication than it is to monitor a number of processes. VB .NET VB .NET C# C# FCL FCL (Framework (Framework CLS CLS Class Library) Compiler (Common (Common Class Library) Compiler Language Language Specification) Specification) Web Web component component CTS CTS (Common (Common MSIL (Microsoft Type Type Intermediate Language) System) System) CLR (Common Language Runtime) CLR (Common Language Runtime) Allows the programs to run – similar to the Java Virtual Machine (JVM) Allows the programs to run – similar to the Java Virtual Machine (JVM) Figure 3.1: .NET Framework 3.3 Distributed Systems Distributed systems allows resources to be distributed around a network, rather than tying them to a specific host. These resources could relate to hardware and software resources. This allows for less centralized approach, and typically im- proves the robustness of a system and also makes improved usage of network traffic. For example an organisation might use a centralized Web server for their document management. This has the advantage is that it is relatively easy to man- age, but it becomes a centralized point of failure, also the network traffic is likely to be relatively large towards the server. Along with this the CPU usage it likely to be relatively large. An improved system would be to distribute Web servers around the network, and for hosts to access them on a local level. This type of approach can be scaled down to an object-level, where objects can be distributed around a network, either outwith the application domain, or outwith the host. These objects could reside on W.Buchanan Unit 3 - .NET Remoting 2
  • 3. different types of operating systems or system types and thus allow applications to run over heterogeneous systems. Another similar approach is to develop applications which is made of intercon- nected components. These components make it easier to design software, where tasks are split into elements. The distribution of components allows for the stan- dardization of components, which could run remotely. For example a component which does a grammar checker could be standardized and when an application re- quires a grammar checker it calls it up remotely, and uses it. In general distributed systems are generally more scaleable, more robust, and increase availability of services. The most common distributed protocols are RPC (Remote Procedure Calls), Microsoft Distributed Object Model (DCOM), Common Object Request Broker Architecture (CORBA) and Java Remote Invocation (RMI). These are typically applied to certain types of environments, such as DCOM on Windows-based systems and RPC in a UNIX environment. Some of these are legacy type systems which were designed to be simple, and have never really kept up-to- date with modern methods, especially related to security. The .NET framework hopes to produce a new standard for distributed applications. The main namespaces used for .NET Remoting include:  System.Net. This includes classes relating to the networking elements of the dis- tributed system.  System.Runtime.Remoting. This includes classes for the remote aspects of the .NET framework, such as mechanisms for remote communication between ob- jects.  System.Web.Services. This includes protocols relating to Web services, such as those relating to HTTP and SOAP. This is defined as the ASP.NET Web services framework. 3.4 Remote Objects .NET remoting provides a simple mechanism to call remote objects, where a remote object is any object which is outside the application domain, and can thus also be local on the same machine. Within an application domain, the object is passed by reference, whereas primitive data types are passed by value. Obviously it is not possible to pass an object from a remote object by reference since the reference to the object is only valid on the side which contains the object (that is, they only have lo- cal significance). For an object to be passed over an application domain, they must be passed by value, and also serialized (that is, send over a single communications channel). This, thus, defines the structure of the object, and also its contents. The process of communicating between objects and transferring them over an over application boundaries is known as marshalling. Objects are converted into remote objects when they derive from MarshalByRefObject. Then, when a client activates the remote object, it interfaces with a proxy for the remote object, as illus- trated in Figure 3.2. The proxy object acts on behalf of the remote object, and, as previously mentioned, is created when the client actives a remote object. Its main W.Buchanan Unit 3 - .NET Remoting 3
  • 4. objective is to make sure that all the messages sent to the remote object are sent to the correct instance of the object. Client application domain Server application domain Client object Remoteable object (object.dll) ShowCapital() Proxy Remoting Channel Remoting System System Serialisation Figure 3.2: .NET remoting On the remote machine, the remote object is initially registered into an application domain. The MarshalByRefObject is then used to encapsulate all the information required to locate and access the remote object, such as its class name, its class hier- archy, its interfaces and its communication channels. Activation occurs using the URL, and identifies the URI (Unique Reference Identifier) of the remote object. A MBR (Marshal-by-reference) always resides on the server, and the methods are executed on the server, while the client communicates with the local proxy. The fol- lowing shows an example of the ShowCapital class which derives from the MashalByRefObject, and contains a show() method. public class ShowCapital : MarshalByRefObject { public ShowCapital() Derive from { } MarshalByRefObject public string show(string country) { } } The MarshalByValue (MBV) involves serializing values on the server, and sending them to the client. An MBV object is declared by a class with the Serializable attrib- ute, such as: [Serializable()] public class NewMBVObject { } W.Buchanan Unit 3 - .NET Remoting 4
  • 5. 3.4.1 Channels Remote objects transfer messages between themselves using channels. These chan- nels are thus used to send and receive objects, as well as sending information on the methods that require to be called. Each object must have at least one channel set up for this communication, and the channel must be registered before a remote object is called. Once the object is deleted, the channel which it uses is also deleted. Also the same channel cannot be used by different application domains on the same ma- chine. These channels map onto TCP port numbers, and the application must be sure that it does not use one which is currently being used. 3.4.2 HTTP and TCP channels Messages which are transferred by the SOAP protocol use an HTTP channel, whereas a TCP channel uses a binary format to serialize all message. In the HTTP channel, all the messages are converted into an XML format, and serialised (along with the required SOAP headers). The namespaces are: System.Runtime.Remoting.Channels.HTTP for HTTP System.Runtime.Remoting.Channels.TCP for TCP For example to create a client connection to a server port of 1234: TcpChannel channel = new TcpChannel(1234); ChannelServices.RegisterChannel(channel); The HTTPChannel can be used for a wide range of services which are hosted by a Web server (such as IIS). It has security built into it, but has an overhead of extra information (as it works at a higher level than TCP). The TCPChannel is more effi- cient in its operation, but does not have any security built into it. 3.4.3 Activation A key element of the .NET remoting framework is that it supports the activation of remote objects as either a client or a server. Server activation is typically used when remote objects do not required to maintain their state between method calls, or where there are multiple clients who call methods on the same object instance where the object maintains its state between function calls. In a client-activated ob- ject, the client initiates the object and manages it for its lifetime. Remote objects have to be initially registered with the remoting framework be- fore the clients can use them. This is normally done when a hosting application starts up and then registers one or more channels and one or more remote objects. It then waits until it is terminated. When the hosting application is terminated, the ob- jects and channels are deleted. For an object to be registered into the .NET remoting framework the following need to be set:  Assembly name. This defines the assembly in which the class is contained in.  Type name. This defines the data type of the remote object.  Object URI. This is the indicator that clients use to locate the object. W.Buchanan Unit 3 - .NET Remoting 5
  • 6. Object mode. This defines the server activation, such as SingleCall or Singleton. Remote objects are registered using the RegisterWellKnownServiceType, by passing the required parameters into the method, such as: RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital1", WellKnownObjectMode.SingleCall); which defines a SingleCall remote object, and the ShowCapital object, which is within the newclass namespace. ShowCapital is thus the name of the object, where the ShowCapital1 is the object URI. It is also possible to store the parameters in a configuration file then using Con- figure with the required configuration file, such as: RemotingConfiguration.Configure("myconfig.config"); where the configuration file could be in the form of: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application> <service> <wellknown mode="Singleton" type="newclass.ShowCapital, newclass" objectUri="ShowCapital1" /> </service> <channels> <channel ref="tcp server" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration> This method has the advantage that it does not need to be compiled with the appli- cation, and can therefore be edited as required, and will be read in as required. Thus a change of parameters, such as a change of object name does not require a recom- pilation. Once registered, the remote object will not instantiate itself, as this requires the client to initiate it, or call a method. This is achieved by a client which knows the URI of the remote object and by registering the channel it prefers using GetObject, such as: TcpClientChannel channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel); ShowCapital sh= (ShowCapital) Activator.GetObject(typeof(newclass.ShowCapital), "tcp://localhost:1234/ShowCapital1"); where:  “tcp://localhost:1234/ShowCapital1”. Specifies that the end point is ShowCapital using TCP port 1234. W.Buchanan Unit 3 - .NET Remoting 6
  • 7. Along with this, the compiler requires type information about the ShowCapital class when this client code is compiled. This can be defined with one of the following:  With a reference to the assembly where the ShowCapital class is stored.  By splitting the remote object into an implementation and interface class and then use the interface as a reference when compiling the client.  Using SOAPSUDS tool to extract metadata directly from the endpoint. SOAPSUDS connects to the endpoint, and extracts the metadata, and generates an assembly or souce code that is then used in the client compilation. Another method is RemotingConfiguration.RegisterWellKnownClientType( typeof(ShowCapital), "tcp://localhost:1234/ShowCapital"); None of these calls actually initiates the remote object, as only a proxy is created which will be used to contact the object. The connection is only made when a method is called on the remote object. Once this happens, the remote framework extracts the URI, and initiates the required object, and forwards the required method to the object. If it is a SingleCall, the object is destroyed after the method has completed. 3.5 Applying .NET Remoting The following sections show a remote objects are initiated and then how they can be used to communicate between a client and a server. 3.5.1 Creating a remotable class The following steps shows how a remote class is created (Figure 3.3). These are: 1. Create a new blank solution (named NetRemoting1). 2. Add a new class library (for example, named newclass). Select Add New Pro- ject, then select Class Library, as illustrated in Figure 3.3. 3. Add System.RunTime.Remoting.dll as a Reference (if required). 4. Change the name of the class file to a new name (for example, ShowCapi- tal.cs). 5. Add the following code:  C# Code 3.1: using System; using System.Data; namespace newclass { public class ShowCapital : MarshalByRefObject { public ShowCapital() W.Buchanan Unit 3 - .NET Remoting 7
  • 8. { } public string show(string country) { if (country.ToLower() == "england") return ("London"); else if (country.ToLower() == "scotland") return ("Edinburgh"); else return ("Not known"); } } } and the results are shown in Figure 3.5. This produces a class named ShowCapital, which has a method of show(). This class, once built, produces a remotable class in the form of a DLL file, which is placed in the binDebug folder. In this case it will create a DLL named newclass.dll, as this is the name of the namespace. Client application domain Server application domain Objects passed by reference or value for local objects. For Client object remote it is not Server object possible to pass by reference – they must be marshalled. Proxy Remoting Channel Remoting System System Serialisation Figure 3.3: Remotable class Figure 3.4: Adding a new class W.Buchanan Unit 3 - .NET Remoting 8
  • 9. Figure 3.5: Completed example 3.5.2 Create a server-activated object This section shows how an application can be created which activates the remotable object. As long as the application runs, the remotable object can be called by a client, and invoked. 1. Add a New Project, and select Console Application, and name it (for example newclass2, as shown in Figure 3.6). 2. Next add the references to the first project (the DLL file), and to the Sys- tem.Runtime.Remoting (Figure 3.7). 3. Next the following code can be added:  C# Code 3.2: using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace newclass2 { class Class1 { [STAThread] static void Main(string[] args) { TcpServerChannel channel = new TcpServerChannel(1234); ChannelServices.RegisterChannel(channel,false); RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital", WellKnownObjectMode.SingleCall); Console.WriteLine("Starting..."); Console.ReadLine(); } } } W.Buchanan Unit 3 - .NET Remoting 9
  • 10. Client application domain Server application domain Client object Server Remoteable object innovation (object.dll) ShowCapital() Proxy Channel=1234 Remoting Channel Remoting System System Server-activation object Figure 3.6: Server-activation object (SAO) For this: RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital", WellKnownObjectMode.SingleCall); defines a SingleCall activation mode (which means it will run once and then be de- leted), on the ShowCapital object, which is within the newclass namespace. ShowCapital is thus the name of the object, where the ShowCapital1 is the object URI. This refers to a DLL file named after the namespace (in this case newclass.dll). The channel used is 1234. Once the server-activated component has been started it will wait for the client to connect to it. As it is a SingleCall it will call the remote ob- ject once, and then it will be deleted. Thus every time it is called, it will not remember the previous state. If the Singleton option is used the remote object will stay active and will thus store its state. Figure 3.7: .NET remoting W.Buchanan Unit 3 - .NET Remoting 10
  • 11. Figure 3.8: .NET remoting referencing 3.5.3 Instantiating and invoking a server-activated object This section shows how an application can invoke a server-activated object. This runs on the client and calls the server to invoke the remotable class. The main steps are: 1. Add a New Project to the solution, using a Windows Application (Figure 3.9). 2. Next a reference is added for a the System.Runtime.Remoting assembly (Fig- ure 3.10) and the remotable class (newclass), as shown in Figure 3.11. Client application domain Server application domain Client object Server Remoteable object innovation (object.dll) ShowCapital() Proxy Channel=1234 Remoting Channel Remoting System System Server-activation object Figure 3.9: Server invocation W.Buchanan Unit 3 - .NET Remoting 11
  • 12. Figure 3.10: .NET remoting Figure 3.11: .NET remoting 3. Add the following code:  C# Code 3.3: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using newclass; namespace WindowsFormsApplication1 W.Buchanan Unit 3 - .NET Remoting 12
  • 13. { public partial class Form1 : Form { public Form1() { InitializeComponent(); } ShowCapital sh; private void button1_Click(object sender, System.EventArgs e) { string country, cap; country = textBox1.Text; cap = sh.show(country); textBox2.Text = cap; } private void Form1_Load(object sender, System.EventArgs e) { TcpClientChannel channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel,false); RemotingConfiguration.RegisterWellKnownClientType( typeof(ShowCapital),"tcp://localhost:1234/ShowCapital"); sh = new ShowCapital(); } } } This then connects to server (in this case, with localhost, which has the IP address of 127.0.0.1), using TCP port of 1234. 3.5.4 Creating a control executable It is possible to create an orderly start for the project, by selecting the properties of the solution, and then selecting Multiple Startup Project. This can then be used to create an orderly innovation of the programs, as the server must be started before the client. Obviously the remotable class will not be started-up, thus its action is None, as illustrated in Figure 3.12. A sample run is given in Figure 3.13. Figure 3.12: .NET remoting W.Buchanan Unit 3 - .NET Remoting 13
  • 14. Figure 3.13: .NET remoting W.Buchanan Unit 3 - .NET Remoting 14
  • 15. 3.6 Tutorial 1 Tutorial (Part 1): [Link] Q3.1 Implement the code in C# Code 3.1, C# Code 3.2 and C# Code 3.3, and prove that the application works. Next, complete the following: Tutorial (Part 2): [Link] (a) Add a debug message within C# Code 3.1 so that it displays the country which is being searched for. Tutorial (Part 3): [Link] (b) Add a counter within C# Code 3.1 so that the remoteable object returns a counter to show the number of times it has been called (as illustrated in Figure 3.14). Show thus, for the SingleCall that the counter will always show the same value. (c) Next modify C# Code 3.2, so that is uses the Singleton method, and show that the counter will increment for every access. Tutorial (Part 4): [Link] (d) Modify the application so that it uses HTTP rather than TCP. Figure 3.14: Example Q3.2 Contact a neighbour in the lab, and ask them to place your server compo- nent (dll and exe) from Tutorial Q3.1 onto their machine. Ask them to run W.Buchanan Unit 3 - .NET Remoting 15
  • 16. the server component. Next run the Windows program to contact their server component, and prove that it works. Note: Make sure you use the IP address of your neighbour’s PC. Q3.3 Modify the server C# Code 3.2 so that it listens on port 80 (or any other re- served ports), and, if you have a WWW server running on your machine, prove that the error message is: An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in system.runtime.remoting.dll Additional information: Only one usage of each socket address (proto- col/network address/port) is normally permitted Q3.3 From the Command Prompt, run netstat -a, and determine the TCP server ports which are open. Next run netstat -a -v, and observe the output. What does the 0.0.0.0 address identify? Q3.4 Create a program which uses .NET remoting to implement the following: (a) Returns the IP address for a specified domain name. An example is given in Figure 3.15. Note, to get the IP addresses the following can be used: if (strHostName=="") strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName(strHostName); IPAddress [] addr = ipEntry.AddressList; Where the first IP address can be return (addr[0]). (b) Created another method which returns the hostname for a given IP address. Figure 3.15: Example W.Buchanan Unit 3 - .NET Remoting 16
  • 17. 3.6.1 Client-activated object The lifetime of server-activated objects (SAO) is directly controlled by the server, whereas the lifetime of client-activated objects (CAO) is controlled by the calling application program, just as if it were local to the client. An SAO the remotable object is defined with: RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital", WellKnownObjectMode.SingleCall); A CAO the remotable object is defined with: RemotingConfiguration.RegisterActivatedServiceType (typeof(newclass.ShowCapital)); When initiating and invoking a SAO: RemotingConfiguration.RegisterWellKnownClientType( typeof(ShowCapital), "tcp://localhost:1234/ShowCapital"); When initiating and invoking a CAO: RemoteConfiguration.RegisterActivedClientType (typeof(newclass.ShowCapital),”tcp://localhost:1234”); 3.6.2 Tutorial 2 Q3.5 Modify Tutorial Q3.1 so that it uses CAO instead of SAO. Q3.6 Modify Tutorial Q3.2 so that it uses CAO instead of SAO. Q3.7 Implement a remote object which has the following methods:  Square(x). Which determines the square of a number.  SquareRoot(x). Which determines the square root of a number.  Power(x,n). Which determines the power of a number (x) raised to another number (n). W.Buchanan Unit 3 - .NET Remoting 17
  • 18. 3.7 Configuration Files for remoting In the previous examples the channel and the definitions for the remote object have been defined within the program (programmatic configuration). Thus it is not pos- sible to change them once the application has been compiled. An enhanced method which allows the channel and remote object definition to be defined as an external configuration is to use an XML file to define the parameters used in .NET remoting (declarative configuration). This is achieved either at a machine-level with the ma- chine.config file (which can be found in the config folder), or at an application level with an application configuration file. In an ASP.NET application the name of the configuration file is web.config. The general format is: <configuration> <system.runtime.remoting> <application> <lifetime> </lifetime> <service> <wellknown/> <activated/> </service> <client> <wellknown/> <activated/> </client> <channels> </channels> </application> </system.runtime.remoting> </configuration> It includes the full name of the application, with a .config extension. Thus an appli- cation named myapp.exe will have an associated configuration file of myapp.exe.config. 3.7.1 Register server-activated object with configuration file RemotingConfiguration.Configure is used to register a server-activated object, such as: static void Main(string[] args) { RemotingConfiguration.Configure("..//..//dotnetremote1.exe.config"); Console.WriteLine("Starting..."); Console.ReadLine(); The file dotnetexample1.exe.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application> <service> <wellknown mode="Singleton" type="newclass.ShowCapital, newclass" objectUri="ShowCapital1" /> </service> <channels> <channel ref="tcp server" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration> W.Buchanan Unit 3 - .NET Remoting 18
  • 19. This achieves the same as: RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital1", WellKnownObjectMode.Singleton); which defines a Singleton remote activation, and the ShowCapital object, which is within the newclass namespace. ShowCapital is thus the name of the object, where the ShowCapital1 is the object URI. 3.7.2 Register client-side configuration The client-side configuration is similar, but uses the <client> element. An example of the configuration file is: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application> <client> <wellknown type="newclass.ShowCapital, newclass" url="tcp://localhost:1234/ShowCapital" /> </client> </application> </system.runtime.remoting> </configuration> and for the call: private void Form1_Load(object sender, System.EventArgs e) { RemotingConfiguration.Configure("app2.config"); sh= new ShowCapital(); } Figure 3.16 shows an example of the output. Figure 3.16: .NET remoting W.Buchanan Unit 3 - .NET Remoting 19
  • 20. 3.7.3 Tutorial 3 Q3.8 Modify C# Code 3.1, C# Code 3.2 and C# Code 3.3, so that they use an XML configuration file for their remoting parameters. (a) Set one port to 1234, and the other to 9999. Prove that the program will create an exception. (b) Next, change both ports to 9999, and prove that the system works. Q3.9 Run the program, and from the command prompt, run netstat, and deter- mine that a TCP connection has been made. Outline its details: Q3.10 Set up the client and server to communicate on port 5555 (using the con- figuration file). Next, contact a neighbour in the lab, and ask them to place your server component (dll and exe) onto their machine. Ask them to run the server component, and run the windows program to contact their com- ponent, and prove that it works. Note: Make sure you use the IP address of your neighbours PC. Next, ask your neighbour to change the port to 8888 on the server side, and change the port on your machine. Prove that the system can still communi- cate. W.Buchanan Unit 3 - .NET Remoting 20
  • 21. 3.8 Interface assemblies to compile remote clients An interface is an alternative method of creating an abstract class, and it does not contain any implementation of the methods, at all. It provides a base class for all the derived classes. This is useful in hiding the code from other developers, as, in the previous examples, the assembly to the remotable class has been included in the cli- ents project. In the following an interface named IDCapital is created, which has a method of show():  C# Code 3.4: using System; namespace IDCapital { public interface IDCap { string show(string str); } } This is the interface assembly. Next we can define the remotable object which im- plements the interface assembly:  C# Code 3.5: using System; using System.Data; using IDCapital; namespace newclass { public class ShowCapital : MarshalByRefObject, IDCapital.IDCap { public string show(string country) { if (country.ToLower()=="england") return("London"); else if (country.ToLower()=="scotland") return("Edinburgh"); else return("Not known"); } } } After which a remoting server can be created to register the remotable object that implements an interface assembly:  C# Code 3.6: using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using IDCapital; namespace newclass2 { class Class1 { [STAThread] W.Buchanan Unit 3 - .NET Remoting 21
  • 22. static void Main(string[] args) { TcpServerChannel channel = new TcpServerChannel(1234); ChannelServices.RegisterChannel(channel); RemotingConfiguration.RegisterWellKnownServiceType (typeof(newclass.ShowCapital), "ShowCapital", WellKnownObjectMode.SingleCall); Console.WriteLine("Starting..."); Console.ReadLine(); } } } Finally a remote client is created which invokes the remotable object that imple- ments the interface assembly:  C# Code 3.7: . . . IDCap sh; private void button1_Click(object sender, System.EventArgs e) { string country,cap; country=textBox1.Text; cap=sh.show(country); textBox2.Text= cap; } private void Form1_Load(object sender, System.EventArgs e) { TcpClientChannel channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel); sh= (IDCapital.IDCap) Activator.GetObject(typeof(IDCap), "tcp://localhost:1234/ShowCapital"); } The references are added as defined in Figure 3.17. Figure 3.17: .NET remoting W.Buchanan Unit 3 - .NET Remoting 22
  • 23. 3.8.1 Soapsuds Tool for Interface Assembly Generation Another method which can be used to generate an interface assembly rather than the implementation assembly is to use the Soapsuds tool. For this the tool requires the URL of the remotable object, of which Soapsuds automatically generates the in- terface assemblies. An example, based on the previous sections is: soapsuds -url:http://localhost:1234/ShowCapital?wsdl -oa:newclass.dll -nowp which uses the required URL, and generates a DLL named newclass.dll. For exam- ple: > soapsuds -url:http://localhost:1234/ShowCapital?wsdl -oa:newclass.dll -nowp and listing the directory gives: >dir 15/01/2005 21:20 1,078 App.ico 15/01/2005 21:20 2,426 AssemblyInfo.cs 16/01/2005 18:11 <DIR> bin 16/01/2005 17:55 732 Class1.cs 16/01/2005 18:38 3,584 newclass.dll 16/01/2005 17:56 4,737 newclass2.csproj 16/01/2005 18:27 1,803 newclass2.csproj.user 16/01/2005 17:16 <DIR> obj The references are then added as Figure 3.18 and Figure 3.19. Figure 3.18: DLL W.Buchanan Unit 3 - .NET Remoting 23
  • 24. Figure 3.19: References 3.8.2 Tutorial 4 Q3.11 Modify C# Code 3.1, C# Code 3.2 and C# Code 3.3, so it uses an interface assembly. W.Buchanan Unit 3 - .NET Remoting 24