Sie sind auf Seite 1von 65

.

NET REMOTING

Remoting
Communication of applications
Instantiating objects through remoting. Sharing data, making function calls Distributed Applications

Motivation
Application domain is a hard boundary
Acts much like a unmanaged process Also includes process/machine boundaries No direct access to objects across boundary

Remoting services required to access an object across a hard boundary

Non-remotable objects
CLR objects cannot, by default, be used outside their AppDomain

No way to copy them No way to reference them

Exception occurs when you try to pass an object reference to a different domain

Remotable objects
Can request that instances of a class be accessible outside original AppDomain

Should a client get a copy of the object? Should a client get a reference (proxy) to the original object

Serializable objects
When runtime can make a copy of the object, an object can marshal-by-value to other AppDomains

Add SerializableAttribute Or implement the ISerializable interface

Clients in foreign AppDomains receive clone


[Serializable] Class Obj { . . . }

MarshalByRef objects
When the object's class derives, directly or indirectly, from MarshalByRefObject, the runtime creates a proxy to the object
[Serializable] class Obj : System.MarshalByRefObject { . . . } // MBRO overrides // Serializable

Clients in foreign AppDomains receive proxy How does a client specify what proxy?

Remoting in general
Clients must connect to servers

Server needs to publish an object


I listen on this TCP channel and that HTTP channel I have a service called "MathService" When client connects to MathService using a supported channel, give the client [ a | this ] Calculator instance

Clients need to specify the desired object

Connect to the "MathService" on server "LightningFast" using protocol HTTP on port 80

Server design and implementation


Design considerations

Decide which channels/ports to support Select an activation model Decide how clients get type metadata Select/write appropriate host Configure remoting system activation mode Register channels

Implementation

Writing a server
Assumption: You have an assembly containing MarshalByRefObject types you wish to make available for use via remoting A server then becomes simply a host app

Loads the managed types Configures remoting to expose the types

Can write your own host Can use IIS as an already available HTTP host

Well-known objects
Server registers a well-known type using RegisterWellKnownServiceType specifying

The type being registered The end point name known to clients The activation model

Well-known objects
Server activated types are "well-known"

Server tells remoting


Here's a type Here's how and when to instantiate the type Here's the name (end point) a client will use to contact the type Connect to this server machine Get the (known) type at this end point (name)

Clients tell remoting


Activation requests
Server also chooses how it wants to process activations requests for a type Two forms of server activation

WellKnownObjectMode.SingleCall WellKnownObjectMode.Singleton Client activated object (CAO)

One form of client activation

SingleCall objects
Server's remoting layer creates one SingleCall object per method call

Each object services one and only one request


Created on-demand as method calls arrive Lifetime limited to method call

Useful in stateless applications Best choice for load-balanced applications

Singleton objects
Server's remoting layer creates one Singleton object

Sole object handles method calls from all clients

Lifetime equals server lifetime

Useful in stateful applications

Can only store client-independent state

Best choice where overhead of creating and maintaining objects is substantial

RegisterWellKnownService Type
using System.Runtime.Remoting; . . . WellKnownServiceTypeEntry WKSTE = new WellKnownServiceTypeEntry(typeof(SuperCalc.Calculator), "Calculator", WellKnownObjectMode.SingleCall);

RemotingConfiguration.RegisterWellKnownServiceType(WKSTE);

Channels
A channel transports messages to and from a remote object

A server selects the channels upon which it listens for requests A client selects the channels it wishes to use to communicate with the server HTTP and TCP channels You can write custom channels

Runtime provides built-in channel types


Registering Channels
System.Runtime.Remoting.Channels ns. Custom channels implement IChannel. ChannelServices class

RegisterChannel UnregisterChannel SyncDispatchMessage AsyncDispatchMessage RegisteredChannels

ChannelServices.RegisterC hannel

using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using System.Runtime.Remoting.Channels.Tcp; . . . ChannelServices.RegisterChannel (new HttpChannel()); ChannelServices.RegisterChannel (new TcpChannel(4242));

Server activation example


using using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http; System.Runtime.Remoting.Channels.Tcp;

class RemotingHost { static void Main(string[] args) { RemotingConfiguration.ApplicationName = MathService"; WellKnownServiceTypeEntry WKSTE = new WellKnownServiceTypeEntry(typeof(SuperCalc.Calculator), "SharedCalc", WellKnownObjectMode.Singleton);

RemotingConfiguration.RegisterWellKnownServiceType(WKSTE); ChannelServices.RegisterChannel(new HttpChannel(9000)); ChannelServices.RegisterChannel(new TcpChannel(4242)); Console.ReadLine();


} }

RemotingServices
Connect Disconnect Marshal Unmarshal GetLifeTimeService IsOneWay

Lifetime Management
The Ilease interface defines the current lifetime.
CurrentLeaseTime CurrentState InitialLeaseTime Register Renew UnRegister

MarshalByRefObject
Used to access objects across domains.
GetLifeTimeService InitializeLifeTimeService

Well-known object URLs


Server-activated objects are published at a URL

The URL is "well-known" to the client


Such types are called well-known types The URL is called the well-known object URL

ProtocolScheme://ComputerName:Port/PossibleApplicationName/ObjectUri

When IIS is the server's host:

PossibleApplicationName becomes virtual dir name ObjectUri should end in ".rem" or ".soap"

A TcpChannel requires the port number

Remoting config file


All hard-coded remoting information in prior example can reside in external config file

Default filename is executable plus ".config" E.g. RuntimeHost.exe is RuntimeHost.exe.config RemotingConfiguration.Configure (file)

Host must tell remoting to use the config file

Server code simplifies

Server remoting config file


<configuration> <system.runtime.remoting> <application name="SuperCalcMathService"> <service> <wellknown mode="SingleCall" type="SuperCalc.Calculator,MathObjects" objectUri = "EphemeralCalc" /> <wellknown mode="Singleton" type="SuperCalc.Calculator,MathObjects" objectUri = "SharedCalc" /> </service> <channels> <channel port="9000" ref="http" /> <channel port="4242" ref="tcp" /> </channels> </application> </system.runtime.remoting> </configuration>

Revised Server Example


using System; using System.Reflection; using System.Runtime.Remoting; class RemotingHost { static void Main(string[] args) { String s = Assembly.GetExecutingAssembly().Location; RemotingConfiguration.Configure (s + ".config"); Console.ReadLine(); } }

Remoting clients
A clients wants to use a remote object

Well-known objects exist at a URL


Client obtains proxy using Activator.GetObject Client can also obtain proxy using new

Client activated object factory exists at a URL


Client requests factory to instantiate object and return a proxy to it using Activator.CreateInstance Client can also make same request using new

Complete client application I


Imports Imports Imports Imports Imports System System.Runtime.Remoting System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Http System.Runtime.Remoting.Channels.Tcp

Class RemotingClient Shared Sub Main() ' Register channel(s) ChannelServices.RegisterChannel(New HttpChannel()) ' Connect to a Well-known object Dim uriWKO As String = "http://localhost:9000/SuperCalcMathService/SharedCalc" Dim o As Object = Activator.GetObject(GetType(SuperCalc.Calculator), uriWKO) ' Use the Calculator Dim c As SuperCalc.Calculator c = CType(o, SuperCalc.Calculator) c.Add(21) End Sub End Class

Complete client application II


Imports Imports Imports Imports Imports System System.Runtime.Remoting System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Http System.Runtime.Remoting.Channels.Tcp

Class RemotingClient Shared Sub Main() ' Register channel(s) ChannelServices.RegisterChannel(New TcpChannel())

Still need to information runtime of proper channels to use

' Create a client activated object Dim url As String = "tcp://localhost:4242/SuperCalcMathService" Dim activationAttributes() As Object = { New Activation.UrlAttribute(url) } Dim o As Object = Activator.CreateInstance(GetType(SuperCalc.Calculator), _ Nothing, activationAttributes) ' Use the Calculator Dim c As SuperCalc.Calculator c = CType(o, SuperCalc.Calculator) c.Add(21) End Sub End Class

Client's remoting config file


As with a server, all client remoting information can reside in external config file

RemotingConfiguration.Configure (file)

<configuration> <system.runtime.remoting> <application name="SuperCalcMathService"> <client url = "http://localhost:9000/SuperCalcMathService" displayName = "SuperCalcMathService"> <activated type = "SuperCalc.Calculator,MathObjects"/> <wellknown type = "SuperCalc.BadCalculator,MathObjects" url="http://localhost:9000/SuperCalcMathService/BadCalc"/> </client> </application> </system.runtime.remoting> </configuration>

ObjRef
Runtime creates an ObjRef when you register an object with the remoting services An ObjRef contains all information required to locate and access a remote object

the strong name of the class the class's hierarchy (its parents) the names of all interfaces the class implements the object URI details of all available registered channels

Summary
A class will either not marshal, marshal by value or marshal by reference across an AppDomain boundary Three forms of activation
Server activated singleton Server activated singlecall Client activated

WellKnownServiceEntry
Holds a remotable object registered on the service.
AssemblyName Mode ObjectUri

CallContext
...Messaging.CallContext Represents the context of a remoted object
SetData GetData GetHeaders SetHeaders

Others
OneWayAttribute

Marks a method as one way for asynchronous calls

AsyncResult - Provides the information for asynchronous calls.


AsyncDelegate AsyncState IsCompleted AsyncWaitHandle

COM+ and .NET Framework

Brief Introduction to COM+


COM+ is about providing services Services provided by COM+ contexts:

Automatic transactions Object pooling Just-in-time activation (JITA) Loosely-coupled events Etc.

COM+ provides these services at the operating system level

.NET CLR and COM+


CLR introduces a newer and easier programming model for COM+
The COM+ services are still available only at the operating system/unmanaged world Transitions between managed/unmanaged layers are taken care of by System.EnterpriseServices namespace Services are made available to components using attributes

.NET and ServicedComponent


COM+ class derives from ServicedComponent

Example:

[ComVisible(true)] [ObjectPooling(MinPoolSize=2, MaxPoolSize=5)] [Guid("57F01F20-9C0C-4e63-9588-720D5D537E66")] [Transaction(TransactionOption.Required)] public class SVCCompClass : ServicedComponent

In COM+ 1.0, the list of services are not changed


In COM+ 1.5 (Microsoft Windows XP Professional and .NET server), newer services are available to leverage CLR features

Contexts
Contexts are the primary service providers
System.EnterpriseServices.ContextUtil class provides access to contexts as did CoGetObjectContext Rich set of static and member functions exposed by System.EnterpriseServices.ContextUtil

ContextUtil Class
Methods exposed by the ContextUtil class are:

SetComplete SetAbort EnableCommit DisableCommit IsCallerInRole GetNamedProperty

ContextUtil Class (2)


Some useful static members of ContextUtil class:

ActivityId IsSecurityEnabled TransactionId DeactivateOnReturn MyTransactionVote

ContextUtil Class Transaction Control


public bool TestTransMethod() { //Setting the doneness bit to true ContextUtil.DeactivateOnReturn = true; //Setting the initial transaction voting to abort ContextUtil.MyTransactionVote = TransactionVote.Abort; //Do Some Transaction work //if success, commit the work ContextUtil.MyTransactionVote = TransactionVote.Commit; return true; }

ContextUtil Class Transaction Control (2)


public void TestTransMethod2() { try { //Do Some Transaction work ContextUtil.SetComplete(); } catch (Exception ex) { ContextUtil.SetAbort(); //Handle the exception } }

ContextUtil Class Transaction Control (3)


[AutoComplete()] public void TestTransMethod2() { //Do Some Transaction work }

AutoComplete attribute calls SetComplete/SetAbort appropriately

Security
Access, authentication, and impersonation levels specified using attributes at the assembly level
[assembly:ApplicationAccessControl( AccessChecksLevel= AccessChecksLevelOption.ApplicationComponent, Authentication=AuthenticationOption.Default, ImpersonationLevel=ImpersonationLevelOption.Impersonate) ]

These attributes act on the COM+ application as a whole

Security Component Level


Component-level security enabled using the ComponentAccessControl attribute

[ComponentAccessControl]

Role-based security enabled by attribute [SecurityRole(AllUserGroup",true)]

Security SecurityCallContext class


Describes the chain of callers until the current method call CurrentCall property returns SecurityCallContext for a component SecurityCallers collection maintains the security call chain

Security SecurityCallContext Class


SecurityIdentity contains information regarding an identity in a COM+ call chain Other important methods IsSecurityEnabled, IsCallerInRole, IsUserInRole, etc.

Queued Component Programming


Enabling an application to be queued

[assembly: ApplicationQueuing(Enabled = true,QueueListenerEnabled=true)]

Enabling interface-level queuing applied on a component class:

[InterfaceQueuing(Interface = IQueuedInterface"]

Exception class specified through ExceptionClass attribute on a component class

Object Pooling
Any .NET ServicedComponent could be pooled Pooling is made available through the ObjectPooling attribute [ObjectPooling(MinPoolSize=2, MaxPoolSize=5)] public class SVCCompClass : ServicedComponent

Object Pooling (2)


The values should NOT be overridden using Component Services Explorer
Override CanBePooled method to return a vote on pooling protected override bool CanBePooled() { return true; }

Object Pooling & JITA


Both OP & JITA could be combined for a simpler and a scalable component architecture
Enabling JITA on a pooled component returns it to the pool on each method return From the client side, use Dispose() to return the object to the pool if JIT is not enabled

Remoting and COM+


Remoting communication protocol between entities in CLR Remoting could be used to access managed COM+ components

IIS as a remoting host Custom host used to invoke COM+ component

Hosting a COM+ Component Using IIS


Server-Side Configuration
Create a virtual directory out of the component directory. Assembly present in \bin subdirectory.

Expose end points and protocol using the Web.config file for the IIS VRoot.

Hosting a COM+ Component Using IIS


Web.Config File

<configuration> <system.runtime.remoting> <application> <service> <wellknown mode="SingleCall"type="SVCCompSoap.SVCCompSo apCls,SVCCompSoap objectUri="SVCCompSoap.soap"/> </service> </application> </system.runtime.remoting> </configuration>

Hosting a COM+ Component Using IIS


Client Side
Sample client code
RemotingConfiguration.Configure("SVCCompSoapCl nt.config"); SVCCompSoapCls obj = new SVCCompSoap.SVCCompSoapCls(); string str = obj.Method1(); Console.WriteLine(str.ToString()); Console.ReadLine(); obj.Dispose();

Hosting a COM+ component using IIS


Client Configuration File
<configuration> <system.runtime.remoting> <application> <client url="http://localhost/SVCCompSoap/"> <wellknown type="SVCCompSoap.SVCCompSoapCls, SVCCompSoap"

url="http://localhost/SVCCompSoap/SVCCompSoap.soap"/> </client> </application> </system.runtime.remoting> </configuration>

Remoting Using a Custom Host


This needs a listener process to expose the endpoints for the COM+ component

Remoting Using a Custom Host


Listener Process The listener process can be configured to use a Config file containing protocol and port info

Code snippet of a listener process:


static void Main(string[] args) { // TODO: Add code to start application here RemotingConfiguration.Configure("SVCCompTCPListener.c onfig"); Console.WriteLine("Listening on Port 8888"); Console.ReadLine(); }

Using a Custom Host


Listener Processs Config File Config file for the listener process
<configuration> <system.runtime.remoting> <application name="SVCCompTCP"> <service> <wellknown mode="SingleCall" type="SVCCompTCP.SVCCompTCPCls, SVCCompTCP" objectUri="SVC.rem" /> </service> <channels> <channel ref="tcp" port=8888" /> </channels> </application> </system.runtime.remoting> </configuration>

Deployment of COM+ Applications


Attributes to specify a library/server application

[assembly:ApplicationActivation(ActivationOption .Server)]

Provide a strong name to the assembly

[assembly: AssemblyKeyFile("..\\..\\SVCComp.snk")]

Deployment of COM+ Applications (2)


Add the assembly to the global assembly cache

C:\Documents and Settings> gacutil /I SVCComp.dll

Register the assembly with the COM+ infrastructure

C:\Documents and Settings> regsvcs SVCComp.dll

Components could be registered only by members of the administrators group

Deployment of Client Proxies


Usual methodology of exporting works Ensure compatibility is checked between COM+ versions (1.5 vs. 1.0) After installation, set a reference in the client application

Das könnte Ihnen auch gefallen