2 // System.Runtime.Remoting.Messaging.CADMessages.cs
7 // (C) Patrik Torstensson
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
36 using System.Reflection;
37 using System.Runtime.Serialization;
38 using System.Runtime.Remoting;
39 using System.Runtime.Remoting.Channels;
40 using System.Runtime.Remoting.Messaging;
41 using System.Runtime.Remoting.Proxies;
43 namespace System.Runtime.Remoting.Messaging {
45 internal class CADArgHolder {
48 public CADArgHolder (int i) {
53 internal class CADObjRef {
55 public int SourceDomain;
57 public CADObjRef (ObjRef o, int sourceDomain) {
59 SourceDomain = sourceDomain;
62 public string TypeName {
63 get { return objref.TypeInfo.TypeName; }
67 get { return objref.URI; }
71 internal class CADMessageBase {
73 protected object [] _args;
74 protected byte [] _serializedArgs = null;
75 protected int _propertyCount = 0;
76 protected CADArgHolder _callContext;
77 internal RuntimeMethodHandle MethodHandle;
78 internal string FullTypeName;
79 internal MethodBase _method;
81 public CADMessageBase (IMethodMessage msg) {
82 MethodHandle = msg.MethodBase.MethodHandle;
83 FullTypeName = msg.MethodBase.DeclaringType.AssemblyQualifiedName;
86 internal MethodBase method {
88 if (_method == null) {
89 _method = GetMethod();
95 internal MethodBase GetMethod ()
97 Type tt = Type.GetType (FullTypeName, true);
98 if (tt.IsGenericType || tt.IsGenericTypeDefinition) {
99 _method = MethodBase.GetMethodFromHandleNoGenericCheck (MethodHandle);
101 _method = MethodBase.GetMethodFromHandle (MethodHandle);
104 if (tt != _method.DeclaringType) {
105 // The target domain has loaded the type from a different assembly.
106 // We need to locate the correct type and get the method from it
107 Type [] signature = GetSignature (_method, true);
108 if (_method.IsGenericMethod) {
109 MethodBase [] methods = tt.GetMethods (BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
110 Type [] base_args = _method.GetGenericArguments ();
111 foreach (MethodBase method in methods) {
112 if (!method.IsGenericMethod || method.Name != _method.Name)
114 Type [] method_args = method.GetGenericArguments ();
115 if (base_args.Length != method_args.Length)
118 MethodInfo method_instance = ((MethodInfo) method).MakeGenericMethod (base_args);
119 Type [] base_sig = GetSignature (method_instance, false);
120 if (base_sig.Length != signature.Length) {
124 for (int i = base_sig.Length - 1; i >= 0; i--) {
125 if (base_sig [i] != signature [i]) {
132 return method_instance;
137 MethodBase mb = tt.GetMethod (_method.Name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, signature, null);
139 throw new RemotingException ("Method '" + _method.Name + "' not found in type '" + tt + "'");
145 static protected Type [] GetSignature (MethodBase methodBase, bool load)
147 ParameterInfo[] pars = methodBase.GetParameters ();
148 Type[] signature = new Type [pars.Length];
149 for (int n=0; n<pars.Length; n++) {
150 // The parameter types may also be loaded from a different assembly, so we need
151 // to load them again
153 signature [n] = Type.GetType (pars [n].ParameterType.AssemblyQualifiedName, true);
155 signature [n] = pars [n].ParameterType;
159 // Helper to marshal properties
160 internal static int MarshalProperties (IDictionary dict, ref ArrayList args) {
161 IDictionary serDict = dict;
164 MethodDictionary msgDict = dict as MethodDictionary;
165 if (null != msgDict) {
166 if (msgDict.HasInternalProperties) {
167 serDict = msgDict.InternalProperties;
168 if (null != serDict) {
169 foreach (DictionaryEntry e in serDict) {
171 args = new ArrayList();
179 foreach (DictionaryEntry e in serDict) {
181 args = new ArrayList();
191 internal static void UnmarshalProperties (IDictionary dict, int count, ArrayList args) {
192 for (int i = 0; i < count; i++) {
193 DictionaryEntry e = (DictionaryEntry) args [i];
194 dict [e.Key] = e.Value;
198 // We can ignore marshalling for string and primitive types
199 private static bool IsPossibleToIgnoreMarshal (object obj) {
201 Type objType = obj.GetType();
202 if (objType.IsPrimitive || objType == typeof(void))
205 if (objType.IsArray && objType.GetElementType().IsPrimitive && ((Array)obj).Rank == 1)
208 if (obj is string || obj is DateTime || obj is TimeSpan)
214 // Checks an argument if it's possible to pass without marshalling and
215 // if not it will be added to arguments to be serialized
216 protected object MarshalArgument (object arg, ref ArrayList args) {
220 if (IsPossibleToIgnoreMarshal (arg))
223 MarshalByRefObject mbr = arg as MarshalByRefObject;
226 if (RemotingServices.IsTransparentProxy(mbr)) {
227 // We don't deal with this case yet
230 ObjRef objRef = RemotingServices.Marshal(mbr);
231 return new CADObjRef(objRef, System.Threading.Thread.GetDomainID());
236 args = new ArrayList();
240 // return position that the arg exists in the serialized list
241 return new CADArgHolder(args.Count - 1);
244 protected object UnmarshalArgument (object arg, ArrayList args) {
245 if (arg == null) return null;
247 // Check if argument is an holder (then we know that it's a serialized argument)
248 CADArgHolder holder = arg as CADArgHolder;
249 if (null != holder) {
250 return args [holder.index];
253 CADObjRef objref = arg as CADObjRef;
254 if (null != objref) {
255 string typeName = string.Copy (objref.TypeName);
256 string uri = string.Copy (objref.URI);
257 int domid = objref.SourceDomain;
259 ChannelInfo cinfo = new ChannelInfo (new CrossAppDomainData (domid));
260 ObjRef localRef = new ObjRef (typeName, uri, cinfo);
261 return RemotingServices.Unmarshal (localRef);
266 Array argb = (Array)arg;
269 // We can't use Array.CreateInstance (arg.GetType().GetElementType()) because
270 // GetElementType() returns a type from the source domain.
272 switch (Type.GetTypeCode (arg.GetType().GetElementType()))
274 case TypeCode.Boolean: argn = new bool [argb.Length]; break;
275 case TypeCode.Byte: argn = new Byte [argb.Length]; break;
276 case TypeCode.Char: argn = new Char [argb.Length]; break;
277 case TypeCode.Decimal: argn = new Decimal [argb.Length]; break;
278 case TypeCode.Double: argn = new Double [argb.Length]; break;
279 case TypeCode.Int16: argn = new Int16 [argb.Length]; break;
280 case TypeCode.Int32: argn = new Int32 [argb.Length]; break;
281 case TypeCode.Int64: argn = new Int64 [argb.Length]; break;
282 case TypeCode.SByte: argn = new SByte [argb.Length]; break;
283 case TypeCode.Single: argn = new Single [argb.Length]; break;
284 case TypeCode.UInt16: argn = new UInt16 [argb.Length]; break;
285 case TypeCode.UInt32: argn = new UInt32 [argb.Length]; break;
286 case TypeCode.UInt64: argn = new UInt64 [argb.Length]; break;
287 default: throw new NotSupportedException ();
290 argb.CopyTo (argn, 0);
294 switch (Type.GetTypeCode (arg.GetType()))
296 case TypeCode.Boolean: return (bool)arg;
297 case TypeCode.Byte: return (byte)arg;
298 case TypeCode.Char: return (char)arg;
299 case TypeCode.Decimal: return (decimal)arg;
300 case TypeCode.Double: return (double)arg;
301 case TypeCode.Int16: return (Int16)arg;
302 case TypeCode.Int32: return (Int32)arg;
303 case TypeCode.Int64: return (Int64)arg;
304 case TypeCode.SByte: return (SByte)arg;
305 case TypeCode.Single: return (Single)arg;
306 case TypeCode.UInt16: return (UInt16)arg;
307 case TypeCode.UInt32: return (UInt32)arg;
308 case TypeCode.UInt64: return (UInt64)arg;
309 case TypeCode.String: return string.Copy ((string) arg);
310 case TypeCode.DateTime: return new DateTime (((DateTime)arg).Ticks);
312 if (arg is TimeSpan) return new TimeSpan (((TimeSpan)arg).Ticks);
313 if (arg is IntPtr) return (IntPtr) arg;
317 throw new NotSupportedException ("Parameter of type " + arg.GetType () + " cannot be unmarshalled");
320 internal object [] MarshalArguments (object [] arguments, ref ArrayList args) {
321 object [] marshalledArgs = new object [arguments.Length];
323 int total = arguments.Length;
324 for (int i = 0; i < total; i++)
325 marshalledArgs [i] = MarshalArgument (arguments [i], ref args);
327 return marshalledArgs;
330 internal object [] UnmarshalArguments (object [] arguments, ArrayList args) {
331 object [] unmarshalledArgs = new object [arguments.Length];
333 int total = arguments.Length;
334 for (int i = 0; i < total; i++)
335 unmarshalledArgs [i] = UnmarshalArgument (arguments [i], args);
337 return unmarshalledArgs;
340 protected void SaveLogicalCallContext (IMethodMessage msg, ref ArrayList serializeList)
342 if (msg.LogicalCallContext != null && msg.LogicalCallContext.HasInfo)
344 if (serializeList == null)
345 serializeList = new ArrayList();
347 _callContext = new CADArgHolder (serializeList.Count);
348 serializeList.Add (msg.LogicalCallContext);
352 internal LogicalCallContext GetLogicalCallContext (ArrayList args)
354 if (null == _callContext)
357 return (LogicalCallContext) args [_callContext.index];
361 // Used when passing a IMethodCallMessage between appdomains
362 internal class CADMethodCallMessage : CADMessageBase {
365 internal string Uri {
371 static internal CADMethodCallMessage Create (IMessage callMsg) {
372 IMethodCallMessage msg = callMsg as IMethodCallMessage;
376 return new CADMethodCallMessage (msg);
379 internal CADMethodCallMessage (IMethodCallMessage callMsg): base (callMsg) {
382 ArrayList serializeList = null;
384 _propertyCount = MarshalProperties (callMsg.Properties, ref serializeList);
386 _args = MarshalArguments ( callMsg.Args, ref serializeList);
389 SaveLogicalCallContext (callMsg, ref serializeList);
391 // Serialize message data if needed
393 if (null != serializeList) {
394 MemoryStream stm = CADSerializer.SerializeObject (serializeList.ToArray());
395 _serializedArgs = stm.GetBuffer();
399 internal ArrayList GetArguments () {
400 ArrayList ret = null;
402 if (null != _serializedArgs) {
403 object[] oret = (object[]) CADSerializer.DeserializeObject (new MemoryStream (_serializedArgs));
404 ret = new ArrayList (oret);
405 _serializedArgs = null;
411 internal object [] GetArgs (ArrayList args) {
412 return UnmarshalArguments (_args, args);
415 internal int PropertiesCount {
417 return _propertyCount;
423 // Used when passing a IMethodReturnMessage between appdomains
424 internal class CADMethodReturnMessage : CADMessageBase {
426 CADArgHolder _exception = null;
428 static internal CADMethodReturnMessage Create (IMessage callMsg) {
429 IMethodReturnMessage msg = callMsg as IMethodReturnMessage;
433 return new CADMethodReturnMessage (msg);
436 internal CADMethodReturnMessage(IMethodReturnMessage retMsg): base (retMsg) {
437 ArrayList serializeList = null;
439 _propertyCount = MarshalProperties (retMsg.Properties, ref serializeList);
441 _returnValue = MarshalArgument ( retMsg.ReturnValue, ref serializeList);
442 _args = MarshalArguments ( retMsg.Args, ref serializeList);
444 if (null != retMsg.Exception) {
445 if (null == serializeList)
446 serializeList = new ArrayList();
448 _exception = new CADArgHolder (serializeList.Count);
449 serializeList.Add(retMsg.Exception);
453 SaveLogicalCallContext (retMsg, ref serializeList);
455 if (null != serializeList) {
456 MemoryStream stm = CADSerializer.SerializeObject (serializeList.ToArray());
457 _serializedArgs = stm.GetBuffer();
461 internal ArrayList GetArguments () {
462 ArrayList ret = null;
464 if (null != _serializedArgs) {
465 object[] oret = (object[]) CADSerializer.DeserializeObject (new MemoryStream (_serializedArgs));
466 ret = new ArrayList (oret);
467 _serializedArgs = null;
473 internal object [] GetArgs (ArrayList args) {
474 return UnmarshalArguments (_args, args);
477 internal object GetReturnValue (ArrayList args) {
478 return UnmarshalArgument (_returnValue, args);
481 internal Exception GetException(ArrayList args) {
482 if (null == _exception)
485 return (Exception) args [_exception.index];
488 internal int PropertiesCount {
490 return _propertyCount;