System.Runtime.Remoting.RemotingServices Class

Assembly: Mscorlib.dll
Namespace: System.Runtime.Remoting
Summary
Provides several methods for using and publishing remoted objects and proxies. This class cannot be inherited.
C# Syntax:
public sealed class RemotingServices
Remarks
Unless you are a service provider dealing with issues such as activation, lifetime management, or transactions, you do not need to distinguish between proxy references and object references. The remoting infrastructure uses transparent proxies that give the impression that the remote objects reside in the client's space. Proxies achieve this by forwarding calls made on them to the real objects at remote locations.
See also:
System.Runtime.Remoting Namespace

System.Runtime.Remoting.RemotingServices Member List:

Public Methods
Connect Overloaded:
Connect(Type classToProxy, string url)

Takes in the Type and URL of the well-known object to which you want to connect to, and creates a proxy object for it.
Connect Overloaded:
Connect(Type classToProxy, string url, object data)

Takes in the Type and URL of the well-known object to which you want to connect, and as well as channel specific data, and creates a proxy for it.
Disconnect Stops an object from receiving any further messages through the registered remoting channels.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
ExecuteMessage Connects to the specified remote object, and executes the provided IMethodCallMessage on it.
GetEnvoyChainForProxy Returns a chain of envoy sinks that should be used when sending messages to the remote object represented by the specified proxy.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService Returns a lifetime service object that controls the lifetime policy of the specified object.
GetMethodBaseFromMethodMessage Returns the method base from the given IMethodMessage.
GetObjectData Serializes the specified marshal by reference object into the provided SerializationInfo.
GetObjectUri Retrieves the URI for the specified object.
GetObjRefForProxy Returns the ObjRef that represents the remote object from the specified proxy.
GetRealProxy Returns the real proxy backing the specified transparent proxy.
GetServerTypeForUri Returns the Type of the object with the specified URI.
GetSessionIdForMethodMessage Retrieves a session ID for a message.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
IsMethodOverloaded Returns a Boolean value indicating whether the method in the given message is overloaded.
IsObjectOutOfAppDomain Returns a Boolean value indicating whether the object specified by the given transparent proxy is contained in a different AppDomain than the object that called the current method.
IsObjectOutOfContext Returns a Boolean value indicating whether the object represented by the given proxy is contained in a different context than the object that called the current method.
IsOneWay Returns a Boolean value indicating whether the client that called the method specified in the given message is waiting for the server to finish processing the method before continuing execution.
IsTransparentProxy Returns a Boolean value indicating whether the given object is a transparent proxy or a real object.
LogRemotingStage Public reserved method, for internal use only.
Marshal Overloaded:
Marshal(MarshalByRefObject Obj)

Takes a MarshalByRefObject, registers it with the remoting infrastructure, and converts it into an instance of the ObjRef class.
Marshal Overloaded:
Marshal(MarshalByRefObject Obj, string URI)

Converts the given MarshalByRefObject into an instance of the ObjRef class with the specified URI.
Marshal Overloaded:
Marshal(MarshalByRefObject Obj, string ObjURI, Type RequestedType)

Takes a MarshalByRefObject and converts it into an instance of the ObjRef class with the specified URI, and the provided Type.
SetObjectUriForMarshal Sets the URI for the subsequent call to the RemotingServices.Marshal method.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Unmarshal Overloaded:
Unmarshal(ObjRef objectRef)

Takes an ObjRef and creates a proxy object out of it.
Unmarshal Overloaded:
Unmarshal(ObjRef objectRef, bool fRefine)

Takes an ObjRef and creates a proxy object out of it, refining it to the type on the server.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Runtime.Remoting.RemotingServices Member Details

Overloaded Method: Connect(
   Type classToProxy,
   string url
)
Summary
Takes in the Type and URL of the well-known object to which you want to connect to, and creates a proxy object for it.
C# Syntax:
public static object Connect(
   Type classToProxy,
   string url
);
Parameters:

classToProxy

The Type of a well-known object on the server end to which you want to connect.

url

The URL of the server class.

Return Value:
A proxy to the remote object that points to an endpoint served by the specified well-known object.
Remarks
The returned proxy object points to an endpoint served by the specified well-known object. No messages are sent over the network until a method is called on the proxy.
Example
The following example demonstrates how to use the RemotingServices.Connect method to create a proxy to a well-known object.
      Console.WriteLine("Connecting to SampleNamespace.SampleWellKnown.");
      
      SampleWellKnown proxy = 
         (SampleWellKnown)RemotingServices.Connect(typeof(SampleWellKnown), SERVER_URL);

      Console.WriteLine("Connected to SampleWellKnown");
      
      // Verifies that the object reference is to a transparent proxy.
      if (RemotingServices.IsTransparentProxy(proxy))
          Console.WriteLine("proxy is a reference to a transparent proxy.");
      else
          Console.WriteLine("proxy is not a transparent proxy.  This is unexpected.");
      
      // Calls a method on the server object.
      Console.WriteLine("proxy.Add returned {0}.", proxy.Add(2, 3));

    

Return to top


Overloaded Method: Connect(
   Type classToProxy,
   string url,
   object data
)
Summary
Takes in the Type and URL of the well-known object to which you want to connect, and as well as channel specific data, and creates a proxy for it.
C# Syntax:
public static object Connect(
   Type classToProxy,
   string url,
   object data
);
Parameters:

classToProxy

The Type of the well-known object to which you want to connect.

url

The URL of the well-known object.

data

Channel specific data. Can be null.

Return Value:
A proxy that points to an endpoint that is served by the requested well-known object.
Remarks
The returned proxy object points to an endpoint served by the specified well-known object. No messages are sent over the network until a method is called on the proxy.

The data object is used to communicate information to the channel, and is passed to the IChannelSender.CreateMessageSink method.

Return to top


Method: Disconnect(
   MarshalByRefObject obj
)
Summary
Stops an object from receiving any further messages through the registered remoting channels.
C# Syntax:
public static bool Disconnect(
   MarshalByRefObject obj
);
Parameters:

obj

Object to disconnect from its channel.

Return Value:
true if the object was disconnected from the registered remoting channels successfully; otherwise, false.
Exceptions
Exception Type Condition
ArgumentNullException The obj parameter is null.
ArgumentException The obj parameter is a proxy.
Example
The following example demonstrates how to use the RemotingServices.Disconnect method to disconnect an object from the remoting channels.
      TcpChannel channel = new TcpChannel(9000);
      ChannelServices.RegisterChannel(channel);

      SampleWellKnown objectWellKnown = new SampleWellKnown();
      
      // After the channel is registered, the object needs to be registered
      // with the remoting infrastructure.  So, Marshal is called.
      ObjRef objrefWellKnown = RemotingServices.Marshal(objectWellKnown, "objectWellKnownUri");
      Console.WriteLine("An instance of SampleWellKnown type is published at {0}.", objrefWellKnown.URI);

      Console.WriteLine("Press enter to unregister SampleWellKnown, so that it is no longer available on this channel.");
      Console.ReadLine();
      RemotingServices.Disconnect(objectWellKnown);

      Console.WriteLine("Press enter to end the server process.");
      Console.ReadLine();

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ExecuteMessage(
   MarshalByRefObject target,
   IMethodCallMessage reqMsg
)
Summary
Connects to the specified remote object, and executes the provided IMethodCallMessage on it.
C# Syntax:
public static IMethodReturnMessage ExecuteMessage(
   MarshalByRefObject target,
   IMethodCallMessage reqMsg
);
Parameters:

target

The remote object whose method you want to call.

reqMsg

A method call message to the specified remote object's method.

Return Value:
The response of the remote method.
Remarks
The current method is used in special cases by the server to forward the specified method call to another, possibly remote, object. This method can be called only when the caller is in the appropriate context.
Example
The following example demonstrates how to use the RemotingServices.ExecuteMessage method to forward method calls to remote objects.
   public void ProcessMessageStart(IMessage requestMessage, bool bClientSide, bool bAsyncCall) {
      
      Console.WriteLine("\nProcessMessageStart");
      Console.WriteLine("requestMessage = {0}", requestMessage);
      
      try {
         Console.WriteLine("SessionId = {0}.",
             RemotingServices.GetSessionIdForMethodMessage((IMethodMessage)requestMessage));
      }
      catch (InvalidCastException) {
         Console.WriteLine("The requestMessage is not an IMethodMessage.");
      }

      IMethodCallMessage requestMethodCallMessage;
      
      try {
         requestMethodCallMessage = (IMethodCallMessage)requestMessage;
         // Prints the details of the IMethodCallMessage to the console.
         Console.WriteLine("\nMethodCall details");
         Console.WriteLine("Uri = {0}", requestMethodCallMessage.Uri);
         Console.WriteLine("TypeName = {0}", requestMethodCallMessage.TypeName);
         Console.WriteLine("MethodName = {0}", requestMethodCallMessage.MethodName);
         Console.WriteLine("ArgCount = {0}", requestMethodCallMessage.ArgCount);
         
         Console.WriteLine("MethodCall.Args");
         foreach(object o in requestMethodCallMessage.Args)
             Console.WriteLine("\t{0}", o);
         
         // Sends this method call message to another server to replicate
         // the call at the second server.
         if (requestMethodCallMessage.Uri == replicatedServiceUri) {
            
            SampleService replicationService = 
               (SampleService)Activator.GetObject(typeof(SampleService), 
               replicationServerUrl + replicatedServiceUri);
            
            IMethodReturnMessage returnMessage = 
               RemotingServices.ExecuteMessage(replicationService, requestMethodCallMessage);
            
            // Prints the results of the method call stored in the IMethodReturnMessage.
            Console.WriteLine("\nMessage returned by ExecuteMessage.");
            Console.WriteLine("\tException = {0}", returnMessage.Exception);
            Console.WriteLine("\tReturnValue = {0}", returnMessage.ReturnValue);
            Console.WriteLine("\tOutArgCount = {0}", returnMessage.OutArgCount);
            Console.WriteLine("Return message OutArgs");
            
            foreach(object o in requestMethodCallMessage.Args)
               Console.WriteLine("\t{0}", o);
         }
      }
      catch (InvalidCastException) {
          Console.WriteLine("The requestMessage is not a MethodCall");
      }
   }

    

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~RemotingServices();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnvoyChainForProxy(
   MarshalByRefObject obj
)
Summary
Returns a chain of envoy sinks that should be used when sending messages to the remote object represented by the specified proxy.
C# Syntax:
public static IMessageSink GetEnvoyChainForProxy(
   MarshalByRefObject obj
);
Parameters:

obj

The proxy of the remote object that requested envoy sinks are associated with.

Return Value:
A chain of envoy sinks associated with the specified proxy.
Remarks
Envoy sinks are sinks sent along with the ObjRef of an object that is used when returning messages to that object. The current method returns the envoy sinks that are used during communication between the proxy of the object and the object itself.
See also:
IEnvoyInfo | ObjRef

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService(
   MarshalByRefObject obj
)
Summary
Returns a lifetime service object that controls the lifetime policy of the specified object.
C# Syntax:
public static object GetLifetimeService(
   MarshalByRefObject obj
);
Parameters:

obj

The object to obtain lifetime service for.

Return Value:
The object that controls the lifetime of obj.
Remarks
For the default lifetime service the returned object will be an object of type ILease. If the obj parameter is null, the method returns null.
Example
The following example demonstrates how to use the RemotingServices.GetLifetimeService method to get a lifetime lease for the specified object.
using System;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Lifetime;
using TimerSample;

namespace GroupCoffeeTimer {
    public class TimerClient : MarshalByRefObject, ISponsor {
        public static void Main() {
            TimerClient myClient = new TimerClient();
        }

        public TimerClient() {
            // Registers the HTTP Channel so that this client can receive
            // events from the remote service.
            ChannelServices.RegisterChannel(new HttpChannel(0));
            WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(TimerService), "http://localhost:9000/MyService/TimerService.soap");
            RemotingConfiguration.RegisterWellKnownClientType(remoteType);
            
            TimerService groupTimer = new TimerService();
            groupTimer.MinutesToTime = 4.0; 

            // Registers this client as a lease sponsor so that it can
            // prevent the expiration of the TimerService.
            ILease leaseObject = (ILease)RemotingServices.GetLifetimeService(groupTimer);
            leaseObject.Register(this);
            
            // Subscribes to the event so that the client can receive notifications from the server.
            groupTimer.TimerExpired += new TimerExpiredEventHandler(OnTimerExpired);
            Console.WriteLine("Connected to TimerExpired event");
            
            groupTimer.Start();
            Console.WriteLine("Timer started for {0} minutes.", groupTimer.MinutesToTime);
            Console.WriteLine("Press enter to end the client process.");
            Console.ReadLine();
        }
        
        public void OnTimerExpired (object source, TimerServiceEventArgs e) {
            Console.WriteLine("TimerHelper.OnTimerExpired: {0}", e.Message);
        }

        public TimeSpan Renewal(ILease lease) {
            Console.WriteLine("TimerClient: Renewal called.");
            return TimeSpan.FromMinutes(0.5);
        }
    }
}

    

Return to top


Method: GetMethodBaseFromMethodMessage(
   IMethodMessage msg
)
Summary
Returns the method base from the given IMethodMessage.
C# Syntax:
public static MethodBase GetMethodBaseFromMethodMessage(
   IMethodMessage msg
);
Parameters:

msg

The method message to extract the method base from.

Return Value:
The method base extracted from the msg parameter.
Remarks
This determines the method base from the IMethodMessage.TypeName, IMethodMessage.MethodName, and IMethodMessage.MethodSignature properties of IMethodMessage and is used by classes implementing the IMethodMessage interface. Consumers of IMethodMessage classes should reference the IMethodMessage.MethodBase property.
.NET Framework Security:
ReflectionPermission for extraction of reflection information on members of a type that are not visible. Associated enumeration: ReflectionPermissionFlag.TypeInformation.

Return to top


Method: GetObjectData(
   object obj,
   SerializationInfo info,
   StreamingContext context
)
Summary
Serializes the specified marshal by reference object into the provided SerializationInfo.
C# Syntax:
public static void GetObjectData(
   object obj,
   SerializationInfo info,
   StreamingContext context
);
Parameters:

obj

The object to serialize.

info

The SerializationInfo into which the object is serialized.

context

The source and destination of the serialization.

Exceptions
Exception Type Condition
ArgumentNullException The obj or info parameter is null.
See also:
ISerializable

Return to top


Method: GetObjectUri(
   MarshalByRefObject obj
)
Summary
Retrieves the URI for the specified object.
C# Syntax:
public static string GetObjectUri(
   MarshalByRefObject obj
);
Parameters:

obj

The MarshalByRefObject for which a URI is requested.

Return Value:
The URI of the specified object if it has one, or null if the object has not yet been marshaled.
Example
      RealProxy proxy = RemotingServices.GetRealProxy(obj);
      Console.WriteLine("Real proxy type: {0}", proxy.GetProxiedType().ToString());

      Console.WriteLine("Object URI: {0}", RemotingServices.GetObjectUri(obj).ToString());

      IMessageSink  msgSink = RemotingServices.GetEnvoyChainForProxy(obj).NextSink;

    

Return to top


Method: GetObjRefForProxy(
   MarshalByRefObject obj
)
Summary
Returns the ObjRef that represents the remote object from the specified proxy.
C# Syntax:
public static ObjRef GetObjRefForProxy(
   MarshalByRefObject obj
);
Parameters:

obj

A proxy connected to the object you want to create an ObjRef for.

Return Value:
An ObjRef representing the remote object the specified proxy is connected to, or null if the object or proxy have not been marshaled.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. During unmarshaling, the ObjRef is parsed to extract the method information of the remote object and both the transparent proxy and RealProxy objects are created.

ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remote application where the object is located.

Example
The following example demonstrates how to get an ObjRef instance for the specified object.
        ObjRef objRefSample = RemotingServices.GetObjRefForProxy(myRemoteObject);
        
        Console.WriteLine("***ObjRef Details***");
        Console.WriteLine("URI:\t{0}", objRefSample.URI);
        
        object[] channelData = objRefSample.ChannelInfo.ChannelData;
        
        Console.WriteLine("Channel Info:");
        foreach(object o in channelData)
            Console.WriteLine("\t{0}", o.ToString());
        
        IEnvoyInfo envoyInfo = objRefSample.EnvoyInfo;
        
        if (envoyInfo == null) {
            Console.WriteLine("This ObjRef does not have envoy information.");
        }
        else {
            IMessageSink envoySinks = envoyInfo.EnvoySinks;
            Console.WriteLine("Envoy Sink Class: {0}", envoySinks);
        }
        
        IRemotingTypeInfo typeInfo = objRefSample.TypeInfo;
        Console.WriteLine("Remote type name: {0}", typeInfo.TypeName);
        
        Console.WriteLine("Can my object cast to a Bitmap? {0}",
            typeInfo.CanCastTo(typeof(System.Drawing.Bitmap), objRefSample));

    

Return to top


Method: GetRealProxy(
   object proxy
)
Summary
Returns the real proxy backing the specified transparent proxy.
C# Syntax:
public static RealProxy GetRealProxy(
   object proxy
);
Parameters:

proxy

A transparent proxy.

Return Value:
The real proxy instance backing the transparent proxy.
Remarks
A client that uses an object across any kind of remoting boundary is actually using a transparent proxy for the object. The transparent proxy gives the impression that the actual object resides in the client's space. It achieves this by forwarding calls made on it to the real object using the remoting infrastructure.

The transparent proxy is backed by an instance of a managed runtime class of type RealProxy. The RealProxy implements a part of the functionality needed to forward the operations from the transparent proxy. Note that a proxy object inherits the associated semantics of managed objects such as garbage collection, support for fields and methods, and can be extended to form new classes. The proxy acts as an object of the same class as the remote object (transparent proxy), and is also a managed object.

See also:
RealProxy | ObjRef

Return to top


Method: GetServerTypeForUri(
   string URI
)
Summary
Returns the Type of the object with the specified URI.
C# Syntax:
public static Type GetServerTypeForUri(
   string URI
);
Parameters:

URI

The URI of the object whose Type is requested.

Return Value:
The Type of the object with the specified URI.
Remarks
Since remoting identifies endpoints using URIs, the RemotingServices.GetServerTypeForUri method is very useful in the pluggable parts of the remoting infrastructure (for example channel sinks, dynamic sinks, and context sinks) that use IMessage objects, since the current method will return the associated type object from the URI.
Example
      Console.WriteLine("Server type: {0}",
                        RemotingServices.GetServerTypeForUri(myObjectUri));

    
.NET Framework Security:
ReflectionPermission for extraction of reflection information on members of a type that are not visible. Associated enumeration: ReflectionPermissionFlag.TypeInformation.

Return to top


Method: GetSessionIdForMethodMessage(
   IMethodMessage msg
)
Summary
Retrieves a session ID for a message.
C# Syntax:
public static string GetSessionIdForMethodMessage(
   IMethodMessage msg
);
Parameters:

msg

The IMethodMessage for which a session ID is requested.

Return Value:
A session ID string that uniquely identifies the current session.
Remarks
The same session ID might be returned for objects in the same application, but this method will never return the same session ID for two objects in different remote applications.

For more information on identifying sessions and session IDs, see the conceptual topic at MSDN: sessionstate.

Example
The following example demonstrates how to get the session ID string for the current session.
   public void ProcessMessageStart(IMessage requestMessage, bool bClientSide, bool bAsyncCall) {
      
      Console.WriteLine("\nProcessMessageStart");
      Console.WriteLine("requestMessage = {0}", requestMessage);
      
      try {
         Console.WriteLine("SessionId = {0}.",
             RemotingServices.GetSessionIdForMethodMessage((IMethodMessage)requestMessage));
      }
      catch (InvalidCastException) {
         Console.WriteLine("The requestMessage is not an IMethodMessage.");
      }

      IMethodCallMessage requestMethodCallMessage;
      
      try {
         requestMethodCallMessage = (IMethodCallMessage)requestMessage;
         // Prints the details of the IMethodCallMessage to the console.
         Console.WriteLine("\nMethodCall details");
         Console.WriteLine("Uri = {0}", requestMethodCallMessage.Uri);
         Console.WriteLine("TypeName = {0}", requestMethodCallMessage.TypeName);
         Console.WriteLine("MethodName = {0}", requestMethodCallMessage.MethodName);
         Console.WriteLine("ArgCount = {0}", requestMethodCallMessage.ArgCount);
         
         Console.WriteLine("MethodCall.Args");
         foreach(object o in requestMethodCallMessage.Args)
             Console.WriteLine("\t{0}", o);
         
         // Sends this method call message to another server to replicate
         // the call at the second server.
         if (requestMethodCallMessage.Uri == replicatedServiceUri) {
            
            SampleService replicationService = 
               (SampleService)Activator.GetObject(typeof(SampleService), 
               replicationServerUrl + replicatedServiceUri);
            
            IMethodReturnMessage returnMessage = 
               RemotingServices.ExecuteMessage(replicationService, requestMethodCallMessage);
            
            // Prints the results of the method call stored in the IMethodReturnMessage.
            Console.WriteLine("\nMessage returned by ExecuteMessage.");
            Console.WriteLine("\tException = {0}", returnMessage.Exception);
            Console.WriteLine("\tReturnValue = {0}", returnMessage.ReturnValue);
            Console.WriteLine("\tOutArgCount = {0}", returnMessage.OutArgCount);
            Console.WriteLine("Return message OutArgs");
            
            foreach(object o in requestMethodCallMessage.Args)
               Console.WriteLine("\t{0}", o);
         }
      }
      catch (InvalidCastException) {
          Console.WriteLine("The requestMessage is not a MethodCall");
      }
   }

    
See also:
MSDN: sessionstate

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: IsMethodOverloaded(
   IMethodMessage msg
)
Summary
Returns a Boolean value indicating whether the method in the given message is overloaded.
C# Syntax:
public static bool IsMethodOverloaded(
   IMethodMessage msg
);
Parameters:

msg

The message containing a call to the method in question.

Return Value:
true if the method called in msg is overloaded; otherwise, false.

Return to top


Method: IsObjectOutOfAppDomain(
   object tp
)
Summary
Returns a Boolean value indicating whether the object specified by the given transparent proxy is contained in a different AppDomain than the object that called the current method.
C# Syntax:
public static bool IsObjectOutOfAppDomain(
   object tp
);
Parameters:

tp

The object to check.

Return Value:
true if the object is out of the current AppDomain; otherwise, false.
Remarks
For information on AppDomains see the conceptual topic at MSDN: applicationdomains.
Example
			// Create a remote version of TempConverter.Converter.
			TempConverter.Converter converter1 =
					(TempConverter.Converter) Activator.GetObject(
					typeof(TempConverter.Converter),
					"http://localhost:8085/TempConverter");
			// Create a local version of TempConverter.Converter.
			TempConverter.Converter converter2 = new TempConverter.Converter();

			// Returns true, converter1 is remote and in a different appdomain.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(
									converter1); 

			// Returns false, converter2 is local and running in this appdomain.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(
									converter2); 

			// Returns true, converter1 is remote and in a different context.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfContext(
									converter1);

			// Returns false, converter2 is local and running in this context.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfContext(
									converter2);

    
See also:
MSDN: applicationdomains

Return to top


Method: IsObjectOutOfContext(
   object tp
)
Summary
Returns a Boolean value indicating whether the object represented by the given proxy is contained in a different context than the object that called the current method.
C# Syntax:
public static bool IsObjectOutOfContext(
   object tp
);
Parameters:

tp

The object to check.

Return Value:
true if the object is out of the current context; otherwise, false.
Remarks
A context is an ordered sequence of properties that define an environment for the objects that reside inside it. Contexts are created during the activation process for objects that are configured to require certain automatic services such synchronization, transactions, just-in-time activation, security, and so on. Multiple objects can live inside a context.
Example
			// Create a remote version of TempConverter.Converter.
			TempConverter.Converter converter1 =
					(TempConverter.Converter) Activator.GetObject(
					typeof(TempConverter.Converter),
					"http://localhost:8085/TempConverter");
			// Create a local version of TempConverter.Converter.
			TempConverter.Converter converter2 = new TempConverter.Converter();

			// Returns true, converter1 is remote and in a different appdomain.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(
									converter1); 

			// Returns false, converter2 is local and running in this appdomain.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(
									converter2); 

			// Returns true, converter1 is remote and in a different context.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfContext(
									converter1);

			// Returns false, converter2 is local and running in this context.
			System.Runtime.Remoting.RemotingServices.IsObjectOutOfContext(
									converter2);

    
See also:
Context

Return to top


Method: IsOneWay(
   MethodBase method
)
Summary
Returns a Boolean value indicating whether the client that called the method specified in the given message is waiting for the server to finish processing the method before continuing execution.
C# Syntax:
public static bool IsOneWay(
   MethodBase method
);
Parameters:

method

The method in question.

Return Value:
true if the method is one way; otherwise, false.
Remarks
When a one way method is called, the client does not wait for the server to finish processing the message. The client method returns to the application with no knowledge of whether or not the server will successfully process the message. Methods are marked as one way using the OneWayAttribute.

One way methods cannot have a return value or any out parameters.

Example
public class HelloServer : MarshalByRefObject {

   public HelloServer() {
      Console.WriteLine("HelloServer activated.");
   }

   [OneWay()]
   public void SayHelloToServer(string name) {
      Console.WriteLine("Client invoked SayHelloToServer(\"{0}\").", name);
   }   

   // Note the lack of the OneWayAttribute adornment on this method.
   public string SayHelloToServerAndWait(string name) {
      Console.WriteLine("Client invoked SayHelloToServerAndWait(\"{0}\").", name);

      Console.WriteLine(
         "Client waiting for return? {0}",
         RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()) ? "No" : "Yes"
      );

      return "Hi there, " + name + ".";
   }
}

    

Return to top


Method: IsTransparentProxy(
   object proxy
)
Summary
Returns a Boolean value indicating whether the given object is a transparent proxy or a real object.
C# Syntax:
public static bool IsTransparentProxy(
   object proxy
);
Parameters:

proxy

The reference to the object to check.

Return Value:
A Boolean value indicating whether the object specified in the proxy parameter is a transparent proxy or a real object.
Remarks
A client that uses an object across any kind of a remoting boundary is actually using a transparent proxy for the object. The transparent proxy gives the impression that the actual object resides in the client's space. It achieves this by forwarding calls made on it to the real object using the remoting infrastructure.

The transparent proxy is itself housed by an instance of a managed runtime class of type RealProxy. The RealProxy implements a part of the functionality needed to forward the operations from the transparent proxy. A proxy object inherits the associated semantics of managed objects such as garbage collection, support for fields and methods, and can be extended to form new classes. Thus the proxy has a dual nature; on the one hand it needs to act as an object of the same class as the remote object (transparent proxy), and on the other it is a managed object itself.

A proxy object can be used without regard to any remoting subdivisions within an AppDomain. Applications need not distinguish between proxy references and object references. However, service providers dealing with issues such as activation, lifetime management, and transactions need to make such distinctions.

Example
The following example demonstrates the use of the RemotingServices.IsTransparentProxy method to determine whether an object is a proxy or a real object. For the complete example code, see the example for the AsyncResult class.
        // Creates an instance of a context-bound type SampleSynchronized.
        SampleSyncronized sampSyncObj = new SampleSyncronized();

        // Checks whether the object is a proxy, since it is context-bound.
        if (RemotingServices.IsTransparentProxy(sampSyncObj))
            Console.WriteLine("sampSyncObj is a proxy.");
        else
            Console.WriteLine("sampSyncObj is NOT a proxy.");

    
See also:
RealProxy | ObjRef

Return to top


Method: LogRemotingStage(
   int stage
)
Summary
Public reserved method, for internal use only.
C# Syntax:
[Conditional("")]
public static void LogRemotingStage(
   int stage
);
Parameters:

stage

Return to top


Overloaded Method: Marshal(
   MarshalByRefObject Obj
)
Summary
Takes a MarshalByRefObject, registers it with the remoting infrastructure, and converts it into an instance of the ObjRef class.
C# Syntax:
public static ObjRef Marshal( Marshal(
   MarshalByRefObject Obj
);
Parameters:

Obj

The object to convert.

Return Value:
An instance of the ObjRef class representing the object specified in the Obj parameter.
Exceptions
Exception Type Condition
RemotingException The Obj parameter is an object proxy.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remoting subdivision where the object is located.

During marshaling, the context from the current thread is used, not the context that was active when the object was created. If a URI was not explicitly set by the RemotingServices.SetObjectUriForMarshal method, it is automatically generated by the remoting identity infrastructure.

You cannot associate a URI with a proxy for one of two reasons: either the URI was generated at the server side for the object it represents, or the object is well known, in which case the URI is known. For this reason, if the Obj parameter is a proxy, an exception will be thrown. For custom proxies this restriction is relaxed because the transparent proxy is treated as the server object.

.NET Framework Security:
SecurityPermission for configuration of the remoting infrastructure. Associated enumeration: SecurityPermissionFlag.RemotingConfiguration.
See also:
Uri | MSDN: applicationdomains | RealProxy | ObjRef

Return to top


Overloaded Method: Marshal(
   MarshalByRefObject Obj,
   string URI
)
Summary
Converts the given MarshalByRefObject into an instance of the ObjRef class with the specified URI.
C# Syntax:
public static ObjRef Marshal( Marshal(
   MarshalByRefObject Obj,
   string URI
);
Parameters:

Obj

The object to convert.

URI

The specified URI with which to initialize the new ObjRef. Can be null.

Return Value:
An instance of the ObjRef class representing the object specified in the Obj parameter.
Exceptions
Exception Type Condition
RemotingException Obj is an object proxy, and the URI parameter is not null.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remoting subdivision where the object is located.

During marshaling, the context from the current thread is used, not the context that was active when the object was created.

You cannot associate a URI with a proxy for one of two reasons: either the URI was generated at the server side for the object it represents, or the object is well known, in which case the URI is known. For this reason, if the Obj parameter is a proxy, an exception will be thrown. For custom proxies this restriction is relaxed because the transparent proxy is treated as the server object.

Example
The following example demonstrates how to use the current RemotingServices.Marshal method to marshal a specified object.
      TcpChannel channel = new TcpChannel(9000);
      ChannelServices.RegisterChannel(channel);

      SampleWellKnown objectWellKnown = new SampleWellKnown();
      
      // After the channel is registered, the object needs to be registered
      // with the remoting infrastructure.  So, Marshal is called.
      ObjRef objrefWellKnown = RemotingServices.Marshal(objectWellKnown, "objectWellKnownUri");
      Console.WriteLine("An instance of SampleWellKnown type is published at {0}.", objrefWellKnown.URI);

      Console.WriteLine("Press enter to unregister SampleWellKnown, so that it is no longer available on this channel.");
      Console.ReadLine();
      RemotingServices.Disconnect(objectWellKnown);

      Console.WriteLine("Press enter to end the server process.");
      Console.ReadLine();

    
.NET Framework Security:
SecurityPermission for configuration of the remoting infrastructure. Associated enumeration: SecurityPermissionFlag.RemotingConfiguration.
See also:
Uri | MSDN: applicationdomains | RealProxy | ObjRef

Return to top


Overloaded Method: Marshal(
   MarshalByRefObject Obj,
   string ObjURI,
   Type RequestedType
)
Summary
Takes a MarshalByRefObject and converts it into an instance of the ObjRef class with the specified URI, and the provided Type.
C# Syntax:
public static ObjRef Marshal( Marshal(
   MarshalByRefObject Obj,
   string ObjURI,
   Type RequestedType
);
Parameters:

Obj

The object to convert into an ObjRef.

ObjURI

The URI the object specified in the Obj parameter is marshaled with. Can be null.

RequestedType

The TypeObj is marshaled as. Can be null.

Return Value:
An instance of the ObjRef class representing the object specified in the Obj parameter.
Exceptions
Exception Type Condition
RemotingException Obj is a proxy of a remote object, and the ObjUri parameter is not null.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remoting subdivision where the object is located.

The specified Type is used by the remoting infrastructure to limit the scope of the exposed type hierarchy. For example, if object A derives from object B, which derives from object C, and RemotingServices.Marshal is called, then the client can cast the proxy between C and B but not to A.

During marshaling, the context from the current thread is used, not the context that was active when the object was created.

You cannot associate a URI with a proxy for one of two reasons: either the URI was generated at the server side for the object it represents, or the object is well known, in which case the URI is known. For this reason, if the Obj parameter is a proxy, an exception will be thrown. For custom proxies this restriction is relaxed because the transparent proxy is treated as the server object.

.NET Framework Security:
SecurityPermission for configuration of the remoting infrastructure. Associated enumeration: SecurityPermissionFlag.RemotingConfiguration.
See also:
Uri | MSDN: applicationdomains | RealProxy | ObjRef

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: SetObjectUriForMarshal(
   MarshalByRefObject obj,
   string uri
)
Summary
Sets the URI for the subsequent call to the RemotingServices.Marshal method.
C# Syntax:
public static void SetObjectUriForMarshal(
   MarshalByRefObject obj,
   string uri
);
Parameters:

obj

The object to set a URI for.

uri

The URI to assign to the specified object.

Exceptions
Exception Type Condition
RemotingException obj is not a local object, has already been marshaled, or the current method has already been called on.
Remarks
The URI set by the current method is used when marshaling the given object.

Note After marshaling, the URI of the specified object is set to the string in the uri parameter appended onto the Guid of the current AppDomain.

Note If the current application is listening on an HTTP port, then both the string specified in the uri parameter and the uri string appended onto the Guid of the current AppDomain route to the specified object. For example, if the application is listening on HTTP port 9000, then both http://localhost:9000/objectUri, and http://localhost:9000/<appdomainguid>/objectUri route to the object specified in the obj parameter.
Example
The following example demonstrates how to set the URI that will be used by the RemotingServices.Marshal method when marshaling the specified object.
using System;
using System.Runtime.Remoting;

public class SetObjectUriForMarshalTest  {

    class TestClass : MarshalByRefObject {
    }

    public static void Main()  {

        TestClass obj = new TestClass();    

        RemotingServices.SetObjectUriForMarshal(obj, "testUri");
        RemotingServices.Marshal(obj);

        Console.WriteLine(RemotingServices.GetObjectUri(obj));
    }
}

    
.NET Framework Security:
SecurityPermission for configuration of the remoting infrastructure. Associated enumeration: SecurityPermissionFlag.RemotingConfiguration.
See also:
Uri | Guid

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: Unmarshal(
   ObjRef objectRef
)
Summary
Takes an ObjRef and creates a proxy object out of it.
C# Syntax:
public static object Unmarshal(
   ObjRef objectRef
);
Parameters:

objectRef

The ObjRef that represents the remote object for which the proxy is being created.

Return Value:
A proxy to the object that the given ObjRef represents.
Exceptions
Exception Type Condition
ArgumentException The ObjRef instance specified in the objectRef parameter is not well formed.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. During unmarshaling, the ObjRef is parsed to extract the method information of the remote object and both the transparent proxy and RealProxy objects are created. The content of the parsed ObjRef is added to the transparent proxy before the transparent proxy is registered with the common language runtime.

ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remoting subdivision where the object is located.

Example
The following example demonstrates how to unmarshal an object.
        ChannelServices.RegisterChannel(new HttpChannel());

        SampleService objectSample = (SampleService)Activator.GetObject(typeof(SampleService), 
            "http://localhost:9000/MySampleService/SampleService.soap");

        // The GetManuallyMarshaledObject() method uses RemotingServices.Marshal()
        // to create an ObjRef object for a SampleTwo object.
        ObjRef objRefSampleTwo = objectSample.GetManuallyMarshaledObject();

        SampleTwo objectSampleTwo = (SampleTwo)RemotingServices.Unmarshal(objRefSampleTwo);

        objectSampleTwo.PrintMessage("ObjRef successfuly unmarshaled."); 

    
See also:
RealProxy | ObjRef

Return to top


Overloaded Method: Unmarshal(
   ObjRef objectRef,
   bool fRefine
)
Summary
Takes an ObjRef and creates a proxy object out of it, refining it to the type on the server.
C# Syntax:
public static object Unmarshal(
   ObjRef objectRef,
   bool fRefine
);
Parameters:

objectRef

The ObjRef that represents the remote object for which the proxy is being created.

fRefine

true to refine the proxy to the type on the server; otherwise, false.

Return Value:
A proxy to the object that the given ObjRef represents.
Exceptions
Exception Type Condition
ArgumentException The ObjRef instance specified in the objectRef parameter is not well formed.
Remarks
An ObjRef is a serializable representation of an object used to transfer an object reference across an AppDomain boundary. Creating an ObjRef for an object is known as marshaling. The ObjRef can be transferred through a channel into another AppDomain (possibly on another process or computer). Once in the other AppDomain, the ObjRef must be parsed to create a proxy for the object, generally connected to the real object. This operation is known as unmarshaling. During unmarshaling, the ObjRef is parsed to extract the method information of the remote object and both the transparent proxy and RealProxy objects are created. The content of the parsed ObjRef is added to the transparent proxy before the transparent proxy is registered with the common language runtime.

ObjRef s contain information that describes the Type and class of the object being marshaled, a URI that uniquely identifies the specific object instance, and communication related information on how to reach the remoting subdivision where the object is located.

When first created, the proxy is of type MarshalByRefObject. As you cast it into different types, the remoting infrastructure keeps track of the most used type to avoid loading the type unnecessarily.

See also:
RealProxy | ObjRef

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.