2 // System.Runtime.Remoting.RemotingServices.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Lluis Sanchez Gual (lluis@ideary.com)
9 // (C) 2001 Ximian, Inc. http://www.ximian.com
13 using System.Reflection;
14 using System.Threading;
15 using System.Collections;
16 using System.Runtime.Remoting.Messaging;
17 using System.Runtime.Remoting.Proxies;
18 using System.Runtime.Remoting.Channels;
19 using System.Runtime.Remoting.Contexts;
20 using System.Runtime.Remoting.Activation;
21 using System.Runtime.Remoting.Lifetime;
22 using System.Runtime.CompilerServices;
23 using System.Runtime.Serialization;
26 namespace System.Runtime.Remoting
28 public sealed class RemotingServices
30 // Holds the identities of the objects, using uri as index
31 static Hashtable uri_hash = new Hashtable ();
33 internal static string app_id;
34 static int next_id = 1;
36 static RemotingServices ()
38 RegisterInternalChannels ();
39 app_id = "/" + Guid.NewGuid().ToString().Replace('-', '_') + "/";
40 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
43 private RemotingServices () {}
45 [MethodImplAttribute(MethodImplOptions.InternalCall)]
46 internal extern static object InternalExecute (MonoMethod method, Object obj,
47 Object[] parameters, out object [] out_args);
49 [MethodImplAttribute(MethodImplOptions.InternalCall)]
50 public extern static bool IsTransparentProxy (object proxy);
52 internal static IMethodReturnMessage InternalExecuteMessage (
53 MarshalByRefObject target, IMethodCallMessage reqMsg)
57 MonoMethod method = (MonoMethod)reqMsg.MethodBase;
61 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
62 result = new ReturnMessage (rval, out_args, out_args.Length,
63 reqMsg.LogicalCallContext, reqMsg);
65 } catch (Exception e) {
66 result = new ReturnMessage (e, reqMsg);
72 public static IMethodReturnMessage ExecuteMessage (
73 MarshalByRefObject target, IMethodCallMessage reqMsg)
75 if (IsTransparentProxy(target))
77 // Message must go through all chain of sinks
78 RealProxy rp = GetRealProxy (target);
79 return (IMethodReturnMessage) rp.Invoke (reqMsg);
82 return InternalExecuteMessage (target, reqMsg);
85 public static object Connect (Type classToProxy, string url)
87 ObjRef objRef = new ObjRef (classToProxy, url, null);
88 return GetRemoteObject(objRef);
91 public static object Connect (Type classToProxy, string url, object data)
93 ObjRef objRef = new ObjRef (classToProxy, url, data);
94 return GetRemoteObject(objRef);
97 public static bool Disconnect (MarshalByRefObject obj)
99 if (obj == null) throw new ArgumentNullException ("obj");
100 if (IsTransparentProxy (obj)) throw new ArgumentException ("The obj parameter is a proxy");
102 ServerIdentity identity = obj.ObjectIdentity;
103 if (identity == null || !identity.IsConnected)
107 LifetimeServices.StopTrackingLifetime (identity);
108 DisposeIdentity (identity);
113 public static Type GetServerTypeForUri (string uri)
115 Identity ident = GetIdentityForUri (uri);
116 if (ident == null) return null;
117 return ident.ObjectType;
120 public static string GetObjectUri (MarshalByRefObject obj)
122 Identity ident = GetObjectIdentity(obj);
123 if (ident != null) return ident.ObjectUri;
127 public static object Unmarshal (ObjRef objref)
129 return Unmarshal(objref, false);
132 public static object Unmarshal (ObjRef objref, bool fRefine)
134 // FIXME: use type name when fRefine==true
136 if (objref.IsReferenceToWellKnow)
137 return GetRemoteObject(objref);
140 if (objref.ServerType.IsContextful)
142 // Look for a ProxyAttribute
143 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (objref.ServerType, typeof(ProxyAttribute),true);
145 return att.CreateProxy (objref, objref.ServerType, null, null).GetTransparentProxy();
147 return GetProxyForRemoteObject (objref, fRefine);
151 public static ObjRef Marshal (MarshalByRefObject obj)
153 return Marshal (obj, null, null);
156 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
158 return Marshal (obj, uri, null);
161 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
163 if (IsTransparentProxy (obj))
165 RealProxy proxy = RemotingServices.GetRealProxy(obj);
166 Identity identity = proxy.ObjectIdentity;
168 if (identity != null)
170 if (identity.ObjectType.IsContextful && !identity.IsConnected)
172 // Unregistered local contextbound object. Register now.
173 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
174 if (uri == null) uri = NewUri();
175 cboundIdentity.ObjectUri = uri;
176 RegisterServerIdentity (cboundIdentity);
177 cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
178 return cboundIdentity.CreateObjRef(requested_type);
180 else if (uri != null)
181 throw new RemotingException ("It is not possible marshal a proxy of a remote object");
183 return proxy.ObjectIdentity.CreateObjRef(requested_type);
187 if (requested_type == null) requested_type = obj.GetType();
192 CreateClientActivatedServerIdentity (obj, requested_type, uri);
196 ClientActivatedIdentity identity = uri_hash [uri] as ClientActivatedIdentity;
197 if (identity == null || obj != identity.GetServerObject())
198 CreateClientActivatedServerIdentity (obj, requested_type, uri);
201 return obj.CreateObjRef(requested_type);
204 static string NewUri ()
206 return app_id + Environment.TickCount + "_" + next_id++;
209 public static RealProxy GetRealProxy (object proxy)
211 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy");
212 return (RealProxy)((TransparentProxy)proxy)._rp;
215 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
217 Type type = Type.GetType (msg.TypeName);
219 throw new RemotingException ("Type '" + msg.TypeName + "' not found!");
221 BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
222 if (msg.MethodSignature == null)
223 return type.GetMethod (msg.MethodName, bflags);
225 return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
228 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
230 if (obj == null) throw new ArgumentNullException ("obj");
232 ObjRef oref = Marshal ((MarshalByRefObject)obj);
233 oref.GetObjectData (info, context);
236 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
238 Identity ident = GetObjectIdentity(obj);
239 if (ident == null) return null;
240 else return ident.CreateObjRef(null);
244 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
246 throw new NotImplementedException ();
249 public static bool IsMethodOverloaded(IMethodMessage msg)
251 Type type = msg.MethodBase.DeclaringType;
252 MemberInfo[] members = type.GetMember (msg.MethodName, MemberTypes.Method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
253 return members.Length > 1;
256 public static bool IsObjectOutOfAppDomain(object tp)
258 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
259 if (ident != null) return !ident.IsFromThisAppDomain;
263 public static bool IsObjectOutOfContext(object tp)
265 ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
266 if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
270 public static bool IsOneWay(MethodBase method)
272 object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
273 return atts.Length > 0;
276 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
278 if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
282 #region Internal Methods
284 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
286 if (entry.ContextAttributes != null || activationAttributes != null)
288 ArrayList props = new ArrayList ();
289 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
290 if (activationAttributes != null) props.AddRange (activationAttributes);
291 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
294 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
297 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
299 string activationUrl = url + "/RemoteActivationService.rem";
302 IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
304 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
305 return proxy.GetTransparentProxy();
308 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
310 return Connect (entry.ObjectType, entry.ObjectUrl, null);
313 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
315 if (type.IsContextful)
317 // Look for a ProxyAttribute
318 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
320 return att.CreateInstance (type);
322 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
323 return proxy.GetTransparentProxy();
326 internal static Identity GetIdentityForUri (string uri)
330 return (Identity)uri_hash [uri];
334 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
336 if (IsTransparentProxy(obj))
337 return GetRealProxy (obj).ObjectIdentity;
339 return obj.ObjectIdentity;
342 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, RealProxy proxyToAttach)
344 // This method looks for an identity for the given url.
345 // If an identity is not found, it creates the identity and
346 // assigns it a proxy to the remote object.
348 // Creates the client sink chain for the given url or channelData.
349 // It will also get the object uri from the url.
351 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
352 string url = (channelData == null) ? objRef.URI : null;
355 IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
357 if (objectUri == null) objectUri = objRef.URI;
361 ClientIdentity identity = uri_hash [objRef.URI] as ClientIdentity;
362 if (identity != null)
363 return identity; // Object already registered
365 // Creates an identity and a proxy for the remote object
367 identity = new ClientIdentity (objectUri, objRef);
368 identity.ChannelSink = sink;
370 if (proxyToAttach == null) proxyToAttach = new RemotingProxy (objRef.ServerType, identity);
371 identity.ClientProxy = (MarshalByRefObject) proxyToAttach.GetTransparentProxy();
373 // Registers the identity
374 uri_hash [objRef.URI] = identity;
379 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
381 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
386 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
387 throw new RemotingException (msg);
391 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
392 throw new RemotingException (msg);
398 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
400 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
401 identity.ChannelSink = ChannelServices.CrossContextChannel;
405 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
407 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
408 identity.AttachServerObject (realObject, Context.DefaultContext);
409 RegisterServerIdentity (identity);
410 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
414 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
416 ServerIdentity identity;
418 if (mode == WellKnownObjectMode.SingleCall)
419 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
421 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
423 RegisterServerIdentity (identity);
427 private static void RegisterServerIdentity(ServerIdentity identity)
431 if (uri_hash.ContainsKey (identity.ObjectUri))
432 throw new RemotingException ("Uri already in use: " + identity.ObjectUri);
434 uri_hash[identity.ObjectUri] = identity;
438 internal static object GetProxyForRemoteObject (ObjRef objref, bool fRefine)
440 ClientActivatedIdentity identity = uri_hash [objref.URI] as ClientActivatedIdentity;
441 if (identity != null) return identity.GetServerObject ();
442 else return GetRemoteObject (objref);
445 internal static object GetRemoteObject(ObjRef objRef)
447 ClientIdentity id = GetOrCreateClientIdentity (objRef, null);
448 return id.ClientProxy;
451 internal static object GetDomainProxy(AppDomain domain)
455 Context currentContext = Thread.CurrentContext;
456 AppDomain currentDomain = AppDomain.InternalSetDomain (domain);
459 data = domain.GetMarshalledDomainObjRef ();
463 AppDomain.InternalSetDomain (currentDomain);
464 AppDomain.InternalSetContext (currentContext);
467 MemoryStream stream = new MemoryStream (data);
468 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
469 return (AppDomain) RemotingServices.Unmarshal(appref);
472 private static void RegisterInternalChannels()
474 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
477 internal static void DisposeIdentity (ServerIdentity ident)
479 uri_hash.Remove (ident.ObjectUri);
482 internal static Identity GetMessageTargetIdentity (IMessage msg)
484 // Returns the identity where the message is sent
486 if (msg is IInternalMessage)
487 return ((IInternalMessage)msg).TargetIdentity;
491 return uri_hash [((IMethodMessage)msg).Uri] as ServerIdentity;
495 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
497 if (msg is IInternalMessage)
498 ((IInternalMessage)msg).TargetIdentity = ident;