Title: Microsoft .NET Remoting Essentials
1Microsoft .NET Remoting Essentials
- Martin Petersen-Frey Technical LeadDeveloper
SupportMicrosoft Corporation
2Overview
- Well be covering the essentials of what you need
to know to get up and running with a Microsoft
.NET Remoting application
3Why .NET Remoting?
- Objects in different .NET application domains
cannot access each other directly. - Solves the problem of communicating between
application domains. This includes between
Application domains in the same Microsoft Win32
process, in different processes on the same
machine, and different machines. - Enables client code in one application domain to
call methods/properties of objects running in
another application domain. - The .NET analogy to DCOM.
4Why .NET Remoting? (2)
Server Application Domain
Client Application Domain
Obj new ObjectType Obj.MethodCall()
Instance of ObjectType
5.NET Remoting vs. DCOM
- Both enable object-oriented communication between
processes. - .NET Remoting has a completely different
architecture. - .NET Remoting is more flexible (more activation
and deployment options) - .NET Remoting is customizable (you can add
logging or other features) - .NET Remoting requires more explicit client and
server application configuration. DCOM simply
allows you to change a registry entry. DCOM
clients do not need to know the object is being
remoted. - .NET Remoting has no built-in support for
security.
6Remoting Application Development Flow
- Write the components that you wish to make
remotely accessible into a .NET DLL. - Configure any managed executable to host those
components. - Write the client(s) that call the components.
Unlike DCOM, the client application must
configure the object to be remoted.
7Writing Remotable Components
- To make an object remotable, simply derive it
from MarshallByRefObject - Makes the object externally creatable
- Allows it to be passed in method/property calls
- Causes the object to run in the application
domain that created it - What in an object is remoted?
- Public methods (non-static)
- Public properties (non-static)
- Public fields (non-static)
8Remotable Object Example in C
public class MBRObject MarshalByRefObject str
ing MemberData public MBRObject()
public MBRObject(string ctor) MemberData
ctor public string GetData () return
MemberData public void SetData (string
NewValue) MemberData NewValue
9Writing Serializable Components
- At times, it is useful to be able to pass an
object via remoting so that the receiving
application domain receives a local copy of the
object and can work with its state locally.This
is known as marshalling an object by value in the
DCOM world.
10Writing Serializable Components (2)
- To make an object marshall itself by value, make
it serializable - Use the Serializable attribute or implement
ISerializable - Causes object state to be marshalled to a copy of
the object in the client application domain. - The Serializable attribute causes the remoting
system to do a member-wise copy of an objects
public and private member variables - Member objects must be serializable themselves
- ISerializable gives you more flexibility by
allowing use of name/value pairs - Allows object to be passed in method/property
calls - Requires that the serialized object assembly be
referenced by the client
11Serializable Object Example in C
Serializable public class MBVObject string
MemberData public MBVObject() MemberData
"Initial State" public void SetMBVData
(string NewData) MemberData NewData public
string GetMBVData () return MemberData
// function that returns a Serializable
object public MBVObject GetMBVObject() MBVObjec
t o new MBVObject() o.SetMBVData ("Server
side data") return o
12Configuring Remoting Hosts
- A Remoting host can be any managed .exe
- To be a host, an .exe file must do two things
- Configure a remoting channel
- Register each of the types it will make available
via remoting - Can be done programmatically or using config files
13Configuring a Remoting Channel in a Remoting Host
- A channel is the inter-AppDomain transport
mechanism. - Can be done programmatically or via a config
files. - There are two choices HTTP, or TCP. You must
select one and configure a host to use it. Both
must be configured to listen on a TCP port. - Which one should you use?
- The TCP channel is much faster than the HTTP
channel. It uses binary formatting for remoting
method calls. - The HTTP channel is required for calling objects
hosted in IIS. Because it formats method calls
using SOAP, it can also be used for third-party
interoperability.
14Registering Remoting Objects in a Remoting Host
- Can be done programmatically or via a config file
- Object types can be configured to have several
activation behaviors - Singleton A single object instance handles all
client calls - SingleCall Each client call is serviced by a new
object instance similar to JIT activation in COM - Client activated Each object instance created in
a client corresponds to an object instance in the
server - Singleton and SingleCall types are known as
WellKnown object types
15Example of Channel and Type Registration For a
Remoting Host
ltconfigurationgt ltsystem.runtime.remotinggt
ltapplicationgt ltservicegt
ltwellknown
mode"SingleCall"
type"RemotableObjects.MBRObject,RemotableObjects"
objectUri"SomeMBRObject"
/gt lt/servicegt ltchannelsgt
ltchannel port"8080" ref"http"
/gt lt/channelsgt
lt/applicationgt lt/system.runtime.remotinggt lt/co
nfigurationgt
// set contents of .config file RemotingConfigurat
ion.Configure (HostConfiguration.Config")
16Configuring Remoting Clients
- To use a remoted object type, a client must
register it and specify the URL where it can be
found. This can be done programmatically or via a
config file. - Once a type has been registered, objects can be
created and used as though they were local
objects. - For WellKnown objects, you have the option of
using Activator.GetObject() instead of New to
create a remote object reference. GetObject
immediately returns a proxy to the object without
creating the object first. This avoids
unnecessary network roundtrips.
17Example of Type Registration for a Remoting Client
ltconfigurationgt ltsystem.runtime.remotinggt
ltapplicationgt ltclientgt
ltwellknown
type"RemotableObjects.MBRObject,RemotableObjects"
url"http//localhost8080/S
omeMBRObject" /gt lt/clientgt
lt/applicationgt lt/system.runtime.remotinggt lt/co
nfigurationgt
// Set contents of config file RemotingConfigurat
ion.Configure ("ClientConfiguration.Config")
18Client Metadata Deployment Options
- For a client to use a remoted object, it must
have the objects metadata - Object metadata can be deployed to a client
application in the following ways - Include the remoted object assembly with client
applications. This is commonly done now in the
unmanaged COM/COM world. - Specify interfaces in a separate assembly and
reference that assembly in both client and server
applications. The remoted objects must expose
their functionality via those interfaces. - Generate metadata-only assemblies and have the
client applications reference them. They are
generated with Soapsuds.exe. They use the HTTP
remoting channel and the SOAP formatter.
19Hosting Objects in IIS
- IIS can be used as a remoting host
- All remoting object types can be specified
- This allows remoting objects to be exposed as Web
Services - WSDL is returned in response to WSDL queries
- For WellKnown objects, use http//ltComputergt/ltVir
tDirgt/ObjectURIgt?wsdl - For Client Activated objects, use
http//ltComputergt/ltVirtDirgt/RemoteApplicationMetad
ata.rem?wsdl - The object is accessible to SOAP clients
- SOAP clients cannot access Client Activated
objects - .NET Remoting objects use RPC SOAP encoding
20Hosting Objects in IIS (2)
- Clients can use the HTTP channel with either the
binary or SOAP formatters - When creating IIS hosted .NET objects, you cannot
specify constructor parameters
21Hosting in IIS (3)
- Hosting objects in IIS is simple
- Put the DLL containing the remotable objects into
the \bin directory of an IIS Web application or
put it in the GAC. - Put the remoting configuration section into the
Web.Config file for the Web application. - Alternatively, the Gobal.asax file can contain an
Application_Start() function where you can
register your objects in the same way you would
in an .exe host. - You should not specify a channel. IIS already
listens on port 80. Specifying a port for a
channel causes exceptions to be thrown when new
IIS worker processes are started. - WellKnown object URIs must end with .rem or .soap.
22Object Life Time Management
- Remoting system must know when clients no longer
need remoted object instances so that they can be
garbage collected. - Different from DCOM which uses pinging to
determine if clients are still alive. - Introduces the concept of a lease. In this
scheme, objects time out regardless of whether or
not clients are still using them. Clients
optionally have the option of renewing a lease or
taking control of it themselves. - Leases apply only to Singleton and Client
Activated objects.
23Object Lifetime Management Using Lease Timeouts
- By default, when an object is created, it gets an
initial lease of five minutes - By default, each call renews the lease to two
minutes or the current lease time, whichever is
greater - Lease times can be controlled through the
ltlifetimegt section of a config file - Individual objects can control their own lease
times by overriding MarshalByRefObject.
InitializeLifetimeService()
ltlifetime leaseTime"30S" renewOnCallTime"10S
sponsorshipTimeout"2M leaseManagerPollTime"20S
/gt
public override object InitializeLifetimeService()
ILease lease (ILease)base.InitializeLifetime
Service() if (lease.CurrentState
LeaseState.Initial) lease.InitialLeaseTime
TimeSpan.FromSeconds(20) lease.RenewOnCallTim
e TimeSpan.FromSeconds(10) return lease
24Object Lifetime Management Using Lease Renewal
- Clients can explicitly renew leases using the
RemotingServices.GetLifetimeService() API and the
ILease interface
ILease lease (ILease)RemotingServices.GetLifetim
eService(RemoteObject) TimeSpan expireTime
lease.Renew(TimeSpan.FromSeconds(60))
25Object Lifetime Management Using A Lease Sponsor
- Clients can also use a lease sponsor to directly
control the life of a lease. - A sponsor object must be submitted to the lease
manager in the object host. The lease manager
periodically calls the sponsor requesting it to
renew the lease. - Typically, a client will submit a sponsor object
to keep an object alive for as long as it is
alive. This causes the host lease manager to call
the client back periodically to have it renew the
lease. Much more complex scenarios are possible.
public class Form1 System.Windows.Forms.Form,
ISponsor TimeSpan ISponsor.Renewal(ILease
lease) return new TimeSpan(0,1,0) //
Submit the sponsor object private void Register
Sponsor () ILease lease
(ILease)RemotingServices.GetLifetimeService(Remote
Obj) lease.Register ((ISponsor) this)
26.NET Remoting Security
- .NET Remoting has no security built into it!
- Remoting relies on the remoting host to provide
security - The only host that provides security for remoted
objects at present is IIS therefore, secured
objects must be hosted in IIS - The HTTP remoting channel supports the IIS
security mechanisms - In IIS, standard ASP.NET security mechanisms can
be used
27.NET Remoting Security (2)
- To secure remoted objects via IIS, do the
following - Configure the objects in IIS as you normally
would. - Set the desired security settings for the IIS
application. Your authentication choices are
Anonymous, Integrated, Basic, or Digest. For
intranet scenarios, Integrated only is a good
choice. - Configure the client to use the correct
authentication method. - To use Integrated security, you must configure
the client to use the HTTP channel and set the
use useDefaultCredentials property to TRUE. - You can also programmatically set the
credentials property for a channel to a
NetworkCredential or a CredentialCache object to
enable Integrated, Basic, and Digest
authentication. - If IIS security is enabled, only clients using a
properly configured HTTP channel can make calls.
28.NET Remoting Security (3)
- Configure the Web.config file to allow or deny
access to the IIS application using the following
tags in Web.Config - ltauthenticationgt
- Determines which identity will be placed in the
HttpContext. It must have attribute mode
Windows. - ltauthorizationgt
- Allows/denies access based on the identity placed
in HttpContext. It contains comma-separated lists
of users. - ltidentitygt
- This is an optional setting. It determines what
identity the thread runs as. If the attribute
impersonatetrue is set, the caller will be
impersonated for the call. This is useful for ACL
checking.
29.NET Remoting Security (4)
- Client-side configuration tags
ltchannelsgt ltchannel ref"http"
useDefaultCredentials"true" /gt lt/channelsgt
ltsystem.webgt ltauthentication mode"Windows"
/gt ltidentity impersonate"true"
/gt ltauthorizationgt ltallow usersDomain\user"/gt
ltdeny users""/gt lt/authorizationgt lt/system.we
bgt
30Using CallContext
- CallContext is a set of named objects that flow
with the execution code path. Clients can place
items into the context. This context flows across
local function calls and to remote objects where
it can be retrieved and modified. It is flowed
back to a remoting caller when a call returns. - If items placed into the context are to be flowed
to remote objects, they must be objects that
implement the ILogicalThreadAffinitive interface
and are serializable.
// in client CallContext.SetData(ItemName,
ItemObj) // in server ItemObj (ItemType)
CallContext.GetData(ItemName)
31Dynamically Publishing a WellKnown Object
- WellKnown objects cannot be invoked from a client
with a non-default constructor. You can create an
object using any constructor you wish, intialize
it anyway you wish, and then make it available to
clients. - Use RemotingServices.Marshal to publish an
existing object instance and Remoting
Services.Disconnect to disconnect it.
// in the remoting host create the object, then
publish it RemtableType object1 new
RemotableType(Constructor Parameters)
RemotingServices.Marshal(object1, "object1Uri")
// Now unpublish it RemotingServices.Disc
onnect(object1)
32- Thank you for joining us for todays Microsoft
Support - WebCast.
- For information about all upcoming Support
WebCasts - and access to the archived content (streaming
media - files, PowerPoint slides, and transcripts),
please visit - http//support.microsoft.com/webcasts/
- We sincerely appreciate your feedback. Please
send any - comments or suggestions regarding the Support
- WebCasts to supweb_at_microsoft.com