Updates referencesource to .NET 4.7
[mono.git] / mcs / class / referencesource / mscorlib / system / runtime / remoting / message.cs
1 // ==++==
2 // 
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 // 
5 // ==--==
6 /*============================================================
7 **
8 ** File:    Message.cs
9 **
10 **
11 ** Purpose: Defines the message object created by the transparent
12 **          proxy and used by the message sinks
13 **
14 **
15 ===========================================================*/
16 namespace System.Runtime.Remoting.Messaging {
17     using System;
18     using System.Collections;
19     using System.Threading;
20     using System.Runtime.InteropServices;
21     using System.Runtime.Remoting;    
22     using System.Runtime.Remoting.Activation;
23     using System.Runtime.Remoting.Contexts;
24     using System.Runtime.Remoting.Channels;
25     using System.Runtime.Remoting.Metadata;
26     using System.Runtime.Remoting.Metadata.W3cXsd2001;
27     using System.Runtime.Remoting.Proxies;
28     using System.Runtime.Serialization;
29     using System.Runtime.Serialization.Formatters;  
30     using System.Runtime.Serialization.Formatters.Binary;  
31     using System.Runtime.Versioning;
32     using System.Reflection;
33     using System.Text;
34     using System.Runtime.CompilerServices;
35     using System.Security.Permissions;
36     using System.Globalization;
37     using System.Diagnostics.Contracts;
38     using System.Security;
39
40     //+=======================================================================
41     //
42     // Synopsis:   Message is used to represent call and is created by the
43     //             Transparent proxy
44     //
45     //-=======================================================================
46     [Serializable]
47     internal class Message : IMethodCallMessage, IInternalMessage, ISerializable
48     {
49
50         // *** NOTE ***
51         // Keep these in sync with the flags in Message.h
52         // flags
53         internal const int Sync = 0;        // Synchronous call
54         internal const int BeginAsync = 1;  // Async Begin call
55         internal const int EndAsync   = 2;  // Async End call
56         internal const int Ctor       = 4;  // The call is a .Ctor
57         internal const int OneWay     = 8;  // One way call
58         internal const int CallMask   = 15; // Mask for call type bits
59         
60         internal const int FixedArgs  = 16;  // Fixed number of arguments call       
61         internal const int VarArgs    = 32; // Variable number of arguments call        
62
63     //
64         // Changing the type or position of these fields requires making changes 
65         //  to the corresponding unmanaged class and to mscorlib.h
66         //
67
68         // Private data members
69         private String _MethodName;                 // Method name
70         private Type[] _MethodSignature;            // Array of parameter types
71         private MethodBase _MethodBase;             // Reflection method object
72         private Object  _properties;                // hash table for properities
73         private String    _URI;                     // target object URI
74         private String _typeName;
75         private Exception _Fault;                   // null if no fault
76
77         private Identity _ID;            // identity cached during Invoke
78         private ServerIdentity _srvID;   // server Identity cached during Invoke
79         private ArgMapper _argMapper;
80         [System.Security.SecurityCritical] // auto-generated
81         private LogicalCallContext _callContext;
82
83         private IntPtr _frame;               // ptr to the call frame
84         private IntPtr _methodDesc;          // ptr to the internal method descriptor
85         private IntPtr _metaSigHolder;         // Pointer to the MetaSig structure
86         private IntPtr _delegateMD;          // ptr to the internal method descriptor for the delegate
87         private IntPtr _governingType;       // ptr to the internal type handle for the type calling the method
88
89         private int _flags;               // internal flags
90         private bool _initDone;           // called the native init routine
91
92
93         internal static String CallContextKey = "__CallContext";
94         internal static String UriKey           = "__Uri";
95         
96
97         public virtual Exception GetFault()       {return _Fault;}
98         public virtual void      SetFault(Exception e) {_Fault = e;}
99
100         internal virtual void SetOneWay()   { _flags |= Message.OneWay;}
101         public virtual int       GetCallType()
102         {
103             // We should call init only if neccessary
104             InitIfNecessary();
105             return _flags;
106         }
107
108         internal IntPtr GetFramePtr() { return _frame;}
109
110
111
112         [System.Security.SecurityCritical]  // auto-generated
113         [ResourceExposure(ResourceScope.None)]
114         [MethodImplAttribute(MethodImplOptions.InternalCall)]
115         public extern void GetAsyncBeginInfo(out AsyncCallback acbd,
116                                              out Object        state);
117
118         [System.Security.SecurityCritical]  // auto-generated
119         [ResourceExposure(ResourceScope.None)]
120         [MethodImplAttribute(MethodImplOptions.InternalCall)]
121         public extern Object         GetThisPtr();
122         [System.Security.SecurityCritical]  // auto-generated
123         [ResourceExposure(ResourceScope.None)]
124         [MethodImplAttribute(MethodImplOptions.InternalCall)]
125         public extern IAsyncResult   GetAsyncResult();
126
127         public void Init()
128         {
129             // This method no longer does any meaninfull work, however it is
130             // publicly exposed so we cannot get rid of it.
131         }
132
133         [System.Security.SecurityCritical]  // auto-generated
134         [ResourceExposure(ResourceScope.None)]
135         [MethodImplAttribute(MethodImplOptions.InternalCall)]
136         public extern Object GetReturnValue();
137         //
138         // Constructor
139         // This should be internal. The message object is
140         // allocated and deallocated via a pool to enable
141         // reuse.
142         //
143         internal Message()
144         {
145         }
146
147         // NOTE: This method is called multiple times as we reuse the
148         // message object. Make sure that you reset any fields that you
149         // add to the message object to the default values. This will
150         // ensure that the reused message object starts with the correct
151         // values.
152         [System.Security.SecurityCritical]  // auto-generated
153         internal void InitFields(MessageData msgData)
154         {
155             _frame = msgData.pFrame;
156             _delegateMD = msgData.pDelegateMD;
157             _methodDesc = msgData.pMethodDesc;
158             _flags = msgData.iFlags;
159             _initDone = true;
160             _metaSigHolder = msgData.pSig;
161             _governingType = msgData.thGoverningType;
162
163             _MethodName = null;
164             _MethodSignature = null;
165             _MethodBase = null;
166             _URI = null;
167             _Fault = null;
168             _ID = null;
169             _srvID = null;
170             _callContext = null;
171
172             if (_properties != null)
173             {
174                 // A dictionary object already exists. This case occurs
175                 // when we reuse the message object. Just remove all the
176                 // entries from the dictionary object and reuse it.
177                 ((IDictionary)_properties).Clear();
178             }
179             
180         }
181
182         private void InitIfNecessary()
183         {
184             if (!_initDone)
185             {
186                 // We assume that Init is an idempotent operation
187                 Init();
188                 _initDone = true;
189             }
190         }
191
192
193         //-------------------------------------------------------------------
194         //                  IInternalMessage
195         //-------------------------------------------------------------------
196         ServerIdentity IInternalMessage.ServerIdentityObject
197         {
198             [System.Security.SecurityCritical]
199             get { return _srvID; }
200             [System.Security.SecurityCritical]
201             set {_srvID = value;}
202         }
203
204         Identity IInternalMessage.IdentityObject
205         {
206             [System.Security.SecurityCritical]
207             get { return _ID; }
208             [System.Security.SecurityCritical]
209             set { _ID = value;}
210         }
211
212         [System.Security.SecurityCritical]
213         void IInternalMessage.SetURI(String URI)
214         {
215             _URI = URI;
216         }
217
218         [System.Security.SecurityCritical]
219         void IInternalMessage.SetCallContext(LogicalCallContext callContext)
220         {
221             _callContext = callContext;
222         }
223
224         [System.Security.SecurityCritical]
225         bool IInternalMessage.HasProperties()
226         {
227             return _properties != null;
228         }
229
230         //-------------------------------------------------------------------
231         //                           IMessage
232         //-------------------------------------------------------------------
233         public IDictionary Properties
234         {
235             [System.Security.SecurityCritical]  // auto-generated
236             get
237             {
238                 if (_properties == null)
239                 {
240                     Interlocked.CompareExchange(ref _properties,
241                                                 new MCMDictionary(this, null),
242                                                 null);
243                 }
244                 return (IDictionary)_properties;
245             }
246         }
247
248         //-------------------------------------------------------------------
249         //                      IMethodCallMessage
250         //-------------------------------------------------------------------
251
252         public String     Uri                
253         { 
254             [System.Security.SecurityCritical]  // auto-generated
255             get { return _URI;}
256
257             set { _URI = value; }
258         }
259         
260         public bool       HasVarArgs         
261         { 
262             [System.Security.SecurityCritical]  // auto-generated
263             get 
264             {
265                 // When this method is called for the first time, we
266                 // obtain the answer from a native call and set the flags 
267                 if((0 == (_flags & Message.FixedArgs)) &&  
268                     (0 == (_flags & Message.VarArgs)))
269                 {
270                     if(!InternalHasVarArgs())
271                     {
272                         _flags |= Message.FixedArgs;
273                     }
274                     else
275                     {
276                         _flags |= Message.VarArgs;
277                     }
278                 }
279                 return (1 == (_flags & Message.VarArgs));
280             }
281             
282         }
283         
284         public int        ArgCount           
285         { 
286             [System.Security.SecurityCritical]  // auto-generated
287             get { return InternalGetArgCount();}
288         }
289         
290         [System.Security.SecurityCritical]  // auto-generated
291         public Object     GetArg(int argNum) 
292         { 
293             return InternalGetArg(argNum);
294         }
295         
296         [System.Security.SecurityCritical]  // auto-generated
297         public String     GetArgName(int index)
298         {
299             if (index >= ArgCount)
300             {
301                 throw new ArgumentOutOfRangeException("index");
302             }
303             Contract.EndContractBlock();
304
305             RemotingMethodCachedData methodCache = 
306                 InternalRemotingServices.GetReflectionCachedData(GetMethodBase());
307
308             ParameterInfo[] pi = methodCache.Parameters;
309
310             if (index < pi.Length)
311             {
312                 return pi[index].Name;
313             }
314             else
315             {
316                 return "VarArg" + (index - pi.Length);
317             }
318         }
319
320         public Object[]   Args
321         {
322             [System.Security.SecurityCritical]  // auto-generated
323             get
324             {
325                 return InternalGetArgs();
326             }
327         }
328
329         public int InArgCount                        
330         { 
331             [System.Security.SecurityCritical]  // auto-generated
332             get 
333             {
334                 if (_argMapper == null) _argMapper = new ArgMapper(this, false);
335                 return _argMapper.ArgCount;
336             }
337         }
338
339         [System.Security.SecurityCritical]  // auto-generated
340         public Object  GetInArg(int argNum)   
341         {   
342             if (_argMapper == null) _argMapper = new ArgMapper(this, false);
343             return _argMapper.GetArg(argNum);
344         }
345
346         [System.Security.SecurityCritical]  // auto-generated
347         public String GetInArgName(int index) 
348         { 
349             if (_argMapper == null) _argMapper = new ArgMapper(this, false);
350             return _argMapper.GetArgName(index);
351         }
352         
353         public Object[] InArgs                       
354         {
355             [System.Security.SecurityCritical]  // auto-generated
356             get
357             {
358                 if (_argMapper == null) _argMapper = new ArgMapper(this, false);
359                 return _argMapper.Args;
360             }
361         }
362
363         [System.Security.SecurityCritical]  // auto-generated
364         private void UpdateNames()
365         {
366             RemotingMethodCachedData methCache = 
367                 InternalRemotingServices.GetReflectionCachedData(GetMethodBase());
368             _typeName = methCache.TypeAndAssemblyName;
369             _MethodName = methCache.MethodName;
370         }
371
372         public String MethodName
373         { 
374             [System.Security.SecurityCritical]  // auto-generated
375             get 
376             { 
377                 if(null == _MethodName)
378                     UpdateNames();
379                 return _MethodName;
380             }
381         }
382         
383         public String TypeName
384         { 
385             [System.Security.SecurityCritical]  // auto-generated
386             get 
387             { 
388                 if (_typeName == null)
389                     UpdateNames();
390                 return _typeName;
391             }
392         }
393         
394         public Object MethodSignature
395         { 
396             [System.Security.SecurityCritical]  // auto-generated
397             get
398             {
399                 if(null == _MethodSignature)
400                     _MethodSignature = GenerateMethodSignature(GetMethodBase());
401                     
402                 return _MethodSignature;
403             }
404         }
405
406         public LogicalCallContext LogicalCallContext  
407         { 
408             [System.Security.SecurityCritical]  // auto-generated
409             get
410             {                
411                 return GetLogicalCallContext();                 
412             }
413         }
414
415         public MethodBase MethodBase
416         {
417             [System.Security.SecurityCritical]  // auto-generated
418             get
419             {
420                 return GetMethodBase();
421             }
422         }
423
424
425         //
426         // ISerializable
427         //
428         [System.Security.SecurityCritical]  // auto-generated_required
429         public void GetObjectData(SerializationInfo info, StreamingContext context)
430         {
431             throw new NotSupportedException(
432                 Environment.GetResourceString("NotSupported_Method"));                
433         }
434         
435         [System.Security.SecurityCritical]  // auto-generated
436         internal MethodBase GetMethodBase()
437         {
438             if(null == _MethodBase)
439             {
440                 unsafe 
441                 {
442                     IRuntimeMethodInfo mh = new RuntimeMethodInfoStub(_methodDesc, null);
443                     _MethodBase = RuntimeType.GetMethodBase(Type.GetTypeFromHandleUnsafe(_governingType), mh);
444                 }
445             }           
446             return _MethodBase;
447         }
448
449         [System.Security.SecurityCritical]  // auto-generated
450         internal LogicalCallContext SetLogicalCallContext(
451             LogicalCallContext callCtx)
452         {
453             LogicalCallContext oldCtx = _callContext;
454             _callContext = callCtx;
455             
456             return oldCtx;
457         }
458
459         [System.Security.SecurityCritical]  // auto-generated
460         internal LogicalCallContext GetLogicalCallContext()
461         {
462             if (_callContext == null)
463                 _callContext = new LogicalCallContext();
464             return _callContext;
465         }
466
467
468         // Internal helper to create method signature
469         [System.Security.SecurityCritical]  // auto-generated
470         internal static Type[] GenerateMethodSignature(MethodBase mb)
471         {
472             RemotingMethodCachedData methodCache = 
473                 InternalRemotingServices.GetReflectionCachedData(mb);
474                 
475             ParameterInfo[] paramArray = methodCache.Parameters;
476             Type[] methodSig = new Type[paramArray.Length];
477             for(int i = 0; i < paramArray.Length; i++)
478             {
479                 methodSig[i] = paramArray[i].ParameterType;
480             }
481
482             return methodSig;
483         } // GenerateMethodSignature
484         
485         //
486         // The following two routines are used by StackBuilderSink to check
487         // the consistency of arguments.
488         //
489         // Check that all the arguments are of the type 
490         // specified by the parameter list.
491         //
492         [System.Security.SecurityCritical]  // auto-generated
493         internal static Object[] CoerceArgs(IMethodMessage m)
494         {
495             MethodBase mb = m.MethodBase;
496             Contract.Assert(mb != null, "null method base passed to CoerceArgs");
497
498             RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(mb);
499             
500             return CoerceArgs(m, methodCache.Parameters);
501         } // CoerceArgs
502
503         [System.Security.SecurityCritical]  // auto-generated
504         internal static Object[] CoerceArgs(IMethodMessage m, ParameterInfo[] pi)
505         {
506             return CoerceArgs(m.MethodBase, m.Args, pi);
507         } // CoerceArgs
508
509         [System.Security.SecurityCritical]  // auto-generated
510         internal static Object[] CoerceArgs(MethodBase mb, Object[] args, ParameterInfo[] pi)
511         {
512             if (pi == null) 
513             {
514                 throw new ArgumentNullException("pi");
515             }
516             Contract.EndContractBlock();
517             
518             if (pi.Length != args.Length) 
519             {
520                 throw new RemotingException(
521                     String.Format(
522                         CultureInfo.CurrentCulture, Environment.GetResourceString(
523                             "Remoting_Message_ArgMismatch"),
524                         mb.DeclaringType.FullName, mb.Name,
525                         args.Length, pi.Length));
526             }
527             
528             for (int i=0; i < pi.Length; i++)
529             {
530                 ParameterInfo currentPi = pi[i];
531                 Type pt = currentPi.ParameterType;                    
532                 Object oArg = args[i];
533                 if (oArg != null) 
534                 {
535                     args[i] = CoerceArg(oArg, pt);
536                 }
537                 else
538                 {   
539                     if (pt.IsByRef)
540                     {
541                         Type paramType = pt.GetElementType();
542                         if (paramType.IsValueType)
543                         {
544                             // nullables can be null, 
545                             if (currentPi.IsOut)
546                             {
547                                 // we need to fill in the blanks for value types if they are null
548                                 args[i] = Activator.CreateInstance(paramType, true);
549                             }
550                             else
551                             {
552                                 if (!(paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable<>))) 
553                                 {
554                                     throw new RemotingException(
555                                         String.Format(
556                                             CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Message_MissingArgValue"),
557                                             paramType.FullName, i));
558                                 }
559                             }
560                         }
561                     }
562                     else
563                     {
564                         if (pt.IsValueType)
565                         {
566                             // nullables can be null, 
567                             if (!(pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>)))
568                             {
569                                 // A null value was passed as a value type parameter.
570                                 throw new RemotingException(
571                                     String.Format(
572                                         CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Message_MissingArgValue"),
573                                         pt.FullName, i));
574                             }
575                         }
576                     }
577                 }
578             }
579
580             return args;
581         } // CoerceArgs
582         
583         
584         [System.Security.SecurityCritical]  // auto-generated
585         internal static Object CoerceArg(Object value, Type pt)
586         {
587             Object ret = null;
588             
589             if(null != value)
590             {
591                 Exception inner = null;
592                 try
593                 {
594                     if (pt.IsByRef) 
595                     {
596                         pt = pt.GetElementType();
597                     }
598                 
599                     if (pt.IsInstanceOfType(value))
600                     {
601                         ret = value;
602                     }
603                     else
604                     {
605                         ret = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
606                     }
607                 }
608                 catch(Exception e)
609                 {
610                     // Quietly ignore all exceptions. We will throw
611                     // a more meaningful exception below.
612                     inner = e;
613                 }
614
615                 // If the coercion failed then throw an exception
616                 if(null == ret)
617                 {
618                     // NOTE: Do not call value.ToString() on proxies as
619                     // it results in loading the type and loss of refinement
620                     // optimization or denial of service attacks by loading
621                     // a lot of types in the server.
622                     String valueName = null;
623                     if(RemotingServices.IsTransparentProxy(value))
624                     {
625                         valueName = typeof(MarshalByRefObject).ToString();
626                     }
627                     else
628                     {
629                         valueName = value.ToString();
630                     }
631
632                     throw new RemotingException(                        
633                         String.Format(
634                             CultureInfo.CurrentCulture, Environment.GetResourceString(
635                                 "Remoting_Message_CoercionFailed"), valueName, pt), inner);                
636                 }
637             }
638                 
639             return ret;
640         } //end of CoerceArg
641
642         [System.Security.SecurityCritical]  // auto-generated
643         internal static Object SoapCoerceArg(Object value, Type pt, Hashtable keyToNamespaceTable)
644         {
645             Object ret = null;
646
647             if (value != null)
648             {
649                 try
650                 {
651                     if (pt.IsByRef) 
652                     {
653                         pt = pt.GetElementType();
654                     }
655                 
656                     if (pt.IsInstanceOfType(value))
657                     {
658                         ret = value;
659                     }
660                     else
661                     {
662                         String strValue = value as String;
663                         if (strValue != null)
664                         {
665                             if (pt == typeof(Double))
666                             {
667                                 if (strValue == "INF")
668                                     ret =  Double.PositiveInfinity;
669                                 else if (strValue == "-INF")
670                                     ret =  Double.NegativeInfinity;
671                                 else
672                                     ret = Double.Parse(strValue, CultureInfo.InvariantCulture);
673                             }
674                             else if (pt == typeof(Single))
675                             {
676                                 if (strValue == "INF")
677                                     ret =  Single.PositiveInfinity;
678                                 else if (strValue == "-INF")
679                                     ret =  Single.NegativeInfinity;
680                                 else
681                                     ret = Single.Parse(strValue, CultureInfo.InvariantCulture);
682                             }
683                             else if (SoapType.typeofISoapXsd.IsAssignableFrom(pt))
684                             { 
685                                 if (pt == SoapType.typeofSoapTime)
686                                     ret = SoapTime.Parse(strValue);
687                                 else if (pt == SoapType.typeofSoapDate)
688                                     ret = SoapDate.Parse(strValue);
689                                 else if (pt == SoapType.typeofSoapYearMonth)
690                                     ret = SoapYearMonth.Parse(strValue);
691                                 else if (pt == SoapType.typeofSoapYear)
692                                     ret = SoapYear.Parse(strValue);
693                                 else if (pt == SoapType.typeofSoapMonthDay)
694                                     ret = SoapMonthDay.Parse(strValue);
695                                 else if (pt == SoapType.typeofSoapDay)
696                                     ret = SoapDay.Parse(strValue);
697                                 else if (pt == SoapType.typeofSoapMonth)
698                                     ret = SoapMonth.Parse(strValue);
699                                 else if (pt == SoapType.typeofSoapHexBinary)
700                                     ret = SoapHexBinary.Parse(strValue);
701                                 else if (pt == SoapType.typeofSoapBase64Binary)
702                                     ret = SoapBase64Binary.Parse(strValue);
703                                 else if (pt == SoapType.typeofSoapInteger)
704                                     ret = SoapInteger.Parse(strValue);
705                                 else if (pt == SoapType.typeofSoapPositiveInteger)
706                                     ret = SoapPositiveInteger.Parse(strValue);
707                                 else if (pt == SoapType.typeofSoapNonPositiveInteger)
708                                     ret = SoapNonPositiveInteger.Parse(strValue);
709                                 else if (pt == SoapType.typeofSoapNonNegativeInteger)
710                                     ret = SoapNonNegativeInteger.Parse(strValue);
711                                 else if (pt == SoapType.typeofSoapNegativeInteger)
712                                     ret = SoapNegativeInteger.Parse(strValue);
713                                 else if (pt == SoapType.typeofSoapAnyUri)
714                                     ret = SoapAnyUri.Parse(strValue);
715                                 else if (pt == SoapType.typeofSoapQName)
716                                 {
717                                     ret = SoapQName.Parse(strValue);
718                                     SoapQName soapQName = (SoapQName)ret;
719                                     if (soapQName.Key.Length == 0)
720                                         soapQName.Namespace = (String)keyToNamespaceTable["xmlns"];
721                                     else
722                                         soapQName.Namespace = (String)keyToNamespaceTable["xmlns"+":"+soapQName.Key];
723                                 }
724                                 else if (pt == SoapType.typeofSoapNotation)
725                                     ret = SoapNotation.Parse(strValue);
726                                 else if (pt == SoapType.typeofSoapNormalizedString)
727                                     ret = SoapNormalizedString.Parse(strValue);
728                                 else if (pt == SoapType.typeofSoapToken)
729                                     ret = SoapToken.Parse(strValue);
730                                 else if (pt == SoapType.typeofSoapLanguage)
731                                     ret = SoapLanguage.Parse(strValue);
732                                 else if (pt == SoapType.typeofSoapName)
733                                     ret = SoapName.Parse(strValue);
734                                 else if (pt == SoapType.typeofSoapIdrefs)
735                                     ret = SoapIdrefs.Parse(strValue);
736                                 else if (pt == SoapType.typeofSoapEntities)
737                                     ret = SoapEntities.Parse(strValue);
738                                 else if (pt == SoapType.typeofSoapNmtoken)
739                                     ret = SoapNmtoken.Parse(strValue);
740                                 else if (pt == SoapType.typeofSoapNmtokens)
741                                     ret = SoapNmtokens.Parse(strValue);
742                                 else if (pt == SoapType.typeofSoapNcName)
743                                     ret = SoapNcName.Parse(strValue);
744                                 else if (pt == SoapType.typeofSoapId)
745                                     ret = SoapId.Parse(strValue);
746                                 else if (pt == SoapType.typeofSoapIdref)
747                                     ret = SoapIdref.Parse(strValue);
748                                 else if (pt == SoapType.typeofSoapEntity)
749                                     ret = SoapEntity.Parse(strValue);
750                             }
751                             else if (pt == typeof(Boolean))
752                             {
753                                 if (strValue == "1" || strValue == "true")
754                                     ret = (bool)true;
755                                 else if (strValue == "0" || strValue =="false")
756                                     ret = (bool)false;
757                                 else
758                                 {
759                                     throw new RemotingException(                        
760                                         String.Format(
761                                             CultureInfo.CurrentCulture, Environment.GetResourceString(
762                                                 "Remoting_Message_CoercionFailed"), strValue, pt));                
763                                 }
764                             }
765                             else if (pt == typeof(DateTime))
766                                 ret = SoapDateTime.Parse(strValue);
767                             else if (pt.IsPrimitive)
768                                 ret = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
769                             else if (pt == typeof(TimeSpan))
770                                 ret = SoapDuration.Parse(strValue);
771                             else if (pt == typeof(Char))
772                                 ret = strValue[0];
773
774                             else
775                                 ret = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture); //Should this just throw an exception
776                         }
777                         else
778                             ret = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
779                     }
780                 }
781                 catch(Exception )
782                 {
783                     // Quietly ignore all exceptions. We will throw
784                     // a more meaningful exception below.
785                 }
786
787                 // If the coercion failed then throw an exception
788                 if(null == ret)
789                 {
790                     // NOTE: Do not call value.ToString() on proxies as
791                     // it results in loading the type and loss of refinement
792                     // optimization or denial of service attacks by loading
793                     // a lot of types in the server.
794                     String valueName = null;
795                     if(RemotingServices.IsTransparentProxy(value))
796                     {
797                         valueName = typeof(MarshalByRefObject).ToString();
798                     }
799                     else
800                     {
801                         valueName = value.ToString();
802                     }
803
804                     throw new RemotingException(                        
805                         String.Format(
806                             CultureInfo.CurrentCulture, Environment.GetResourceString(
807                                 "Remoting_Message_CoercionFailed"), valueName, pt));                
808                 }
809             }
810                 
811             return ret;
812         }//end of SoapCoerceArg
813
814
815         [System.Security.SecurityCritical]  // auto-generated
816         [ResourceExposure(ResourceScope.None)]
817         [MethodImplAttribute(MethodImplOptions.InternalCall)]
818         internal extern bool InternalHasVarArgs();
819
820         [System.Security.SecurityCritical]  // auto-generated
821         [ResourceExposure(ResourceScope.None)]
822         [MethodImplAttribute(MethodImplOptions.InternalCall)]
823         internal extern int InternalGetArgCount();
824
825         [System.Security.SecurityCritical]  // auto-generated
826         [ResourceExposure(ResourceScope.None)]
827         [MethodImplAttribute(MethodImplOptions.InternalCall)]
828         private extern Object    InternalGetArg(int argNum);
829
830         [System.Security.SecurityCritical]  // auto-generated
831         [ResourceExposure(ResourceScope.None)]
832         [MethodImplAttribute(MethodImplOptions.InternalCall)]
833         private extern Object[]    InternalGetArgs();
834
835         [System.Security.SecurityCritical]  // auto-generated
836         [ResourceExposure(ResourceScope.None)]
837         [MethodImplAttribute(MethodImplOptions.InternalCall)]
838         public extern void PropagateOutParameters(Object[] OutArgs, Object retVal);
839
840         [System.Security.SecurityCritical]  // auto-generated
841         [ResourceExposure(ResourceScope.None)]
842         [MethodImplAttribute(MethodImplOptions.InternalCall)]
843         public extern bool   Dispatch(Object target);
844
845         //
846         // <
847
848         [System.Security.SecurityCritical]  // auto-generated
849         [System.Diagnostics.Conditional("_REMOTING_DEBUG")]
850         public static void DebugOut(String s)
851         {
852             BCLDebug.Trace(
853                 "REMOTE", "RMTING: Thrd " 
854                 + Thread.CurrentThread.GetHashCode() 
855                 + " : " + s);
856             OutToUnmanagedDebugger(
857                 "\nRMTING: Thrd "
858                 + Thread.CurrentThread.GetHashCode() 
859                 + " : " + s);
860         }
861
862         [System.Security.SecurityCritical]  // auto-generated
863         [ResourceExposure(ResourceScope.None)]
864         [MethodImplAttribute(MethodImplOptions.InternalCall)]
865         internal extern static void OutToUnmanagedDebugger(String s);
866
867         [System.Security.SecurityCritical]  // auto-generated
868         internal static LogicalCallContext PropagateCallContextFromMessageToThread(IMessage msg)
869         {
870             return CallContext.SetLogicalCallContext(
871                     (LogicalCallContext) msg.Properties[Message.CallContextKey]);            
872         }
873
874         [System.Security.SecurityCritical]  // auto-generated
875         internal static void PropagateCallContextFromThreadToMessage(IMessage msg)
876         {
877             LogicalCallContext callCtx = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
878             
879             msg.Properties[Message.CallContextKey] = callCtx;
880         }
881
882         [System.Security.SecurityCritical]  // auto-generated
883         internal static void PropagateCallContextFromThreadToMessage(IMessage msg, LogicalCallContext oldcctx)
884         {
885             // First do the common work
886             PropagateCallContextFromThreadToMessage(msg);
887
888             // restore the old call context on the thread
889             CallContext.SetLogicalCallContext(oldcctx);
890         }
891     }
892
893     //+================================================================================
894     //
895     // Synopsis:   Return message for constructors
896     //
897     //-================================================================================
898     [System.Security.SecurityCritical]  // auto-generated
899     internal class ConstructorReturnMessage : ReturnMessage, IConstructionReturnMessage
900     {
901
902         private const int Intercept = 0x1;
903
904         private MarshalByRefObject _o;
905         private int    _iFlags;
906
907
908         public ConstructorReturnMessage(MarshalByRefObject o, Object[] outArgs, int outArgsCount,
909                                         LogicalCallContext callCtx, IConstructionCallMessage ccm)
910         : base(o, outArgs, outArgsCount, callCtx, ccm)
911         {
912             _o = o;
913             _iFlags = Intercept;
914         }
915
916         public ConstructorReturnMessage(Exception e, IConstructionCallMessage ccm)
917         :       base(e, ccm)
918         {
919         }
920
921         public override  Object  ReturnValue
922         {
923             [System.Security.SecurityCritical]
924             get
925             {
926                 if (_iFlags == Intercept)
927                 {
928                     return RemotingServices.MarshalInternal(_o,null,null);
929                 }
930                 else
931                 {
932                     return base.ReturnValue;
933                 }
934             }
935         }
936
937
938         public override  IDictionary Properties
939         {
940             [System.Security.SecurityCritical]
941             get
942             {
943                 if (_properties == null)
944                 {
945                     Object properties = new CRMDictionary(this, new Hashtable());
946                     Interlocked.CompareExchange(ref _properties, properties, null);
947                 }
948                 return(IDictionary) _properties;
949             }
950         }
951
952         internal Object GetObject()
953         {
954             return _o;
955         }
956     }
957
958     //+========================================================================
959     //
960     // Synopsis:  client side implementation of activation message
961     //
962     //-========================================================================
963     internal class ConstructorCallMessage : IConstructionCallMessage
964     {
965
966         // data
967
968         private Object[]            _callSiteActivationAttributes;
969         private Object[]            _womGlobalAttributes;
970         private Object[]            _typeAttributes;
971
972         // The activation type isn't serialized because we want to 
973         // re-resolve the activation type name on the other side
974         // based on _activationTypeName.
975         [NonSerialized]
976         private RuntimeType         _activationType;
977         
978         private String              _activationTypeName;
979         
980         private IList               _contextProperties;
981         private int                 _iFlags;
982         private Message             _message;
983         private Object              _properties;
984         private ArgMapper           _argMapper; 
985         private IActivator          _activator;
986         
987         // flags
988         private const int CCM_ACTIVATEINCONTEXT = 0x01;
989
990         private ConstructorCallMessage()
991         {
992             // Default constructor
993         }
994
995         [System.Security.SecurityCritical]  // auto-generated
996         internal ConstructorCallMessage(Object[] callSiteActivationAttributes,
997                     Object[]womAttr, Object[] typeAttr, RuntimeType serverType)
998         {
999             _activationType = serverType;
1000             _activationTypeName = RemotingServices.GetDefaultQualifiedTypeName(_activationType);
1001             _callSiteActivationAttributes = callSiteActivationAttributes;
1002             _womGlobalAttributes = womAttr;
1003             _typeAttributes = typeAttr;
1004         }
1005
1006         [System.Security.SecurityCritical]  // auto-generated
1007         public Object GetThisPtr()
1008         {
1009             if (_message != null)
1010             {
1011                 return _message.GetThisPtr();
1012             }
1013             else
1014             {
1015                 throw new InvalidOperationException(
1016                     Environment.GetResourceString(
1017                         "InvalidOperation_InternalState"));
1018             }
1019         }
1020
1021         public Object[] CallSiteActivationAttributes
1022         {
1023             [System.Security.SecurityCritical]  // auto-generated
1024             get
1025             {
1026                 return _callSiteActivationAttributes;
1027             }
1028
1029         }
1030
1031         internal Object[] GetWOMAttributes()
1032         {
1033             return _womGlobalAttributes;
1034         }
1035
1036         internal Object[] GetTypeAttributes()
1037         {
1038             return _typeAttributes;
1039         }
1040
1041         public Type ActivationType
1042         {
1043             [System.Security.SecurityCritical]  // auto-generated
1044             get
1045             {
1046                 if ((_activationType == null) && (_activationTypeName != null))
1047                     _activationType = RemotingServices.InternalGetTypeFromQualifiedTypeName(_activationTypeName, false);
1048                     
1049                 return _activationType;
1050             }
1051         }
1052
1053         public String ActivationTypeName
1054         {
1055             [System.Security.SecurityCritical]  // auto-generated
1056             get
1057             {
1058                 return _activationTypeName;
1059             }
1060         }
1061
1062         public IList ContextProperties
1063         {
1064             [System.Security.SecurityCritical]  // auto-generated
1065             get
1066             {
1067                 if (_contextProperties == null)
1068                 {
1069                     _contextProperties = new ArrayList();
1070                 }
1071                 return _contextProperties;
1072             }
1073         }
1074
1075         public String Uri
1076         {
1077             [System.Security.SecurityCritical]  // auto-generated
1078             get
1079             {
1080                 if (_message != null)
1081                 {
1082                     return _message.Uri;
1083                 }
1084                 else
1085                 {
1086                     throw new InvalidOperationException(
1087                         Environment.GetResourceString(
1088                             "InvalidOperation_InternalState"));
1089                 }
1090             }
1091
1092             set
1093             {
1094                 if (_message != null)
1095                 {
1096                     _message.Uri = value;
1097                 }
1098                 else
1099                 {
1100                     throw new InvalidOperationException(
1101                         Environment.GetResourceString(
1102                             "InvalidOperation_InternalState"));
1103                 }
1104             }
1105
1106         }
1107
1108         public String MethodName
1109         {
1110             [System.Security.SecurityCritical]  // auto-generated
1111             get
1112             {
1113                 if (_message != null)
1114                 {
1115                     return _message.MethodName;
1116                 }
1117                 else
1118                 {
1119                     throw new InvalidOperationException(
1120                         Environment.GetResourceString(
1121                             "InvalidOperation_InternalState"));
1122                 }
1123             }
1124         }
1125
1126         public String TypeName
1127         {
1128             [System.Security.SecurityCritical]  // auto-generated
1129             get
1130             {
1131                 if (_message != null)
1132                 {
1133                     return _message.TypeName;
1134                 }
1135                 else
1136                 {
1137                     throw new InvalidOperationException(
1138                         Environment.GetResourceString(
1139                             "InvalidOperation_InternalState"));
1140                 }
1141             }
1142         }
1143
1144         public Object MethodSignature
1145         {
1146             [System.Security.SecurityCritical]  // auto-generated
1147             get
1148             {
1149                 if (_message != null)
1150                 {
1151                     return _message.MethodSignature;
1152                 }
1153                 else
1154                 {
1155                     throw new InvalidOperationException(
1156                         Environment.GetResourceString(
1157                             "InvalidOperation_InternalState"));
1158                 }
1159             }
1160         } // MethodSignature
1161
1162         public MethodBase MethodBase
1163         {
1164             [System.Security.SecurityCritical]  // auto-generated
1165             get
1166             {
1167                 if (_message != null)
1168                 {
1169                     return _message.MethodBase;
1170         }
1171                 else
1172                 {
1173                     throw new InvalidOperationException(
1174                         Environment.GetResourceString(
1175                             "InvalidOperation_InternalState"));
1176                 }
1177             }
1178         } // MethodBase
1179
1180
1181     /// <internalonly/>
1182         public int InArgCount                        
1183         { 
1184             [System.Security.SecurityCritical]  // auto-generated
1185             get 
1186             {
1187                 if (_argMapper == null) 
1188                     _argMapper = new ArgMapper(this, false);
1189                 return _argMapper.ArgCount;
1190             }
1191         }
1192
1193         [System.Security.SecurityCritical]  // auto-generated
1194         public Object  GetInArg(int argNum)   
1195         {   
1196             if (_argMapper == null) 
1197                 _argMapper = new ArgMapper(this, false);
1198             return _argMapper.GetArg(argNum);
1199         }
1200
1201     /// <internalonly/>
1202         [System.Security.SecurityCritical]  // auto-generated
1203         public String GetInArgName(int index) 
1204         { 
1205             if (_argMapper == null) 
1206                 _argMapper = new ArgMapper(this, false);
1207             return _argMapper.GetArgName(index);
1208         }
1209         public Object[] InArgs                       
1210         {
1211             [System.Security.SecurityCritical]  // auto-generated
1212             get
1213             {
1214                 if (_argMapper == null) 
1215                     _argMapper = new ArgMapper(this, false);
1216                 return _argMapper.Args;
1217             }
1218         }
1219     
1220         public int ArgCount
1221         {
1222             [System.Security.SecurityCritical]  // auto-generated
1223             get
1224             {
1225                 if (_message != null)
1226                 {
1227                     return _message.ArgCount;
1228                 }
1229                 else
1230                 {
1231                     throw new InvalidOperationException(
1232                         Environment.GetResourceString(
1233                             "InvalidOperation_InternalState"));
1234                 }
1235             }
1236         }
1237
1238         [System.Security.SecurityCritical]  // auto-generated
1239         public Object GetArg(int argNum)
1240         {
1241             if (_message != null)
1242             {
1243                 return _message.GetArg(argNum);
1244             }
1245             else
1246             {
1247                 throw new InvalidOperationException(
1248                     Environment.GetResourceString(
1249                         "InvalidOperation_InternalState"));
1250             }
1251         }
1252
1253         [System.Security.SecurityCritical]  // auto-generated
1254         public String GetArgName(int index)
1255         {
1256             if (_message != null)
1257             {
1258                 return _message.GetArgName(index);
1259             }
1260             else
1261             {
1262                 throw new InvalidOperationException(
1263                     Environment.GetResourceString(
1264                         "InvalidOperation_InternalState"));
1265             }
1266         }
1267
1268         public bool HasVarArgs
1269         {
1270             [System.Security.SecurityCritical]  // auto-generated
1271             get
1272             {
1273                 if (_message != null)
1274                 {
1275                     return _message.HasVarArgs;
1276                 }
1277                 else
1278                 {
1279                     throw new InvalidOperationException(
1280                         Environment.GetResourceString(
1281                             "InvalidOperation_InternalState"));
1282                 }
1283             }
1284         }
1285
1286         public Object[] Args
1287         {
1288             [System.Security.SecurityCritical]  // auto-generated
1289             get
1290             {
1291                 if (_message != null)
1292                 {
1293                     return _message.Args;
1294                 }
1295                 else
1296                 {
1297                     throw new InvalidOperationException(
1298                         Environment.GetResourceString(
1299                             "InvalidOperation_InternalState"));
1300                 }
1301             }
1302         }
1303
1304         public IDictionary Properties
1305         {
1306             [System.Security.SecurityCritical]  // auto-generated
1307             get
1308             {
1309                 if (_properties == null)
1310                 {
1311                     Object properties = new CCMDictionary(this, new Hashtable());
1312                     Interlocked.CompareExchange(ref _properties, properties, null);
1313                 }
1314                 return(IDictionary) _properties;
1315             }
1316         }
1317
1318         public IActivator Activator
1319         {
1320             [System.Security.SecurityCritical]  // auto-generated
1321             get { return _activator; }
1322             [System.Security.SecurityCritical]  // auto-generated
1323             set { _activator =  value; }
1324         }
1325
1326         public LogicalCallContext LogicalCallContext  
1327         { 
1328             [System.Security.SecurityCritical]  // auto-generated
1329             get
1330             {
1331                 return GetLogicalCallContext();                 
1332             }
1333         }
1334         
1335
1336         internal bool ActivateInContext
1337         {
1338             get { return((_iFlags & CCM_ACTIVATEINCONTEXT) != 0);}
1339             set { _iFlags = value ? (_iFlags | CCM_ACTIVATEINCONTEXT) : (_iFlags & ~CCM_ACTIVATEINCONTEXT);}
1340         }
1341
1342         [System.Security.SecurityCritical]  // auto-generated
1343         internal void SetFrame(MessageData msgData)
1344         {
1345             Contract.Assert(_message == null, "Can't set frame twice on ConstructorCallMessage");
1346             _message = new Message();
1347             _message.InitFields(msgData);
1348         }
1349
1350         [System.Security.SecurityCritical]  // auto-generated
1351         internal LogicalCallContext GetLogicalCallContext()
1352         {
1353             if (_message != null)
1354             {
1355                 return _message.GetLogicalCallContext();
1356             }
1357             else
1358             {
1359                 throw new InvalidOperationException(
1360                     Environment.GetResourceString(
1361                         "InvalidOperation_InternalState"));
1362             }
1363         }
1364
1365         [System.Security.SecurityCritical]  // auto-generated
1366         internal LogicalCallContext SetLogicalCallContext(LogicalCallContext ctx)
1367         {
1368             if (_message != null)
1369             {
1370                 return _message.SetLogicalCallContext(ctx);
1371             }
1372             else
1373             {
1374                 throw new InvalidOperationException(
1375                     Environment.GetResourceString(
1376                         "InvalidOperation_InternalState"));
1377             }
1378
1379         }
1380
1381         internal Message GetMessage()
1382         {
1383             return _message;
1384         }
1385     }
1386
1387     //+========================================================================
1388     //
1389     // Synopsis:   Specialization of MessageDictionary for
1390     //             ConstructorCallMessage objects
1391     //
1392     //-========================================================================
1393
1394     internal class CCMDictionary : MessageDictionary
1395     {
1396         public static String[] CCMkeys = {
1397             "__Uri",                //0
1398             "__MethodName",         //1
1399             "__MethodSignature",    //2
1400             "__TypeName",           //3
1401             "__Args",               //4
1402             "__CallContext",        //5
1403             "__CallSiteActivationAttributes",   //6
1404             "__ActivationType",         //7
1405             "__ContextProperties",  //8
1406             "__Activator",          //9
1407             "__ActivationTypeName"};         //10
1408
1409         internal IConstructionCallMessage _ccmsg;           // back pointer to message object
1410
1411
1412         public CCMDictionary(IConstructionCallMessage msg, IDictionary idict)
1413         : base(CCMkeys, idict)
1414         {
1415             _ccmsg = msg;
1416         }
1417
1418         [System.Security.SecuritySafeCritical]  // auto-generated
1419         internal override Object GetMessageValue(int i)
1420         {
1421             switch (i)
1422             {
1423             case 0:
1424                 return _ccmsg.Uri;
1425             case 1:
1426                 return _ccmsg.MethodName;
1427             case 2:
1428                 return _ccmsg.MethodSignature;
1429             case 3:
1430                 return _ccmsg.TypeName;
1431             case 4:
1432                 return _ccmsg.Args;
1433             case 5:
1434                 return FetchLogicalCallContext();
1435             case 6:
1436                 return _ccmsg.CallSiteActivationAttributes;
1437             case 7:
1438                 // This it to keep us from serializing the requested server type
1439                 return null;
1440             case 8:
1441                 return _ccmsg.ContextProperties;
1442             case 9:
1443                 return _ccmsg.Activator;
1444             case 10:
1445                 return _ccmsg.ActivationTypeName;
1446             }
1447             // We should not get here!
1448             throw new RemotingException(
1449                 Environment.GetResourceString(
1450                     "Remoting_Default"));                    
1451         }
1452
1453         [System.Security.SecurityCritical]  // auto-generated
1454         private LogicalCallContext FetchLogicalCallContext()
1455         {
1456             ConstructorCallMessage ccm = _ccmsg as ConstructorCallMessage;
1457             if (null != ccm)
1458             {
1459                 return ccm.GetLogicalCallContext();
1460             }
1461             else if (_ccmsg is ConstructionCall)
1462             {
1463                 // This is the case where the message got serialized
1464                 // and deserialized
1465                 return((MethodCall)_ccmsg).GetLogicalCallContext();
1466             }
1467             else
1468             {
1469                 throw new RemotingException(
1470                     Environment.GetResourceString(
1471                         "Remoting_Message_BadType"));                    
1472             }
1473         }
1474
1475         [System.Security.SecurityCritical]
1476         internal override void SetSpecialKey(int keyNum, Object value)
1477         {
1478             switch (keyNum)
1479             {
1480             case 0:
1481                 ((ConstructorCallMessage)_ccmsg).Uri = (String)value;
1482                 break;
1483             case 1:
1484                 ((ConstructorCallMessage)_ccmsg).SetLogicalCallContext(
1485                       (LogicalCallContext)value);
1486                 break;
1487             default:
1488                 // We should not get here!
1489                 throw new RemotingException(
1490                     Environment.GetResourceString(
1491                         "Remoting_Default"));                    
1492             }
1493         }
1494     }
1495
1496
1497     //+========================================================================
1498     //
1499     // Synopsis:   Specialization of MessageDictionary for ConstructorCallMessage objects
1500     //
1501     //-========================================================================
1502
1503     internal class CRMDictionary : MessageDictionary
1504     {
1505         public static String[]  CRMkeysFault = {
1506             "__Uri",
1507             "__MethodName",
1508             "__MethodSignature",
1509             "__TypeName",
1510             "__CallContext"};
1511         public static String[]  CRMkeysNoFault =  {
1512             "__Uri",
1513             "__MethodName",
1514             "__MethodSignature",
1515             "__TypeName",
1516             "__Return",
1517             "__OutArgs",            
1518             "__CallContext"};
1519         internal IConstructionReturnMessage _crmsg;
1520         internal bool fault;
1521
1522         [System.Security.SecurityCritical]  // auto-generated
1523         public CRMDictionary(IConstructionReturnMessage msg, IDictionary idict)
1524         : base( (msg.Exception!=null)? CRMkeysFault : CRMkeysNoFault, idict)
1525         {
1526             fault = (msg.Exception != null) ;
1527             _crmsg = msg;
1528         }
1529
1530         [System.Security.SecuritySafeCritical]  // auto-generated
1531         internal override Object GetMessageValue(int i)
1532         {
1533             switch (i)
1534             {
1535             case 0:
1536                 return _crmsg.Uri;
1537             case 1:
1538                 return _crmsg.MethodName;
1539             case 2:
1540                 return _crmsg.MethodSignature;
1541             case 3:
1542                 return _crmsg.TypeName;
1543             case 4:
1544                 return fault ? FetchLogicalCallContext() : _crmsg.ReturnValue;
1545             case 5:
1546                 return _crmsg.Args;
1547             case 6:
1548                 return FetchLogicalCallContext();
1549             }
1550             throw new RemotingException(
1551                 Environment.GetResourceString(
1552                     "Remoting_Default"));                    
1553         }
1554
1555         [System.Security.SecurityCritical]  // auto-generated
1556         private LogicalCallContext FetchLogicalCallContext()
1557         {
1558             ReturnMessage retMsg = _crmsg as ReturnMessage;
1559             if (null != retMsg)
1560             {
1561                 return retMsg.GetLogicalCallContext();
1562             }
1563             else 
1564             {
1565                 MethodResponse mr = _crmsg as MethodResponse;
1566                 if (null != mr)
1567                 {
1568                     return mr.GetLogicalCallContext();
1569                 }
1570                 else
1571                 {
1572                     throw new RemotingException(
1573                         Environment.GetResourceString(
1574                             "Remoting_Message_BadType"));                    
1575                 }
1576             }
1577         }
1578
1579         [System.Security.SecurityCritical]
1580         internal override void SetSpecialKey(int keyNum, Object value)
1581         {
1582             // NOTE: we use this for Uri & CallContext only ...
1583
1584             ReturnMessage rm = _crmsg as ReturnMessage;
1585             MethodResponse mr = _crmsg as MethodResponse;
1586             switch(keyNum)
1587             {
1588             case 0:
1589                 if (null != rm)
1590                 {
1591                     rm.Uri = (String)value;
1592                 }
1593                 else 
1594                 {
1595                     
1596                     if (null != mr)
1597                     {
1598                         mr.Uri = (String)value;
1599                     }
1600                     else
1601                     {
1602                         throw new RemotingException(
1603                             Environment.GetResourceString(
1604                                 "Remoting_Message_BadType"));                    
1605                     }                        
1606                 }
1607                 break;
1608             case 1:
1609                 if (null != rm)
1610                 {
1611                     rm.SetLogicalCallContext((LogicalCallContext)value);
1612                 }
1613                 else 
1614                 {
1615                     
1616                     if (null != mr)
1617                 {
1618                         mr.SetLogicalCallContext((LogicalCallContext)value);
1619                 }
1620                 else
1621                 {
1622                     throw new RemotingException(
1623                         Environment.GetResourceString(
1624                             "Remoting_Message_BadType"));                    
1625                 }
1626                 }
1627                 break;
1628             default:
1629                 throw new RemotingException(
1630                     Environment.GetResourceString(
1631                         "Remoting_Default"));                    
1632             }
1633         }
1634     }
1635
1636     //+================================================================================
1637     //
1638     // Synopsis:   Specialization of MessageDictionary for MethodCallMessage
1639     //
1640     //-========================================================================
1641
1642     internal class MCMDictionary : MessageDictionary
1643     {
1644         public static String[] MCMkeys = {
1645             "__Uri",
1646             "__MethodName",
1647             "__MethodSignature",
1648             "__TypeName",
1649             "__Args",
1650             "__CallContext"};
1651
1652         internal IMethodCallMessage _mcmsg;           // back pointer to message object
1653
1654
1655         public MCMDictionary(IMethodCallMessage msg, IDictionary idict)
1656         : base(MCMkeys, idict)
1657         {
1658             _mcmsg = msg;
1659         }
1660
1661         [System.Security.SecuritySafeCritical]  // auto-generated
1662         internal override Object GetMessageValue(int i)
1663         {
1664             switch (i)
1665             {
1666             case 0:
1667                 return _mcmsg.Uri;
1668             case 1:
1669                 return _mcmsg.MethodName;
1670             case 2:
1671                 return _mcmsg.MethodSignature;
1672             case 3:
1673                 return _mcmsg.TypeName;
1674             case 4:
1675                 return _mcmsg.Args;
1676             case 5:
1677                 return FetchLogicalCallContext();
1678             }
1679
1680             // Shouldn't get here.
1681             throw new RemotingException(
1682                 Environment.GetResourceString(
1683                     "Remoting_Default"));                    
1684         }
1685
1686         [System.Security.SecurityCritical]  // auto-generated
1687         private LogicalCallContext FetchLogicalCallContext()
1688         {
1689             Message msg = _mcmsg as Message;
1690             if (null != msg)
1691             {
1692                 return msg.GetLogicalCallContext();
1693             }
1694             else
1695             {
1696                 MethodCall mc = _mcmsg as MethodCall;
1697                 if (null != mc)
1698                 {
1699                     return mc.GetLogicalCallContext();
1700                 }                    
1701             else
1702             {
1703                 throw new RemotingException(
1704                     Environment.GetResourceString(
1705                         "Remoting_Message_BadType"));                    
1706             }                
1707         }        
1708         }
1709
1710         [System.Security.SecurityCritical]
1711         internal override void SetSpecialKey(int keyNum, Object value)
1712         {
1713             Message msg = _mcmsg as Message;
1714             MethodCall mc = _mcmsg as MethodCall;
1715             switch (keyNum)
1716             {
1717             case 0:
1718                 if(null != msg)
1719                 {
1720                     msg.Uri = (String)value;
1721                 }
1722                 else if (null != mc)
1723                 {
1724                     mc.Uri = (String)value;
1725                 }                
1726                 else
1727                 {
1728                     throw new RemotingException(
1729                         Environment.GetResourceString(
1730                             "Remoting_Message_BadType"));                    
1731                 }
1732             break;
1733
1734             case 1:               
1735                 if(null != msg)
1736                 {
1737                     msg.SetLogicalCallContext((LogicalCallContext)value);
1738                 }
1739                 else
1740                 {
1741                     throw new RemotingException(
1742                         Environment.GetResourceString(
1743                             "Remoting_Message_BadType"));                    
1744                 }
1745                 break;
1746             default:
1747                 // Shouldn't get here.
1748                 throw new RemotingException(
1749                     Environment.GetResourceString(
1750                         "Remoting_Default"));                    
1751             }        
1752         }
1753     }
1754
1755     //+================================================================================
1756     //
1757     // Synopsis:   Specialization of MessageDictionary for MethodReturnMessage objects
1758     //
1759     //-================================================================================
1760     internal class MRMDictionary : MessageDictionary
1761     {
1762         public static String[]  MCMkeysFault = {"__CallContext"};
1763         public static String[]  MCMkeysNoFault =  {
1764             "__Uri",
1765             "__MethodName",
1766             "__MethodSignature",
1767             "__TypeName",
1768             "__Return",
1769             "__OutArgs",
1770             "__CallContext"};
1771
1772         internal IMethodReturnMessage _mrmsg;
1773         internal bool fault;
1774
1775         [System.Security.SecurityCritical]  // auto-generated
1776         public MRMDictionary(IMethodReturnMessage msg, IDictionary idict)
1777         : base((msg.Exception != null) ? MCMkeysFault : MCMkeysNoFault, idict)
1778         {
1779             fault = (msg.Exception != null) ;
1780             _mrmsg = msg;
1781         }
1782
1783         [System.Security.SecuritySafeCritical]
1784         internal override Object GetMessageValue(int i)
1785         {
1786             switch (i)
1787             {
1788             case 0:
1789                 if (fault)
1790                     return FetchLogicalCallContext();
1791                 else
1792                     return _mrmsg.Uri;
1793             case 1:
1794                 return _mrmsg.MethodName;
1795             case 2:
1796                 return _mrmsg.MethodSignature;
1797             case 3:
1798                 return _mrmsg.TypeName;
1799             case 4:
1800                 if (fault)
1801                 {
1802                     return _mrmsg.Exception;
1803                 }
1804                 else
1805                 {
1806                     return _mrmsg.ReturnValue;
1807                 }
1808             case 5:
1809                 return _mrmsg.Args;
1810             case 6:
1811                 return FetchLogicalCallContext();
1812             }
1813             // Shouldn't get here.
1814             throw new RemotingException(
1815                 Environment.GetResourceString(
1816                     "Remoting_Default"));                    
1817         }
1818
1819         [System.Security.SecurityCritical]  // auto-generated
1820         private LogicalCallContext FetchLogicalCallContext()
1821         {
1822             ReturnMessage rm = _mrmsg as ReturnMessage;
1823             if (null != rm)
1824             {
1825                 return rm.GetLogicalCallContext();
1826             }
1827             else                 
1828             {
1829                 MethodResponse mr = _mrmsg as MethodResponse;
1830                 if (null != mr)
1831                 {
1832                     return mr.GetLogicalCallContext(); 
1833             }
1834                 else
1835                 {
1836                     StackBasedReturnMessage srm = _mrmsg as StackBasedReturnMessage;
1837                     if (null != srm)
1838             {
1839                         return srm.GetLogicalCallContext();
1840             }
1841             else
1842             {
1843                 throw new RemotingException(
1844                     Environment.GetResourceString(
1845                         "Remoting_Message_BadType"));                    
1846             }
1847         }        
1848             }
1849         }
1850
1851         [System.Security.SecurityCritical]
1852         internal override void SetSpecialKey(int keyNum, Object value)
1853         {
1854             // 0 == Uri
1855             // 1 == CallContext
1856             // NOTE : we use this for Uri & CallContext only ... 
1857             ReturnMessage rm = _mrmsg as ReturnMessage;
1858             MethodResponse mr = _mrmsg as MethodResponse;
1859
1860             switch (keyNum)
1861             {
1862             case 0:
1863                 if (null != rm)
1864                 {
1865                     rm.Uri = (String)value;
1866                 }
1867                 else 
1868                 {                    
1869                     if (null != mr)
1870                     {
1871                         mr.Uri = (String)value;
1872                     }
1873                     else
1874                     {
1875                         throw new RemotingException(
1876                             Environment.GetResourceString(
1877                                 "Remoting_Message_BadType"));                    
1878                     }            
1879                 }
1880                 break;
1881             case 1:
1882                 if (null != rm)
1883                 {
1884                     rm.SetLogicalCallContext((LogicalCallContext)value);
1885                 }
1886                 else 
1887                 {
1888                     
1889                     if (null != mr)
1890                 {
1891                         mr.SetLogicalCallContext((LogicalCallContext)value);
1892                 }
1893                 else
1894                 {
1895                     throw new RemotingException(
1896                         Environment.GetResourceString(
1897                             "Remoting_Message_BadType"));                    
1898                 }            
1899                 }
1900                 break;
1901             default:
1902                 // Shouldn't get here.
1903                 throw new RemotingException(
1904                     Environment.GetResourceString(
1905                         "Remoting_Default"));                    
1906             }        
1907         }
1908
1909     }
1910
1911     //+================================================================================
1912     //
1913     // Synopsis:   Abstract class to help present a dictionary view of an object
1914     //
1915     //-================================================================================
1916     internal abstract class MessageDictionary : IDictionary
1917     {
1918         internal String[] _keys;
1919         internal IDictionary  _dict;
1920
1921         internal MessageDictionary(String[] keys, IDictionary idict)
1922         {
1923             _keys = keys;
1924             _dict = idict;
1925         }        
1926
1927         internal bool HasUserData()
1928         {
1929             // used by message smuggler to determine if there is any custom user
1930             //   data in the dictionary
1931             if ((_dict != null) && (_dict.Count > 0))
1932                 return true;
1933             else
1934                 return false;
1935         }
1936
1937         // used by message smuggler, so that it doesn't have to iterate
1938         //   through special keys
1939         internal IDictionary InternalDictionary
1940         {
1941             get { return _dict; }
1942         }
1943         
1944
1945         internal abstract Object GetMessageValue(int i);
1946
1947         [System.Security.SecurityCritical]
1948         internal abstract void SetSpecialKey(int keyNum, Object value);
1949
1950         public virtual bool IsReadOnly { get { return false; } }
1951         public virtual bool IsSynchronized { get { return false; } }
1952         public virtual bool IsFixedSize { get { return false; } }
1953         
1954         public virtual Object SyncRoot { get { return this; } }
1955         
1956
1957         public virtual bool Contains(Object key)
1958         {
1959             if (ContainsSpecialKey(key))
1960             {
1961                 return true;
1962             }
1963             else if (_dict != null)
1964             {
1965                 return _dict.Contains(key);
1966             }
1967             return false;
1968         }
1969
1970         protected virtual bool ContainsSpecialKey(Object key)
1971         {
1972             if (!(key is System.String))
1973             {
1974                 return false;
1975             }
1976             String skey = (String) key;
1977             for (int i = 0 ; i < _keys.Length; i++)
1978             {
1979                 if (skey.Equals(_keys[i]))
1980                 {
1981                     return true;
1982                 }
1983             }
1984             return false;
1985         }
1986
1987         public virtual void CopyTo(Array array, int index)
1988         {
1989             for (int i=0; i<_keys.Length; i++)
1990             {
1991                 array.SetValue(GetMessageValue(i), index+i);
1992             }
1993
1994             if (_dict != null)
1995             {
1996                 _dict.CopyTo(array, index+_keys.Length);
1997             }
1998         }
1999
2000         public virtual Object this[Object key]
2001         {
2002             get
2003             {
2004                 System.String skey = key as System.String;
2005                 if (null != skey)
2006                 {
2007                     for (int i=0; i<_keys.Length; i++)
2008                     {
2009                         if (skey.Equals(_keys[i]))
2010                         {
2011                             return GetMessageValue(i);
2012                         }
2013                     }
2014                     if (_dict != null)
2015                     {
2016                         return _dict[key];
2017                     }
2018                 }
2019                 return null;
2020             }
2021             [System.Security.SecuritySafeCritical] // 
2022             set
2023             {
2024                 if (ContainsSpecialKey(key))
2025                 {
2026                     if (key.Equals(Message.UriKey))
2027                     {
2028                         SetSpecialKey(0,value);
2029                     }
2030                     else if (key.Equals(Message.CallContextKey))
2031                     {
2032                         SetSpecialKey(1,value);
2033                     }                    
2034                     else
2035                     {
2036                         throw new ArgumentException(
2037                             Environment.GetResourceString(
2038                                 "Argument_InvalidKey"));
2039                     }
2040                 }
2041                 else
2042                 {
2043                     if (_dict == null)
2044                     {
2045                         _dict = new Hashtable();
2046                     }
2047                     _dict[key] = value;
2048                 }
2049
2050             }
2051         }
2052
2053         IDictionaryEnumerator IDictionary.GetEnumerator()
2054         {
2055             return new MessageDictionaryEnumerator(this, _dict);
2056         }
2057
2058         IEnumerator IEnumerable.GetEnumerator()
2059         {
2060             throw new NotSupportedException();
2061         }
2062
2063
2064         public virtual void Add(Object key, Object value)
2065         {
2066             if (ContainsSpecialKey(key))
2067             {
2068                 throw new ArgumentException(
2069                     Environment.GetResourceString(
2070                         "Argument_InvalidKey"));
2071             } 
2072             else
2073             {
2074                 if (_dict == null)
2075                 {
2076                     // no need to interlock, message object not guaranteed to
2077                     // be thread-safe.
2078                     _dict = new Hashtable();
2079                 }
2080                 _dict.Add(key, value);
2081             }
2082         }
2083
2084         public virtual void Clear()
2085         {
2086             // Remove all the entries from the hash table
2087             if (null != _dict)
2088             {
2089                 _dict.Clear();
2090             }
2091         }
2092
2093         public virtual void Remove(Object key)
2094         {
2095             if (ContainsSpecialKey(key) || (_dict == null))
2096             {
2097                 throw new ArgumentException(
2098                     Environment.GetResourceString(
2099                         "Argument_InvalidKey"));
2100             } 
2101             else
2102             {
2103                 _dict.Remove(key);
2104             }
2105         }
2106
2107         public virtual ICollection Keys
2108         {
2109             get
2110             {
2111
2112                 int len = _keys.Length;
2113                 ICollection c = (_dict != null) ? _dict.Keys : null;
2114                 if (c != null)
2115                 {
2116                     len += c.Count;
2117                 }
2118
2119                 ArrayList l = new ArrayList(len);
2120                 for (int i = 0; i<_keys.Length; i++)
2121                 {
2122                     l.Add(_keys[i]);
2123                 }
2124
2125                 if (c != null)
2126                 {
2127                     l.AddRange(c);
2128                 }
2129
2130                 return l;
2131             }
2132         }
2133
2134         public virtual ICollection Values
2135         {
2136             get
2137             {
2138                 int len = _keys.Length;
2139                 ICollection c = (_dict != null) ? _dict.Keys : null;
2140                 if (c != null)
2141                 {
2142                     len += c.Count;
2143                 }
2144
2145                 ArrayList l = new ArrayList(len);
2146
2147                 for (int i = 0; i<_keys.Length; i++)
2148                 {
2149                     l.Add(GetMessageValue(i));
2150                 }
2151
2152                 if (c != null)
2153                 {
2154                     l.AddRange(c);
2155                 }
2156                 return l;
2157             }
2158         }
2159
2160         public virtual int Count
2161         {
2162             get
2163             {
2164                 if (_dict != null)
2165                 {
2166                     return _dict.Count+_keys.Length;
2167                 }
2168                 else
2169                 {
2170                     return _keys.Length;
2171                 }
2172             }
2173         }
2174
2175     }
2176
2177     //+================================================================================
2178     //
2179     // Synopsis:   Dictionary enumerator for helper class
2180     //
2181     //-================================================================================
2182     internal class MessageDictionaryEnumerator : IDictionaryEnumerator
2183     {
2184         private int i=-1;
2185         private IDictionaryEnumerator _enumHash;
2186         private MessageDictionary    _md;
2187
2188
2189         public MessageDictionaryEnumerator(MessageDictionary md, IDictionary hashtable)
2190         {
2191             _md = md;
2192             if (hashtable != null)
2193             {
2194                 _enumHash = hashtable.GetEnumerator();
2195             }
2196             else
2197             {
2198                 _enumHash = null;
2199             }
2200         }
2201         // Returns the key of the current element of the enumeration. The returned
2202         // value is undefined before the first call to GetNext and following
2203         // a call to GetNext that returned false. Multiple calls to
2204         // GetKey with no intervening calls to GetNext will return
2205         // the same object.
2206         //
2207         public Object Key {
2208             get {
2209                 Message.DebugOut("MessageDE::GetKey i = " + i + "\n");
2210                 if (i < 0)
2211                 {
2212                     throw new InvalidOperationException(
2213                         Environment.GetResourceString(
2214                             "InvalidOperation_InternalState"));
2215                 }
2216                 if (i < _md._keys.Length)
2217                 {
2218                     return _md._keys[i];
2219                 }
2220                 else
2221                 {
2222                     Contract.Assert(_enumHash != null,"_enumHash != null");
2223                     return _enumHash.Key;
2224                 }
2225             }
2226         }
2227
2228         // Returns the value of the current element of the enumeration. The
2229         // returned value is undefined before the first call to GetNext and
2230         // following a call to GetNext that returned false. Multiple calls
2231         // to GetValue with no intervening calls to GetNext will
2232         // return the same object.
2233         //
2234         public Object Value {
2235             get {
2236                 if (i < 0)
2237                 {
2238                     throw new InvalidOperationException(
2239                         Environment.GetResourceString(
2240                             "InvalidOperation_InternalState"));
2241                 }
2242
2243                 if (i < _md._keys.Length)
2244                 {
2245                     return _md.GetMessageValue(i);
2246                 }
2247                 else
2248                 {
2249                     Contract.Assert(_enumHash != null,"_enumHash != null");
2250                     return _enumHash.Value;
2251                 }
2252             }
2253         }
2254
2255         // Advances the enumerator to the next element of the enumeration and
2256         // returns a boolean indicating whether an element is available. Upon
2257         // creation, an enumerator is conceptually positioned before the first
2258         // element of the enumeration, and the first call to GetNext brings
2259         // the first element of the enumeration into view.
2260         //
2261         public bool MoveNext()
2262         {
2263             if (i == -2)
2264             {
2265                 throw new InvalidOperationException(
2266                     Environment.GetResourceString(
2267                         "InvalidOperation_InternalState"));
2268             }
2269             i++;
2270             if (i < _md._keys.Length)
2271             {
2272                 return true;
2273             }
2274             else
2275             {
2276                 if (_enumHash != null && _enumHash.MoveNext())
2277                 {
2278                     return true;
2279                 }
2280                 else
2281                 {
2282                     i = -2;
2283                     return false;
2284                 }
2285             }
2286         }
2287
2288         // Returns the current element of the enumeration. The returned value is
2289         // undefined before the first call to MoveNext and following a call
2290         // to MoveNext that returned false. Multiple calls to
2291         // Current with no intervening calls to MoveNext will return
2292         // the same object.
2293         //
2294         public Object Current {
2295             get {
2296                 return Entry;
2297             }
2298         }
2299
2300         public DictionaryEntry Entry {
2301             get {
2302                 return new DictionaryEntry(Key, Value);
2303             }
2304         }
2305
2306         // Resets the enumerator, positioning it before the first element.  If an
2307         // Enumerator doesn't support Reset, a NotSupportedException is
2308         // thrown.
2309         public void Reset()
2310         {
2311             i = -1;
2312             if (_enumHash != null)
2313             {
2314                 _enumHash.Reset();
2315             }
2316         }
2317     }
2318
2319     //+================================================================================
2320     //
2321     // Synopsis:   Message for return from a stack blit call
2322     //
2323     //-================================================================================
2324     internal class StackBasedReturnMessage : IMethodReturnMessage, IInternalMessage
2325     {
2326         Message _m;
2327         Hashtable _h;
2328         MRMDictionary _d;
2329         ArgMapper _argMapper;
2330
2331         internal StackBasedReturnMessage()      {}
2332
2333         // NOTE: This method is called multiple times as we reuse the
2334         // message object. Make sure that you reset any fields that you
2335         // add to the message object to the default values. This will
2336         // ensure that the reused message object starts with the correct
2337         // values.
2338         internal void InitFields(Message m)
2339         {
2340             _m = m;
2341             if (null != _h)
2342             {
2343                 // Remove all the hashtable entries
2344                 _h.Clear();
2345             }
2346             if (null != _d)
2347             {
2348                 // Remove all the dictionary entries
2349                 _d.Clear();
2350             }
2351         }
2352
2353         public String Uri
2354         {
2355             [System.Security.SecurityCritical]  // auto-generated
2356             get {return _m.Uri;}
2357         }
2358
2359         public String MethodName
2360         {
2361             [System.Security.SecurityCritical]  // auto-generated
2362             get {return _m.MethodName;}
2363         }
2364
2365         public String TypeName
2366         {
2367             [System.Security.SecurityCritical]  // auto-generated
2368             get {return _m.TypeName;}
2369         }
2370
2371         public Object MethodSignature
2372         {
2373             [System.Security.SecurityCritical]  // auto-generated
2374             get {return _m.MethodSignature;}
2375         }
2376
2377         public MethodBase MethodBase
2378         {
2379             [System.Security.SecurityCritical]  // auto-generated
2380             get {return _m.MethodBase;}
2381         }
2382
2383         public bool HasVarArgs
2384         {
2385             [System.Security.SecurityCritical]  // auto-generated
2386             get {return _m.HasVarArgs;}
2387         }
2388
2389         public int ArgCount
2390         {
2391             [System.Security.SecurityCritical]  // auto-generated
2392             get {return _m.ArgCount;}
2393         }
2394
2395         [System.Security.SecurityCritical]  // auto-generated
2396         public Object GetArg(int argNum)     {return _m.GetArg(argNum);}
2397         [System.Security.SecurityCritical]  // auto-generated
2398         public String GetArgName(int index)  {return _m.GetArgName(index);}
2399         public Object[] Args
2400         {
2401             [System.Security.SecurityCritical]  // auto-generated
2402             get {return _m.Args;}
2403         }
2404         public LogicalCallContext LogicalCallContext
2405         {
2406             [System.Security.SecurityCritical]  // auto-generated
2407             get { return _m.GetLogicalCallContext(); }
2408         }
2409
2410         [System.Security.SecurityCritical]  // auto-generated
2411         internal LogicalCallContext GetLogicalCallContext() {return _m.GetLogicalCallContext();}
2412         [System.Security.SecurityCritical]  // auto-generated
2413         internal LogicalCallContext SetLogicalCallContext(LogicalCallContext callCtx)
2414         {
2415             return _m.SetLogicalCallContext(callCtx);
2416         }
2417
2418         public int OutArgCount                        
2419         { 
2420             [System.Security.SecurityCritical]  // auto-generated
2421             get 
2422             {
2423                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2424                 return _argMapper.ArgCount;
2425             }
2426         }
2427
2428         [System.Security.SecurityCritical]  // auto-generated
2429         public Object  GetOutArg(int argNum)   
2430         {   
2431             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2432             return _argMapper.GetArg(argNum);
2433         }
2434
2435         [System.Security.SecurityCritical]  // auto-generated
2436         public String GetOutArgName(int index) 
2437         { 
2438             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2439             return _argMapper.GetArgName(index);
2440         }
2441         public Object[] OutArgs                       
2442         {
2443             [System.Security.SecurityCritical]  // auto-generated
2444             get
2445             {
2446                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2447                 return _argMapper.Args;
2448             }
2449         }
2450
2451         public Exception Exception
2452         {
2453             [System.Security.SecurityCritical]  // auto-generated
2454             get {return null;}
2455         }
2456
2457         public Object ReturnValue
2458         {
2459             [System.Security.SecurityCritical]  // auto-generated
2460             get {return _m.GetReturnValue();}
2461         }
2462
2463         public IDictionary Properties
2464         {
2465             [System.Security.SecurityCritical]  // auto-generated
2466             get
2467             {
2468                 lock(this)
2469                 {
2470                     if (_h == null)
2471                     {
2472                         _h = new Hashtable();
2473                     }
2474                     if (_d == null)
2475                     {
2476                         _d = new MRMDictionary(this, _h);
2477                     }
2478                     return _d;
2479                 }
2480             }
2481         }
2482
2483         //
2484         // IInternalMessage
2485         //
2486
2487         ServerIdentity IInternalMessage.ServerIdentityObject
2488         {
2489             [System.Security.SecurityCritical]
2490             get { return null; }
2491             [System.Security.SecurityCritical]
2492             set {}
2493         }
2494
2495         Identity IInternalMessage.IdentityObject
2496         {
2497             [System.Security.SecurityCritical]
2498             get { return null; }
2499             [System.Security.SecurityCritical]
2500             set {}
2501         }
2502
2503         [System.Security.SecurityCritical]
2504         void IInternalMessage.SetURI(String val)
2505         {
2506             _m.Uri = val;
2507         }
2508
2509         [System.Security.SecurityCritical]
2510         void IInternalMessage.SetCallContext(LogicalCallContext newCallContext)
2511         {
2512             _m.SetLogicalCallContext(newCallContext);
2513         }
2514
2515         [System.Security.SecurityCritical]
2516         bool IInternalMessage.HasProperties()
2517         {
2518             return _h != null;
2519         }
2520     } // class StackBasedReturnMessage
2521     
2522
2523     //+================================================================================
2524     //
2525     // Synopsis:   Message for return from a stack builder sink call
2526     //
2527     //-================================================================================
2528     [System.Security.SecurityCritical]  // auto-generated_required
2529     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
2530     [System.Runtime.InteropServices.ComVisible(true)]
2531     public class ReturnMessage : IMethodReturnMessage
2532     {
2533         internal Object         _ret;
2534         internal Object         _properties;
2535         internal String         _URI;
2536         internal Exception      _e;
2537         internal Object[]      _outArgs;
2538         internal int            _outArgsCount;
2539         internal String         _methodName;
2540         internal String         _typeName;
2541         internal Type[]         _methodSignature;
2542         internal bool           _hasVarArgs;
2543         internal LogicalCallContext _callContext;
2544         internal ArgMapper      _argMapper;
2545         internal MethodBase     _methodBase;
2546
2547         [System.Security.SecurityCritical]  // auto-generated
2548         public ReturnMessage(Object ret, Object[] outArgs, int outArgsCount, LogicalCallContext callCtx,
2549                              IMethodCallMessage mcm)
2550         {
2551             _ret = ret;
2552             _outArgs = outArgs;
2553             _outArgsCount = outArgsCount;
2554             
2555             if (callCtx != null)
2556                 _callContext = callCtx;
2557             else
2558                 _callContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
2559                 
2560             if (mcm != null)
2561             {
2562                 _URI = mcm.Uri;
2563                 _methodName = mcm.MethodName;
2564                 _methodSignature = null;
2565                 _typeName = mcm.TypeName;
2566                 _hasVarArgs = mcm.HasVarArgs;
2567                 _methodBase = mcm.MethodBase;
2568             }
2569         }
2570
2571         [System.Security.SecurityCritical]  // auto-generated
2572         public ReturnMessage(Exception e, IMethodCallMessage mcm)
2573         {
2574             _e   = IsCustomErrorEnabled()? new RemotingException(Environment.GetResourceString("Remoting_InternalError")):e;
2575             _callContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
2576             if (mcm != null)
2577             {
2578                 _URI = mcm.Uri;
2579                 _methodName = mcm.MethodName;
2580                 _methodSignature = null;
2581                 _typeName = mcm.TypeName;
2582                 _hasVarArgs = mcm.HasVarArgs;
2583                 _methodBase = mcm.MethodBase;
2584             }
2585         }
2586
2587         public String Uri
2588         {
2589             [System.Security.SecurityCritical]
2590             get { return _URI; }
2591             set { _URI = value; }
2592         }
2593         public String MethodName
2594         {
2595             [System.Security.SecurityCritical]
2596             get { return _methodName; }
2597         }
2598         public String TypeName
2599         {
2600             [System.Security.SecurityCritical]
2601             get { return _typeName; }
2602         }
2603         public Object MethodSignature 
2604         {
2605             [System.Security.SecurityCritical]
2606             get 
2607             { 
2608                 if ((_methodSignature == null) && (_methodBase != null))
2609                     _methodSignature = Message.GenerateMethodSignature(_methodBase);
2610                     
2611                 return _methodSignature; 
2612             }
2613         }
2614
2615         public MethodBase MethodBase
2616         {
2617             [System.Security.SecurityCritical]
2618             get { return _methodBase; }
2619         }
2620
2621         public bool HasVarArgs
2622         {
2623             [System.Security.SecurityCritical]
2624             get
2625             {
2626                 return _hasVarArgs;
2627             }
2628
2629         }
2630
2631         public int ArgCount
2632         {
2633             [System.Security.SecurityCritical]
2634             get
2635             {
2636                 if (_outArgs == null)
2637                 {
2638                     return _outArgsCount;
2639                 }
2640                 else
2641                 {
2642                     return _outArgs.Length;
2643                 }
2644             }
2645         }
2646
2647         [System.Security.SecurityCritical]
2648         public Object GetArg(int argNum)
2649         {
2650             if (_outArgs == null)
2651             {
2652                 if ((argNum<0) || (argNum>=_outArgsCount))
2653                 {
2654                     throw new ArgumentOutOfRangeException("argNum");
2655                 }
2656                 return null;
2657             }
2658             else
2659             {
2660                 if ((argNum<0) || (argNum>=_outArgs.Length))
2661                 {
2662                     throw new ArgumentOutOfRangeException("argNum");
2663                 }
2664                 return _outArgs[argNum];
2665             }
2666
2667         }
2668
2669         [System.Security.SecurityCritical]  // auto-generated
2670         public String GetArgName(int index)
2671         {
2672
2673             if (_outArgs == null)
2674             {
2675                 if ((index < 0) || (index>=_outArgsCount))
2676                 {
2677                     throw new ArgumentOutOfRangeException("index");
2678                 }
2679             }
2680             else
2681             {
2682                 if ((index < 0) || (index>=_outArgs.Length))
2683                 {
2684                     throw new ArgumentOutOfRangeException("index");
2685                 }
2686             }
2687             
2688             if (_methodBase != null)
2689             {
2690                 RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(_methodBase);             
2691                 return methodCache.Parameters[index].Name;
2692             }
2693             else
2694                 return "__param" + index;
2695         }
2696
2697         public Object[] Args
2698         {
2699             [System.Security.SecurityCritical]
2700             get
2701             {
2702                 if (_outArgs == null)
2703                 {
2704                     return new Object[_outArgsCount];
2705                 }
2706                 return _outArgs;
2707             }
2708         }
2709
2710         public int OutArgCount                        
2711         {
2712             [System.Security.SecurityCritical]
2713             get 
2714             {
2715                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2716                 return _argMapper.ArgCount;
2717             }
2718         }
2719
2720         [System.Security.SecurityCritical]
2721         public Object GetOutArg(int argNum)   
2722         {   
2723             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2724             return _argMapper.GetArg(argNum);
2725         }
2726
2727         [System.Security.SecurityCritical]
2728         public String GetOutArgName(int index) 
2729         { 
2730             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2731             return _argMapper.GetArgName(index);
2732         }
2733         public Object[] OutArgs                       
2734         {
2735             [System.Security.SecurityCritical]
2736             get
2737             {
2738                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
2739                 return _argMapper.Args;
2740             }
2741         }
2742
2743         public Exception Exception
2744         {
2745             [System.Security.SecurityCritical]
2746             get { return _e; }
2747         }
2748         public virtual Object ReturnValue
2749         {
2750             [System.Security.SecurityCritical]
2751             get { return _ret; }
2752         }
2753
2754         public virtual IDictionary Properties
2755         {
2756             [System.Security.SecurityCritical]
2757             get
2758             {
2759                 if (_properties == null)
2760                 {
2761                     _properties = new MRMDictionary(this, null);
2762                 }
2763                 return(MRMDictionary) _properties;
2764             }
2765         }
2766
2767         public LogicalCallContext LogicalCallContext 
2768         {
2769             [System.Security.SecurityCritical]  // auto-generated
2770             get { return GetLogicalCallContext();}
2771         }
2772             
2773
2774         [System.Security.SecurityCritical]  // auto-generated
2775         internal LogicalCallContext GetLogicalCallContext()
2776         {
2777             if (_callContext == null)
2778                 _callContext = new LogicalCallContext();
2779             return _callContext;
2780         }
2781
2782         internal LogicalCallContext SetLogicalCallContext(LogicalCallContext ctx)
2783         {
2784             LogicalCallContext old = _callContext;
2785             _callContext=ctx;
2786             return old;
2787         }
2788
2789         // used to determine if the properties dictionary has already been created
2790         internal bool HasProperties()
2791         {
2792             return _properties != null;
2793         }
2794         [System.Security.SecurityCritical]  // auto-generated
2795         static internal bool IsCustomErrorEnabled(){
2796             Object oIsCustomErrorEnabled  = CallContext.GetData("__CustomErrorsEnabled");
2797             // The server side will always have this CallContext item set. If it is not set then
2798             // it means this is the client side. In that case customError is false.
2799             return (oIsCustomErrorEnabled == null) ? false:(bool)oIsCustomErrorEnabled;
2800         }
2801
2802     } // class ReturnMessage
2803     
2804     //+================================================================================
2805     //
2806     // Synopsis:   Message used for deserialization of a method call
2807     //
2808     //-================================================================================
2809     /// <internalonly/>
2810     [System.Security.SecurityCritical]  // auto-generated_required
2811     [Serializable]
2812     [CLSCompliant(false)]
2813     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
2814     [System.Runtime.InteropServices.ComVisible(true)]
2815     public class MethodCall : IMethodCallMessage, ISerializable, IInternalMessage, ISerializationRootObject
2816     {
2817
2818         private const BindingFlags LookupAll = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
2819         private const BindingFlags LookupPublic = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
2820
2821         // data
2822         private String uri;
2823         private String methodName;
2824         private MethodBase MI;
2825         private String typeName;
2826         private Object[] args;
2827         private Type[] instArgs;
2828         private LogicalCallContext callContext;
2829         private Type[] methodSignature;
2830     /// <internalonly/>
2831         protected IDictionary ExternalProperties = null;
2832     /// <internalonly/>
2833         protected IDictionary InternalProperties = null;
2834
2835         private ServerIdentity srvID;
2836         private Identity identity;
2837         private bool fSoap;
2838         private bool fVarArgs = false;
2839         private ArgMapper argMapper;
2840
2841         //
2842         // MethodCall -- SOAP uses this constructor
2843         //
2844
2845     /// <internalonly/>
2846         [System.Security.SecurityCritical]  // auto-generated
2847         public MethodCall(Header[] h1)
2848         {
2849             Message.DebugOut("MethodCall ctor IN headers: " + (h1 == null ? "<null>" : h1.ToString()) + "\n");
2850
2851             Init();
2852
2853             fSoap = true;
2854             FillHeaders(h1);            
2855
2856             ResolveMethod();
2857
2858             Message.DebugOut("MethodCall ctor OUT\n");
2859         }
2860
2861         //
2862         // MethodCall -- this constructor is used for copying an existing message
2863         //
2864
2865         [System.Security.SecurityCritical]  // auto-generated
2866         public MethodCall(IMessage msg)            
2867         {
2868             if (msg == null)
2869                 throw new ArgumentNullException("msg");
2870             Contract.EndContractBlock();
2871
2872             Init();
2873             
2874             IDictionaryEnumerator de = msg.Properties.GetEnumerator();
2875             while (de.MoveNext())
2876             {
2877                 FillHeader(de.Key.ToString(), de.Value);
2878             }
2879         
2880             IMethodCallMessage mcm = msg as IMethodCallMessage;
2881             if (mcm != null)
2882
2883                 MI = mcm.MethodBase;
2884                     
2885             ResolveMethod();
2886         } 
2887                 
2888         [System.Security.SecurityCritical]  // auto-generated
2889         internal MethodCall(SerializationInfo info, StreamingContext context) 
2890         {        
2891             if (info == null)
2892                 throw new ArgumentNullException("info");
2893             Contract.EndContractBlock();
2894             Init();
2895
2896             SetObjectData(info, context);
2897         }
2898
2899
2900         [System.Security.SecurityCritical]  // auto-generated
2901         internal MethodCall(SmuggledMethodCallMessage smuggledMsg, ArrayList deserializedArgs)
2902         {
2903             uri = smuggledMsg.Uri;
2904             typeName = smuggledMsg.TypeName;
2905             methodName = smuggledMsg.MethodName;
2906             methodSignature = (Type[])smuggledMsg.GetMethodSignature(deserializedArgs);
2907             args = smuggledMsg.GetArgs(deserializedArgs);
2908             instArgs = smuggledMsg.GetInstantiation(deserializedArgs);
2909             callContext = smuggledMsg.GetCallContext(deserializedArgs);
2910    
2911             ResolveMethod();
2912
2913             if (smuggledMsg.MessagePropertyCount > 0)
2914                 smuggledMsg.PopulateMessageProperties(Properties, deserializedArgs);
2915         }
2916
2917         [System.Security.SecurityCritical]  // auto-generated
2918         internal MethodCall(Object handlerObject, BinaryMethodCallMessage smuggledMsg)
2919         {
2920             if (handlerObject != null)
2921             {
2922                 uri = handlerObject as String;
2923                 if (uri == null)
2924                 {
2925                     // This must be the tranparent proxy
2926                     MarshalByRefObject mbr = handlerObject as MarshalByRefObject;
2927                     if (mbr != null)
2928                     {                      
2929                         bool fServer;
2930                         srvID = MarshalByRefObject.GetIdentity(mbr, out fServer) as ServerIdentity; 
2931                         uri = srvID.URI;
2932                     }
2933                 }
2934             }
2935
2936             typeName = smuggledMsg.TypeName;
2937             methodName = smuggledMsg.MethodName;
2938             methodSignature = (Type[])smuggledMsg.MethodSignature;
2939             args = smuggledMsg.Args;
2940             instArgs = smuggledMsg.InstantiationArgs;
2941             callContext = smuggledMsg.LogicalCallContext;
2942
2943             ResolveMethod();
2944
2945             if (smuggledMsg.HasProperties)
2946                 smuggledMsg.PopulateMessageProperties(Properties);
2947         }
2948
2949         
2950
2951         //
2952         // ISerializationRootObject
2953         //
2954     /// <internalonly/>
2955         [System.Security.SecurityCritical]  // auto-generated
2956         public void RootSetObjectData(SerializationInfo info, StreamingContext ctx)
2957         {
2958             SetObjectData(info, ctx);
2959         }
2960
2961         //
2962         // SetObjectData -- the class can also be initialized in part or in whole by serialization
2963         // in the SOAP case, both the constructor and SetObjectData init the object, in the non-SOAP
2964         // case, just SetObjectData is called
2965         //
2966
2967         [System.Security.SecurityCritical]  // auto-generated
2968         internal void SetObjectData(SerializationInfo info, StreamingContext context)
2969         {
2970             if (info == null)
2971                 throw new ArgumentNullException("info");
2972             Contract.EndContractBlock();
2973
2974             if (fSoap)
2975             {
2976                 SetObjectFromSoapData(info);
2977             }
2978             else
2979             {
2980                 SerializationInfoEnumerator siEnum = info.GetEnumerator();
2981                 while (siEnum.MoveNext())
2982                 {
2983                     FillHeader(siEnum.Name, siEnum.Value);
2984                 }
2985                 if ((context.State == StreamingContextStates.Remoting) && 
2986                     (context.Context != null))
2987                 {
2988                     Header[] h = context.Context as Header[];
2989                     if(null != h)
2990                     {
2991                         for (int i=0; i<h.Length; i++)
2992                             FillHeader(h[i].Name, h[i].Value);
2993                     }                
2994                 }
2995             }
2996         } // SetObjectData
2997  
2998         //
2999         // ResolveMethod
3000         //
3001
3002 #if FEATURE_REMOTING
3003         // This is used by Remoting
3004         private static Type ResolveTypeRelativeTo(String typeName, int offset, int count, Type serverType)
3005         {
3006             Type type = ResolveTypeRelativeToBaseTypes(typeName, offset, count, serverType);
3007             if (type == null)
3008             {
3009                 // compare against the interface list
3010                 // GetInterfaces() returns a complete list of interfaces this type supports
3011                 Type[] interfaces = serverType.GetInterfaces();
3012                 foreach (Type iface in interfaces)
3013                 {
3014                     String ifaceTypeName = iface.FullName;
3015                     if (ifaceTypeName.Length == count)
3016                     {
3017                         if (String.CompareOrdinal(typeName, offset, ifaceTypeName, 0, count) == 0)
3018                         {
3019                             return iface;
3020                         }
3021                     }
3022                 }
3023             }
3024
3025             return type;
3026         } // ResolveTypeRelativeTo
3027
3028         // This is used by Remoting
3029         private static Type ResolveTypeRelativeToBaseTypes(String typeName, int offset, int count, Type serverType)
3030         {
3031             // typeName is excepted to contain the full type name
3032             // offset is the start of the full type name within typeName
3033             // count us the number of characters in the full type name
3034             // serverType is the type of the server object
3035
3036             if ((typeName == null) || (serverType == null))
3037                 return null;
3038
3039             String serverTypeName = serverType.FullName;
3040             if (serverTypeName.Length == count)
3041             {
3042                 if (String.CompareOrdinal(typeName, offset, serverTypeName, 0, count) == 0)
3043                 {
3044                     return serverType;
3045                 }
3046             }
3047
3048             return ResolveTypeRelativeToBaseTypes(typeName, offset, count, serverType.BaseType);
3049         } // ResolveTypeRelativeTo
3050 #endif // FEATURE_REMOTING
3051
3052         internal Type ResolveType()
3053         {        
3054             // resolve type
3055             Type t = null;
3056
3057             if (srvID == null)
3058                 srvID = IdentityHolder.CasualResolveIdentity(uri) as ServerIdentity;                
3059
3060             if (srvID != null)
3061             {
3062                 Type serverType = srvID.GetLastCalledType(typeName);
3063                 if (serverType != null)
3064                         return serverType;
3065                 int startIndex = 0; // start of type name
3066
3067                 // check to see if type name starts with "clr:"
3068                 if (String.CompareOrdinal(typeName, 0, "clr:", 0, 4) == 0)
3069                 {
3070                     // type starts just past "clr:"
3071                     startIndex = 4;
3072                 }
3073
3074                 // find end of full type name
3075                 int index = typeName.IndexOf(',', startIndex);
3076                 if (index == -1)
3077                     index = typeName.Length;
3078
3079                 serverType = srvID.ServerType;
3080                 t = ResolveTypeRelativeTo(typeName, startIndex, index - startIndex, serverType);
3081             }
3082
3083             if (t == null)
3084             {
3085                 // fall back to Type.GetType() in case someone isn't using
3086                 //   our convention for the TypeName
3087                 t = RemotingServices.InternalGetTypeFromQualifiedTypeName(typeName);
3088             }
3089             if (srvID != null)
3090                 srvID.SetLastCalledType(typeName, t);
3091             return t;
3092         } // ResolveType
3093
3094
3095     /// <internalonly/>
3096         [System.Security.SecurityCritical]  // auto-generated
3097         public void ResolveMethod()
3098         {
3099             ResolveMethod(true);
3100         }
3101
3102         [System.Security.SecurityCritical]  // auto-generated
3103         internal void ResolveMethod(bool bThrowIfNotResolved)
3104         {
3105             if ((MI == null) && (methodName != null))
3106             {
3107                 BCLDebug.Trace("REMOTE", "TypeName: " + (typeName == null ? "<null>" : typeName) + "\n");
3108
3109                 // resolve type
3110                 RuntimeType t = ResolveType() as RuntimeType;
3111                 
3112                 BCLDebug.Trace("REMOTE", "Type: " + (t == null ? "<null>" : t.ToString()) + "\n");
3113                 if (methodName.Equals(".ctor"))
3114                     return;
3115                 if (t == null)
3116                 {
3117                     throw new RemotingException(
3118                         String.Format(
3119                             CultureInfo.CurrentCulture, Environment.GetResourceString(
3120                                 "Remoting_BadType"),
3121                             typeName));
3122                 }
3123
3124                 // Note: we reflect on non-public members here .. we do
3125                 // block incoming remote calls and allow only specific methods
3126                 // that we use for implementation of certain features (eg.
3127                 // for remote field access)
3128
3129                 // ***********************************************************
3130                 // Note: For the common (non-overloaded method, urt-to-urt) case
3131                 // methodSignature is null.
3132                 // If the call is from a urt client to an overloaded method, 
3133                 // methodSignature is non-null. We could have a non-null 
3134                 // methodSignature if the call is from a non-urt client for 
3135                 // which we have to do special work if the method is overloaded
3136                 // (in the try-catch below).
3137                 // ***********************************************************
3138                 if (null != methodSignature)
3139                 {
3140                     bool found = false;
3141                     
3142                     int arity = instArgs == null ? 0 : instArgs.Length;
3143
3144                     // Handle the common case efficiently, using GetMethod.
3145                     // Note that GetMethod doesn't match methods with uninstantiated 
3146                     // generic arguments, so we can only use the fast case for 
3147                     // non-generic methods.
3148                     if (arity == 0)
3149                     {
3150                         try
3151                         {
3152                             MI = t.GetMethod(methodName,
3153                                              MethodCall.LookupAll,
3154                                              null,
3155                                              CallingConventions.Any,
3156                                              methodSignature,
3157                                              null);
3158                             found = true;
3159                         }
3160                         catch (AmbiguousMatchException)
3161                         {
3162                             // There is more than one match, so we'll have to do 
3163                             // a full search.
3164                         }
3165                     }
3166
3167                     // Do a more thorough search if the fast case didn't succeed.
3168                     if(!found)
3169                     {
3170                         // Make a list of all the methods with the right name.
3171                         MemberInfo [] methods = t.FindMembers(MemberTypes.Method, MethodCall.LookupAll, Type.FilterName, methodName);
3172
3173                         // Filter out all the methods with the wrong arity.
3174                         // (Compress them into the start of the array then copy
3175                         // them into a new array of exactly the right length).
3176                         int candidates = 0;
3177                         for (int i = 0; i < methods.Length; i++)
3178                         {
3179                             // MakeGenericMethod might throw if the generic arguments
3180                             // can't be applied to the method in a type-safe way.
3181                             // In that case, continue with the next method.
3182                             try
3183                             {
3184                                 MethodInfo mi = (MethodInfo)methods[i];
3185                                 int miArity = mi.IsGenericMethod ? mi.GetGenericArguments().Length : 0;
3186                                 if (miArity == arity)
3187                                 {
3188                                     // Fill in generic arguments.
3189                                     if (arity > 0)
3190                                     {
3191                                         mi = mi.MakeGenericMethod(instArgs);
3192                                     }
3193                                     // Got a candidate, compress it back to the
3194                                     // start of the array.
3195                                     methods[candidates] = mi;
3196                                     candidates++;
3197                                 }
3198                             }
3199                             catch (ArgumentException) { }
3200                             catch (VerificationException) { }
3201                         }
3202
3203                         MethodInfo[] matches = new MethodInfo[candidates];
3204                         for (int i = 0; i < candidates; i++)
3205                             matches[i] = (MethodInfo)methods[i];
3206
3207                         // Use the default binder to select the right overload
3208                         // based on signature.
3209                         MI = Type.DefaultBinder.SelectMethod(MethodCall.LookupAll,
3210                                                              matches,
3211                                                              methodSignature,
3212                                                              null);
3213                     }
3214
3215                     BCLDebug.Trace("REMOTE", "Method resolved w/sig ", MI == null ? "<null>" : "<not null>");
3216                 }
3217                 else
3218                 {
3219                     
3220                     // Check the cache to see if you find the methodbase (unless
3221                     // the method has an instantiation, in which case the method
3222                     // name is not a unique key).
3223                     RemotingTypeCachedData typeCache = null;
3224                     if (instArgs == null)
3225                     {
3226                         typeCache = InternalRemotingServices.GetReflectionCachedData(t);
3227                         MI = typeCache.GetLastCalledMethod(methodName);
3228                         if (MI != null)
3229                             return;
3230                     }
3231
3232                     // This could give us the wrong MethodBase because
3233                     // the server and the client types could be of different 
3234                     // versions. The mismatch is caught either when the server has
3235                     // more than one method defined with the same name or when we
3236                     // coerce the args and the incoming argument types do not match 
3237                     // the method signature.                    
3238                     
3239                     Contract.Assert(
3240                         !methodName.Equals(".ctor"),
3241                         "unexpected method type");
3242
3243                     bool bOverloaded = false;
3244
3245                     try
3246                     {
3247                         MI = t.GetMethod(methodName,
3248                                          MethodCall.LookupAll);
3249
3250                         if (instArgs != null && instArgs.Length > 0)
3251                             MI = ((MethodInfo)MI).MakeGenericMethod(instArgs);
3252
3253                         BCLDebug.Trace("REMOTE", "Method resolved w/name ", MI == null ? "<null>" : methodName);
3254                         BCLDebug.Trace("REMOTE", "sig not filled in!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
3255                     }
3256                     catch (AmbiguousMatchException)
3257                     {
3258                         // This is the case when no methodSignature was found
3259                         // but the method is overloaded .. 
3260                         // (possibly because a non-URT client called us)
3261                         bOverloaded = true;                        
3262                         ResolveOverloadedMethod(t);
3263                     } //catch                    
3264
3265                     // In the non-URT call, overloaded case, don't cache the MI
3266                     // Avoid caching generic methods -- their names aren't a unique key.
3267                     if (MI != null && !bOverloaded && typeCache != null)
3268                         typeCache.SetLastCalledMethod(methodName, MI);
3269                 }
3270     
3271                 if (MI == null && bThrowIfNotResolved)
3272                 {   
3273                     throw new RemotingException(
3274                         String.Format(
3275                             CultureInfo.CurrentCulture, Environment.GetResourceString(
3276                                 "Remoting_Message_MethodMissing"),
3277                             methodName,
3278                             typeName));
3279                 }
3280             }
3281         }
3282
3283         // Helper that gets called when we attempt to resolve a method
3284         // without an accompanying methodSignature ... current thinking is
3285         // that we should make a good faith attempt by matching argument
3286         // counts
3287
3288         void ResolveOverloadedMethod(RuntimeType t)
3289         {
3290             // args is null the first call from soap because we havem't passed the arguments yet.
3291             if (args == null) 
3292                 return;
3293
3294             MemberInfo[] canidates = t.GetMember(methodName, MemberTypes.Method, MethodCall.LookupPublic);
3295
3296             int canidatesCount = canidates.Length;
3297
3298             if (canidatesCount == 1)
3299             {
3300                 MI = canidates[0] as MethodBase;
3301                 return;
3302             }
3303
3304             if (canidatesCount == 0)
3305                 return;
3306
3307             int argCount = args.Length;
3308             MethodBase match = null;
3309
3310             // We will let resolve succeed if exactly one of the overloaded methods matches in terms of argCount
3311             for (int i = 0; i < canidatesCount; i++)
3312             {
3313                 MethodBase canidate = canidates[i] as MethodBase;
3314                 if (canidate.GetParameters().Length == argCount)
3315                 {
3316                     if (match != null)
3317                         throw new RemotingException(Environment.GetResourceString("Remoting_AmbiguousMethod"));
3318
3319                     match = canidate;
3320                 } 
3321             }
3322
3323             if (match != null)
3324                 MI = match;
3325         }
3326
3327         // This will find the right overloaded method if the argValues from soap have type information,
3328         // By default parameters will be of type string, this could lead to a wrong choice of methodbase.
3329         void ResolveOverloadedMethod(RuntimeType t, String methodName, ArrayList argNames, ArrayList argValues)
3330         {
3331             MemberInfo[] canidates = t.GetMember(methodName, MemberTypes.Method, MethodCall.LookupPublic);
3332
3333             int canidatesCount = canidates.Length;
3334
3335             if (canidatesCount == 1)
3336             {
3337                 MI = canidates[0] as MethodBase;
3338                 return;
3339             }
3340                 
3341
3342             if (canidatesCount == 0)
3343                 return;
3344
3345             MethodBase match = null;
3346
3347             for (int i = 0; i < canidatesCount; i++)
3348             {
3349                 MethodBase canidate = canidates[i] as MethodBase;
3350
3351                 ParameterInfo[] parameters = canidate.GetParameters();
3352
3353                 if (parameters.Length == argValues.Count)
3354                 {
3355                     bool isMatch = true;
3356                     for (int j = 0; j < parameters.Length; j++)
3357                     {
3358                         Type parameterType = parameters[j].ParameterType;
3359
3360                         if (parameterType.IsByRef)
3361                             parameterType = parameterType.GetElementType();
3362
3363                         if (parameterType != argValues[j].GetType())
3364                         {
3365                             isMatch = false;
3366                             break;
3367                         }
3368
3369                     }
3370                     if (isMatch)
3371                     {
3372                         match = canidate;
3373                         break;
3374                     }
3375                 }
3376             }
3377             if (match == null)
3378                 throw new RemotingException(Environment.GetResourceString("Remoting_AmbiguousMethod"));
3379             MI = match;
3380         }
3381         
3382         //
3383         // GetObjectData -- not implemented
3384         //
3385
3386         /// <internalonly/>
3387         [System.Security.SecurityCritical]  // auto-generated_required
3388         public void GetObjectData(SerializationInfo info, StreamingContext context)
3389         {
3390             throw new NotSupportedException(
3391                 Environment.GetResourceString("NotSupported_Method"));                
3392         }
3393
3394         //
3395         // SetObjectFromSoapData -- parses soap format for serialization data
3396         //
3397
3398         [System.Security.SecurityCritical]  // auto-generated
3399         internal void SetObjectFromSoapData(SerializationInfo info)
3400         {
3401             // resolve method
3402             methodName = info.GetString("__methodName");
3403             ArrayList paramNames = (ArrayList)info.GetValue("__paramNameList", typeof(ArrayList));
3404
3405             Hashtable keyToNamespaceTable = (Hashtable)info.GetValue("__keyToNamespaceTable", typeof(Hashtable));
3406
3407             if (MI == null)
3408             {
3409                 // This is the case where 
3410                 // 1) there is no signature in the header, 
3411                 // 2) there is an overloaded method which can not be resolved by a difference in the number of parameters.
3412                 //
3413                 // The methodbase can be found only if the parameters from soap have type information
3414                 ArrayList argValues = new ArrayList();
3415                 ArrayList argNames = paramNames;
3416                 // SerializationInfoEnumerator siEnum1 = info.GetEnumerator();
3417                 for (int i=0; i<argNames.Count; i++)
3418                 {
3419                     argValues.Add(info.GetValue((String)argNames[i], typeof(Object)));
3420                 }
3421
3422                 //ambiguous member, try to find methodBase using actual argment types (if available)
3423                 RuntimeType t = ResolveType() as RuntimeType;
3424                 if (t == null)
3425                 {
3426                     throw new RemotingException(
3427                         String.Format(
3428                             CultureInfo.CurrentCulture, Environment.GetResourceString(
3429                                 "Remoting_BadType"),
3430                             typeName));
3431                 }
3432
3433                 ResolveOverloadedMethod(t, methodName, argNames, argValues); 
3434
3435                 if (MI == null)
3436                 {   
3437                     throw new RemotingException(
3438                         String.Format(
3439                             CultureInfo.CurrentCulture, Environment.GetResourceString(
3440                                 "Remoting_Message_MethodMissing"),
3441                             methodName,
3442                             typeName));
3443                 }
3444             }
3445             //ResolveMethod();       
3446
3447
3448             //Contract.Assert(null != MI, "null != MI");
3449
3450             // get method parameters and parameter maps
3451             RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
3452             ParameterInfo[] pinfos = methodCache.Parameters;
3453             int[] marshalRequestArgMap = methodCache.MarshalRequestArgMap;
3454             
3455             // check to see if parameters are in-order
3456             Object fUnordered = (null == InternalProperties ? null : InternalProperties["__UnorderedParams"]);
3457
3458             // Create an array for arguments
3459             args = new Object[pinfos.Length];           
3460
3461             //SerializationInfoEnumerator siEnum = info.GetEnumerator();
3462
3463             // Fill up the argument array
3464             if (fUnordered != null &&
3465                 (fUnordered is System.Boolean) && 
3466                 (true == (bool)fUnordered))
3467             {
3468                 String memberName;
3469
3470                 for (int i=0; i<paramNames.Count; i++)
3471                 {
3472                     memberName = (String)paramNames[i];
3473                     Message.DebugOut(
3474                         "MethodCall::PopulateData members[i].Name: " 
3475                         + memberName + " substring:>>" 
3476                         + memberName.Substring(7) + "<<\n");
3477
3478                     int position = -1;
3479                     for (int j=0; j<pinfos.Length; j++)
3480                     {
3481                         if (memberName.Equals(pinfos[j].Name))
3482                         {
3483                             position = pinfos[j].Position;
3484                             break;
3485                         }
3486                     }
3487
3488                     if (position == -1)
3489                     {
3490                         if (!memberName.StartsWith("__param", StringComparison.Ordinal))
3491                         {
3492                             throw new RemotingException(
3493                                 Environment.GetResourceString(
3494                                 "Remoting_Message_BadSerialization"));
3495                         }
3496                         position = Int32.Parse(memberName.Substring(7), CultureInfo.InvariantCulture);
3497                     }
3498                     if (position >= args.Length)
3499                     {
3500                         throw new RemotingException(
3501                             Environment.GetResourceString(
3502                                 "Remoting_Message_BadSerialization"));
3503                     }
3504                     args[position] = Message.SoapCoerceArg(info.GetValue(memberName, typeof(Object)), pinfos[position].ParameterType, keyToNamespaceTable);
3505                 }
3506             }
3507             else
3508             {
3509                 for (int i=0; i<paramNames.Count; i++)
3510                     {
3511                     String memberName = (String)paramNames[i];
3512                         args[marshalRequestArgMap[i]] = 
3513                     Message.SoapCoerceArg(info.GetValue(memberName, typeof(Object)), pinfos[marshalRequestArgMap[i]].ParameterType, keyToNamespaceTable);
3514                 }
3515
3516                 PopulateOutArguments(methodCache);
3517             }
3518         } // SetObjectFromSoapData
3519
3520         [SecurityCritical]
3521         [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
3522         void PopulateOutArguments(RemotingMethodCachedData methodCache)
3523         {
3524             ParameterInfo[] parameterInfos = methodCache.Parameters;
3525             // We need to have a dummy object in the array for out parameters
3526             //   that have value types.
3527             foreach (int outArg in methodCache.OutOnlyArgMap)
3528             {
3529                 Type type = parameterInfos[outArg].ParameterType.GetElementType();
3530                 if (type.IsValueType)
3531                     args[outArg] = Activator.CreateInstance(type, true);
3532             }
3533         }
3534
3535
3536         //
3537         // Init -- constructor helper for for default behavior
3538         //
3539
3540     /// <internalonly/>
3541         public virtual void Init()
3542         {
3543         }
3544
3545         //
3546         // IMethodCallMessage
3547         //
3548
3549     /// <internalonly/>
3550         public int ArgCount
3551         {
3552             [System.Security.SecurityCritical]
3553             get
3554             {
3555                 return(args == null) ? 0 : args.Length;
3556             }
3557         }
3558
3559     /// <internalonly/>
3560         [System.Security.SecurityCritical]
3561         public Object GetArg(int argNum)
3562         {
3563             return args[argNum];
3564         }
3565
3566     /// <internalonly/>
3567         [System.Security.SecurityCritical]  // auto-generated
3568         public String GetArgName(int index)
3569         {
3570             ResolveMethod();
3571         
3572             RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
3573             return methodCache.Parameters[index].Name;
3574         }
3575
3576     /// <internalonly/>
3577         public Object[] Args
3578         {
3579             [System.Security.SecurityCritical]
3580             get
3581             {
3582                 return args;
3583             }
3584         }
3585
3586
3587     /// <internalonly/>
3588         public int InArgCount                        
3589         {
3590             [System.Security.SecurityCritical]
3591             get 
3592             {
3593                 if (argMapper == null) argMapper = new ArgMapper(this, false);
3594                 return argMapper.ArgCount;
3595             }
3596         }
3597
3598     /// <internalonly/>
3599         [System.Security.SecurityCritical]
3600         public Object GetInArg(int argNum)   
3601         {
3602             if (argMapper == null) argMapper = new ArgMapper(this, false);
3603             return argMapper.GetArg(argNum);
3604         }
3605
3606     /// <internalonly/>
3607         [System.Security.SecurityCritical]
3608         public String GetInArgName(int index) 
3609         { 
3610             if (argMapper == null) argMapper = new ArgMapper(this, false);
3611             return argMapper.GetArgName(index);
3612         }
3613     /// <internalonly/>
3614         public Object[] InArgs                       
3615         {
3616             [System.Security.SecurityCritical]
3617             get
3618             {
3619                 if (argMapper == null) argMapper = new ArgMapper(this, false);
3620                 return argMapper.Args;
3621             }
3622         }
3623
3624     /// <internalonly/>
3625         public String MethodName
3626         {
3627             [System.Security.SecurityCritical]
3628             get { return methodName; }
3629         }
3630     /// <internalonly/>
3631         public String TypeName
3632         {
3633             [System.Security.SecurityCritical]
3634             get { return typeName; }
3635         }
3636     /// <internalonly/>
3637         public Object MethodSignature
3638         {
3639             [System.Security.SecurityCritical]  // auto-generated
3640             get
3641             {
3642                 if (methodSignature != null)
3643                     return methodSignature;
3644                 else if (MI != null)
3645                     methodSignature = Message.GenerateMethodSignature(this.MethodBase);
3646                 
3647                 return null;
3648             }
3649         }    
3650
3651     /// <internalonly/>
3652         public MethodBase MethodBase 
3653         {
3654             [System.Security.SecurityCritical]
3655             get
3656             {
3657                 if (MI == null)
3658                     MI = RemotingServices.InternalGetMethodBaseFromMethodMessage(this);
3659                 return MI;
3660             }
3661         }
3662
3663     /// <internalonly/>
3664         public String Uri 
3665         {
3666             [System.Security.SecurityCritical]
3667             get { return uri; }
3668             set { uri = value; }
3669         }
3670
3671     /// <internalonly/>
3672         public bool HasVarArgs
3673         {
3674             [System.Security.SecurityCritical]
3675             get { return fVarArgs; }
3676         }
3677
3678     /// <internalonly/>
3679         public virtual IDictionary Properties
3680         {
3681             [System.Security.SecurityCritical]
3682             get
3683             {
3684                 lock(this) {
3685                     if (InternalProperties == null)
3686                     {
3687                         InternalProperties = new Hashtable();
3688                     }
3689                     if (ExternalProperties == null)
3690                     {
3691                         ExternalProperties = new MCMDictionary(this, InternalProperties);
3692                     }
3693                     return ExternalProperties;
3694                 }
3695             }
3696         }
3697
3698     /// <internalonly/>
3699         public LogicalCallContext LogicalCallContext
3700         {
3701             [System.Security.SecurityCritical]  // auto-generated
3702             get { return GetLogicalCallContext(); }
3703         }
3704
3705         [System.Security.SecurityCritical]  // auto-generated
3706         internal LogicalCallContext GetLogicalCallContext()
3707         {
3708             if (callContext == null)
3709                 callContext = new LogicalCallContext();
3710             return callContext;
3711         }
3712
3713         internal LogicalCallContext SetLogicalCallContext(LogicalCallContext ctx)
3714         {
3715             LogicalCallContext old=callContext;
3716             callContext=ctx;
3717             return old;
3718         }
3719
3720         //
3721         // IInternalMessage
3722         //
3723
3724         /// <internalonly/>
3725         ServerIdentity IInternalMessage.ServerIdentityObject
3726         {
3727             [System.Security.SecurityCritical]
3728             get { return srvID; }
3729             [System.Security.SecurityCritical]
3730             set { srvID = value; }
3731         }
3732
3733         /// <internalonly/>
3734         Identity IInternalMessage.IdentityObject
3735         {
3736             [System.Security.SecurityCritical]
3737             get { return identity; }
3738             [System.Security.SecurityCritical]
3739             set { identity = value; }
3740         }
3741
3742         /// <internalonly/>
3743         [System.Security.SecurityCritical]
3744         void IInternalMessage.SetURI(String val)
3745         {
3746             uri = val;
3747         }
3748         
3749         /// <internalonly/>
3750         [System.Security.SecurityCritical]
3751         void IInternalMessage.SetCallContext(LogicalCallContext newCallContext)
3752         {
3753             callContext = newCallContext;
3754         }
3755
3756         /// <internalonly/>
3757         [System.Security.SecurityCritical]
3758         bool IInternalMessage.HasProperties()
3759         {
3760             return (ExternalProperties != null) || (InternalProperties != null);
3761         }
3762
3763         //
3764         // helper functions
3765         //
3766             
3767         [System.Security.SecurityCritical]  // auto-generated
3768         internal void FillHeaders(Header[] h)
3769         {
3770             FillHeaders(h, false);
3771         }
3772     
3773         [System.Security.SecurityCritical]  // auto-generated
3774         private void FillHeaders(Header[] h, bool bFromHeaderHandler)
3775         {            
3776             if (h == null)
3777                 return;
3778
3779             if (bFromHeaderHandler && fSoap)
3780             {            
3781                 // Handle the case of headers coming off the wire in SOAP.
3782
3783                 // look for message properties
3784                 int co;
3785                 for (co = 0; co < h.Length; co++)
3786                 {
3787                     Header header = h[co];
3788                     if (header.HeaderNamespace == "http://schemas.microsoft.com/clr/soap/messageProperties")
3789                     {
3790                         // add property to the message
3791                         FillHeader(header.Name, header.Value);
3792                     }
3793                     else
3794                     {
3795                         // add header to the message as a header
3796                         String name = LogicalCallContext.GetPropertyKeyForHeader(header);
3797                         FillHeader(name, header);
3798                     }
3799                 }                
3800             }
3801             else
3802             {
3803                 int i;
3804                 for (i=0; i<h.Length; i++)
3805                 {
3806                     FillHeader(h[i].Name, h[i].Value);
3807                 }
3808             }
3809         }
3810
3811         [System.Security.SecurityCritical]  // auto-generated
3812         internal virtual bool FillSpecialHeader(String key, Object value)
3813         {
3814             if (key == null)
3815             {
3816                 //skip
3817             }
3818             else if (key.Equals("__Uri"))
3819             {
3820                 uri = (String) value;
3821             }
3822             else if (key.Equals("__MethodName"))
3823             {
3824                 methodName = (String) value;
3825             }
3826             else if (key.Equals("__MethodSignature"))
3827             {
3828                 methodSignature = (Type[]) value;
3829             }
3830             else if (key.Equals("__TypeName"))
3831             {
3832                 typeName = (String) value;
3833             }
3834             else if (key.Equals("__Args"))
3835             {
3836                 args = (Object[]) value;
3837             }
3838             else if (key.Equals("__CallContext"))
3839             {
3840                 // if the value is a string, then its the LogicalCallId
3841                 if (value is String)
3842                 {
3843                     callContext = new LogicalCallContext();
3844                     callContext.RemotingData.LogicalCallID = (String) value;
3845                 }
3846                 else
3847                     callContext = (LogicalCallContext) value;
3848             }
3849             else
3850             {
3851                 return false;
3852             }
3853             return true;
3854         }
3855         [System.Security.SecurityCritical]  // auto-generated
3856         internal void FillHeader(String key, Object value)
3857         {
3858             Message.DebugOut("MethodCall::FillHeader: key:" + key + "\n");
3859
3860             if (!FillSpecialHeader(key,value))
3861             {
3862                 if (InternalProperties == null)
3863                 {
3864                     InternalProperties = new Hashtable();
3865                 }
3866                 InternalProperties[key] = value;
3867             }
3868
3869         }
3870    
3871         /// <internalonly/>
3872         [System.Security.SecurityCritical]  // auto-generated
3873         public virtual Object HeaderHandler(Header[] h)
3874         {
3875             SerializationMonkey m = (SerializationMonkey) FormatterServices.GetUninitializedObject(typeof(SerializationMonkey));
3876             Header[] newHeaders = null;
3877             if (h != null && h.Length > 0 && h[0].Name == "__methodName")
3878             {
3879                 methodName = (String)h[0].Value;
3880                 if (h.Length > 1)
3881                 {
3882                     newHeaders = new Header[h.Length -1];
3883                     Array.Copy(h, 1, newHeaders, 0, h.Length-1);
3884                 }
3885                 else
3886                     newHeaders = null;
3887             }
3888             else
3889                 newHeaders = h;
3890
3891             FillHeaders(newHeaders, true);
3892             ResolveMethod(false);
3893             m._obj = this;
3894             if (MI != null)
3895             {
3896                 ArgMapper argm = new ArgMapper(MI, false);
3897                 m.fieldNames = argm.ArgNames;
3898                 m.fieldTypes = argm.ArgTypes;
3899             }
3900             return m;
3901         }
3902     }
3903
3904
3905     //+================================================================================
3906     //
3907     // Synopsis:   Message used for deserialization of a construction call
3908     //
3909     //-================================================================================
3910     /// <internalonly/>
3911     [System.Security.SecurityCritical]  // auto-generated_required
3912     [Serializable]
3913     [CLSCompliant(false)]
3914     [System.Runtime.InteropServices.ComVisible(true)]
3915     public class ConstructionCall : MethodCall, IConstructionCallMessage
3916     {
3917
3918         //
3919         // data
3920         //
3921
3922         internal Type         _activationType;
3923         internal String        _activationTypeName;
3924         internal IList        _contextProperties;
3925         internal Object[]     _callSiteActivationAttributes;
3926         internal IActivator   _activator;
3927
3928         /*
3929         [NonSerialized]
3930         internal Object       _fakeThisPtr;     // used for proxyattribute::CI 
3931         */
3932
3933         //
3934         // construction
3935         //
3936
3937     /// <internalonly/>
3938         public ConstructionCall(Header[] headers) : base(headers) {}
3939
3940     /// <internalonly/>
3941         public ConstructionCall(IMessage m) : base(m) {}
3942         internal ConstructionCall(SerializationInfo info, StreamingContext context) : base(info, context) 
3943         {
3944         }
3945
3946 #if false
3947         internal Object GetThisPtr()
3948         {
3949             return _fakeThisPtr;
3950         }
3951         internal void SetThisPtr(Object obj)
3952         {
3953             _fakeThisPtr = obj;
3954         }
3955 #endif
3956
3957         //
3958         //  Function:    FillSpecialHeader
3959         //
3960         //  Synopsis:    this is the only specialization we need to
3961         //               make things go in the right place
3962         //
3963         //
3964         [System.Security.SecurityCritical]
3965         internal override bool FillSpecialHeader(String key, Object value)
3966         {
3967             if (key == null)
3968             {
3969                 //skip
3970             }
3971             else if (key.Equals("__ActivationType"))
3972             {
3973                 Contract.Assert(value==null, "Phoney type in CCM");
3974                 _activationType = null;
3975             }
3976             else if (key.Equals("__ContextProperties"))
3977             {
3978                 _contextProperties = (IList) value;
3979             }
3980             else if (key.Equals("__CallSiteActivationAttributes"))
3981             {
3982                 _callSiteActivationAttributes = (Object[]) value;
3983             }
3984             else if (key.Equals("__Activator"))
3985             {
3986                 _activator = (IActivator) value;
3987             }
3988             else if (key.Equals("__ActivationTypeName"))
3989             {
3990                 _activationTypeName = (String) value;
3991             }
3992             else
3993             {
3994                 return base.FillSpecialHeader(key, value);
3995             }
3996             return true;
3997
3998         }
3999
4000
4001         //
4002         // IConstructionCallMessage
4003         //
4004
4005     /// <internalonly/>
4006         public Object[] CallSiteActivationAttributes
4007         {
4008             [System.Security.SecurityCritical]
4009             get
4010             {
4011                 return _callSiteActivationAttributes;
4012             }
4013
4014         }
4015
4016     /// <internalonly/>
4017         public Type ActivationType
4018         {
4019             [System.Security.SecurityCritical]
4020             get
4021             {
4022                 if ((_activationType == null) && (_activationTypeName != null))
4023                     _activationType = RemotingServices.InternalGetTypeFromQualifiedTypeName(_activationTypeName, false);
4024
4025                 return _activationType;
4026             }
4027         }
4028
4029     /// <internalonly/>
4030         public String ActivationTypeName
4031         {
4032             [System.Security.SecurityCritical]
4033             get
4034             {
4035                 return _activationTypeName;
4036             }
4037         }
4038
4039     /// <internalonly/>
4040         public IList ContextProperties
4041         {
4042             [System.Security.SecurityCritical]
4043             get
4044             {
4045                 if (_contextProperties == null)
4046                 {
4047                     _contextProperties = new ArrayList();
4048                 }
4049                 return _contextProperties;
4050             }
4051         }
4052
4053     /// <internalonly/>
4054         public override IDictionary Properties
4055         {
4056             [System.Security.SecurityCritical]
4057             get
4058             {
4059                 lock(this) 
4060                 {
4061                     if (InternalProperties == null)
4062                     {
4063                         InternalProperties = new Hashtable();
4064                     }
4065                     if (ExternalProperties == null)
4066                     {
4067                         ExternalProperties = new CCMDictionary(this, InternalProperties);
4068                     }
4069                     return ExternalProperties;
4070                 }
4071             }
4072         }
4073         
4074
4075         // IConstructionCallMessage::Activator
4076     /// <internalonly/>
4077         public IActivator Activator
4078         {
4079             [System.Security.SecurityCritical]
4080             get { return _activator; }
4081             [System.Security.SecurityCritical]
4082             set { _activator = value; }
4083         }
4084         
4085     }
4086     //+================================================================================
4087     //
4088     // Synopsis:   Message used for deserialization of a method response
4089     //
4090     //-================================================================================
4091     /// <internalonly/>
4092     [System.Security.SecurityCritical]  // auto-generated_required
4093     [Serializable]
4094     [CLSCompliant(false)]
4095     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
4096     [System.Runtime.InteropServices.ComVisible(true)]
4097     public class MethodResponse : IMethodReturnMessage, ISerializable, ISerializationRootObject, IInternalMessage
4098     {
4099         private MethodBase MI;
4100         private String     methodName;
4101         private Type[]     methodSignature;
4102         private String     uri;
4103         private String     typeName;
4104         private Object     retVal;
4105         private Exception  fault;
4106         private Object[]  outArgs;
4107         private LogicalCallContext callContext;
4108     /// <internalonly/>
4109         protected IDictionary InternalProperties;
4110     /// <internalonly/>
4111         protected IDictionary ExternalProperties;
4112
4113         private int       argCount;
4114         private bool      fSoap;
4115         private ArgMapper argMapper;
4116         private RemotingMethodCachedData _methodCache;
4117
4118         // Constructor -- this constructor is called only in the SOAP Scenario
4119
4120
4121     /// <internalonly/>
4122         [System.Security.SecurityCritical]  // auto-generated
4123         public MethodResponse(Header[] h1, IMethodCallMessage mcm)
4124         {
4125             if (mcm == null)
4126                 throw new ArgumentNullException("mcm");
4127             Contract.EndContractBlock();
4128
4129             Message msg = mcm as Message;
4130             if (null != msg)
4131             {
4132                 MI = (MethodBase)msg.GetMethodBase();
4133             }
4134             else
4135             {
4136                 MI = (MethodBase)mcm.MethodBase;
4137             }
4138             if (MI == null)
4139             {
4140                 throw new RemotingException(
4141                     String.Format(
4142                         CultureInfo.CurrentCulture, Environment.GetResourceString(
4143                             "Remoting_Message_MethodMissing"),
4144                         mcm.MethodName,
4145                         mcm.TypeName));
4146             }
4147             
4148             _methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
4149             
4150             argCount = _methodCache.Parameters.Length;
4151             fSoap = true;
4152             FillHeaders(h1);
4153         }
4154
4155
4156         [System.Security.SecurityCritical]  // auto-generated
4157         internal MethodResponse(IMethodCallMessage msg,
4158                                 SmuggledMethodReturnMessage smuggledMrm,
4159                                 ArrayList deserializedArgs)
4160         {
4161             MI = (MethodBase)msg.MethodBase;
4162             _methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
4163             
4164             methodName = msg.MethodName;
4165             uri = msg.Uri;
4166             typeName = msg.TypeName;
4167
4168             if (_methodCache.IsOverloaded())
4169                 methodSignature = (Type[])msg.MethodSignature;
4170            
4171             retVal = smuggledMrm.GetReturnValue(deserializedArgs);
4172             outArgs = smuggledMrm.GetArgs(deserializedArgs);
4173             fault = smuggledMrm.GetException(deserializedArgs);
4174
4175             callContext = smuggledMrm.GetCallContext(deserializedArgs);
4176
4177             if (smuggledMrm.MessagePropertyCount > 0)
4178                 smuggledMrm.PopulateMessageProperties(Properties, deserializedArgs);           
4179             
4180             argCount = _methodCache.Parameters.Length;
4181             fSoap = false;
4182         }
4183
4184         [System.Security.SecurityCritical]  // auto-generated
4185         internal MethodResponse(IMethodCallMessage msg,
4186                                 Object handlerObject,
4187                                 BinaryMethodReturnMessage smuggledMrm)
4188         {
4189
4190             if (msg != null)
4191             {
4192                 MI = (MethodBase)msg.MethodBase;
4193                 _methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
4194             
4195                 methodName = msg.MethodName;
4196                 uri = msg.Uri;
4197                 typeName = msg.TypeName;
4198
4199                 if (_methodCache.IsOverloaded())
4200                     methodSignature = (Type[])msg.MethodSignature;
4201
4202                 argCount = _methodCache.Parameters.Length;
4203
4204             }
4205            
4206             retVal = smuggledMrm.ReturnValue;
4207             outArgs = smuggledMrm.Args;
4208             fault = smuggledMrm.Exception;
4209
4210             callContext = smuggledMrm.LogicalCallContext;
4211
4212             if (smuggledMrm.HasProperties)
4213                 smuggledMrm.PopulateMessageProperties(Properties);           
4214             
4215             fSoap = false;
4216         }
4217
4218
4219
4220         //
4221         // SetObjectData -- this can be called with the object in two possible states. 1. the object
4222         // is servicing a SOAP response in which it will have been half initialized by the constructor,
4223         // or 2. the object is uninitailized and serialization is passing in the contents.
4224         //
4225         [System.Security.SecurityCritical]  // auto-generated
4226         internal MethodResponse(SerializationInfo info, StreamingContext context) 
4227         {
4228             if (info == null)
4229                 throw new ArgumentNullException("info");
4230             Contract.EndContractBlock();
4231             SetObjectData(info, context);
4232         }
4233
4234
4235     /// <internalonly/>
4236         [System.Security.SecurityCritical]  // auto-generated
4237         public virtual Object HeaderHandler(Header[] h)
4238         {
4239             SerializationMonkey m = (SerializationMonkey) FormatterServices.GetUninitializedObject(typeof(SerializationMonkey));
4240
4241             Header[] newHeaders = null;
4242             if (h != null && h.Length > 0 && h[0].Name == "__methodName")
4243             {
4244                 if (h.Length > 1)
4245                 {
4246                     newHeaders = new Header[h.Length -1];
4247                     Array.Copy(h, 1, newHeaders, 0, h.Length-1);
4248                 }
4249                 else
4250                     newHeaders = null;
4251             }
4252             else
4253                 newHeaders = h;
4254
4255             Type retType = null;
4256             MethodInfo mi = MI as MethodInfo;
4257             if (mi != null)
4258             {
4259                 retType = mi.ReturnType; 
4260             }
4261
4262             ParameterInfo[] pinfos = _methodCache.Parameters;
4263
4264             // Calculate length
4265             int outParamsCount = _methodCache.MarshalResponseArgMap.Length;
4266             if (!((retType == null) || (retType == typeof(void))))
4267                 outParamsCount++;
4268
4269             Type[] paramTypes = new Type[outParamsCount];
4270             String[] paramNames = new String[outParamsCount];
4271             int paramTypesIndex = 0;
4272             if (!((retType == null) || (retType == typeof(void))))
4273             {
4274                 paramTypes[paramTypesIndex++] = retType;
4275             }
4276
4277             foreach (int i in _methodCache.MarshalResponseArgMap)
4278             {
4279                 paramNames[paramTypesIndex] = pinfos[i].Name;
4280                 if (pinfos[i].ParameterType.IsByRef)
4281                     paramTypes[paramTypesIndex++] = pinfos[i].ParameterType.GetElementType();
4282                 else
4283                     paramTypes[paramTypesIndex++] = pinfos[i].ParameterType;
4284             }
4285
4286             ((IFieldInfo)m).FieldTypes = paramTypes;
4287             ((IFieldInfo)m).FieldNames = paramNames;
4288             FillHeaders(newHeaders, true);
4289             m._obj = this;
4290             return m;
4291         }
4292
4293         //
4294         // ISerializationRootObject
4295         //
4296     /// <internalonly/>
4297         [System.Security.SecurityCritical]  // auto-generated
4298         public void RootSetObjectData(SerializationInfo info, StreamingContext ctx)
4299         {
4300             SetObjectData(info, ctx);
4301         }
4302
4303         [System.Security.SecurityCritical]  // auto-generated
4304         internal void SetObjectData(SerializationInfo info, StreamingContext ctx)
4305         {
4306             if (info == null)
4307                 throw new ArgumentNullException("info");
4308             Contract.EndContractBlock();
4309
4310             if (fSoap)
4311             {
4312                 SetObjectFromSoapData(info);
4313             }
4314             else
4315             {
4316                 SerializationInfoEnumerator e = info.GetEnumerator();
4317                 bool ret = false;
4318                 bool excep = false;
4319
4320                 while (e.MoveNext())
4321                 {
4322                     if (e.Name.Equals("__return"))
4323                     {
4324                         ret = true;
4325                         break;
4326                     }
4327                     if (e.Name.Equals("__fault"))
4328                     {
4329                         excep = true;
4330                         fault = (Exception)e.Value;
4331                         break;
4332                     }
4333
4334                     FillHeader(e.Name, e.Value);
4335                 }
4336                 if ((excep) && (ret))
4337                 {
4338                     throw new RemotingException(
4339                         Environment.GetResourceString(
4340                             "Remoting_Message_BadSerialization"));
4341                 }
4342             }
4343         }
4344         //
4345         // ISerializable
4346         //
4347
4348         //
4349         // GetObjectData -- not implemented
4350         //
4351
4352         /// <internalonly/>
4353         [System.Security.SecurityCritical]  // auto-generated_required
4354         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
4355         {
4356             throw new NotSupportedException(
4357                 Environment.GetResourceString("NotSupported_Method"));                
4358         }
4359
4360         //
4361         // SetObjectFromSoapData -- assumes SOAP format and populates the arguments array
4362         //
4363
4364         internal void SetObjectFromSoapData(SerializationInfo info)
4365         {
4366             //SerializationInfoEnumerator e = info.GetEnumerator(); 
4367
4368             Hashtable keyToNamespaceTable = (Hashtable)info.GetValue("__keyToNamespaceTable", typeof(Hashtable));
4369             ArrayList paramNames = (ArrayList)info.GetValue("__paramNameList", typeof(ArrayList));
4370             SoapFault soapFault = (SoapFault)info.GetValue("__fault", typeof(SoapFault));
4371
4372             if (soapFault != null)
4373                     {
4374                 ServerFault serverFault = soapFault.Detail as ServerFault;
4375                 if (null != serverFault)
4376                 {
4377                     // Server Fault information
4378                     if (serverFault.Exception != null)
4379                         fault = serverFault.Exception;
4380                     else
4381                     {
4382                         Type exceptionType = Type.GetType(serverFault.ExceptionType, false, false);
4383                         if (exceptionType == null)
4384                         {
4385                             // Exception type cannot be resolved, use a ServerException
4386                             StringBuilder sb = new StringBuilder();
4387                             sb.Append("\nException Type: ");
4388                             sb.Append(serverFault.ExceptionType);
4389                             sb.Append("\n");
4390                             sb.Append("Exception Message: ");
4391                             sb.Append(serverFault.ExceptionMessage);
4392                             sb.Append("\n");
4393                             sb.Append(serverFault.StackTrace);
4394                             fault = new ServerException(sb.ToString());
4395                         }
4396                         else 
4397                         {
4398                             // Exception type can be resolved, throw the exception
4399                             Object[] args = {serverFault.ExceptionMessage};
4400                             fault = (Exception)Activator.CreateInstance(
4401                                                     exceptionType, 
4402                                                     BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, 
4403                                                     null, 
4404                                                     args, 
4405                                                     null, 
4406                                                     null);
4407                         }
4408                     }
4409                 }
4410                 else if ((soapFault.Detail != null) && (soapFault.Detail.GetType() == typeof(String)) && (!(((String)soapFault.Detail).Length == 0)))
4411                 {
4412                     fault = new ServerException((String)soapFault.Detail);
4413                 }
4414                 else
4415                 {
4416                     fault = new ServerException(soapFault.FaultString);
4417                 }
4418
4419                 return;
4420             }
4421
4422             MethodInfo mi = MI as MethodInfo;
4423             int paramNameIndex = 0;
4424             if (mi != null)
4425             {
4426                 Type retType = mi.ReturnType;
4427                 if (retType != typeof(void))
4428                 {
4429                     paramNameIndex++;
4430                     Object returnValue = info.GetValue((String)paramNames[0], typeof(Object));
4431                     if (returnValue is String)
4432                         retVal = Message.SoapCoerceArg(returnValue, retType, keyToNamespaceTable);
4433                     else
4434                         retVal = returnValue;
4435                 }
4436             }
4437
4438             // populate the args array
4439             ParameterInfo[] pinfos = _methodCache.Parameters;
4440
4441             Object fUnordered = (InternalProperties == null) ? null : InternalProperties["__UnorderedParams"];
4442             if (fUnordered != null &&
4443                 (fUnordered is System.Boolean) && 
4444                 (true == (bool)fUnordered))
4445             {
4446                 // Unordered
4447                 for (int i=paramNameIndex; i<paramNames.Count; i++)
4448                 {
4449                     String memberName = (String)paramNames[i];
4450
4451                     // check for the parameter name
4452
4453                     int position = -1;
4454                     for (int j=0; j<pinfos.Length; j++)
4455                     {
4456                         if (memberName.Equals(pinfos[j].Name))
4457                         {
4458                             position = pinfos[j].Position;
4459                         }
4460                     }
4461
4462                     // no name so check for well known name
4463
4464                     if (position == -1)
4465                     {
4466                         if (!memberName.StartsWith("__param", StringComparison.Ordinal))
4467                         {
4468                             throw new RemotingException(
4469                                 Environment.GetResourceString(
4470                                     "Remoting_Message_BadSerialization"));
4471                         }
4472                         position = Int32.Parse(memberName.Substring(7), CultureInfo.InvariantCulture);
4473                     }
4474
4475                     // if still not resolved then throw
4476
4477                     if (position >= argCount)
4478                     {
4479                         throw new RemotingException(
4480                             Environment.GetResourceString(
4481                                 "Remoting_Message_BadSerialization"));
4482                     }
4483
4484                     // store the arg in the parameter array
4485
4486                     if (outArgs == null)
4487                     {
4488                         outArgs = new Object[argCount];
4489                     }
4490                     outArgs[position]= Message.SoapCoerceArg(info.GetValue(memberName, typeof(Object)), pinfos[position].ParameterType, keyToNamespaceTable);
4491                 }
4492             }
4493             else
4494             {                
4495                 // ordered
4496                 if (argMapper == null) argMapper = new ArgMapper(this, true);
4497                 for (int j=paramNameIndex; j<paramNames.Count; j++)
4498                 {
4499                     String memberName = (String)paramNames[j];
4500                     if (outArgs == null)
4501                     {
4502                         outArgs = new Object[argCount];
4503                     }
4504
4505                     int position = argMapper.Map[j-paramNameIndex];
4506                     outArgs[position] = Message.SoapCoerceArg(info.GetValue(memberName, typeof(Object)), pinfos[position].ParameterType, keyToNamespaceTable);
4507                 }
4508             }
4509         } // SetObjectFromSoapData
4510
4511
4512
4513         [System.Security.SecurityCritical]  // auto-generated
4514         internal LogicalCallContext GetLogicalCallContext()
4515         {
4516             if (callContext == null)
4517                 callContext = new LogicalCallContext();
4518             return callContext;
4519         }
4520
4521         internal LogicalCallContext SetLogicalCallContext(LogicalCallContext ctx)
4522         {
4523             LogicalCallContext old=callContext;
4524             callContext=ctx;
4525             return old;
4526         }
4527
4528         //
4529         // IMethodReturnMessage
4530         //
4531
4532         /// <internalonly/>
4533         public String Uri
4534         {
4535             [System.Security.SecurityCritical]
4536             get { return uri; }
4537             set { uri = value; }
4538         }
4539         /// <internalonly/>
4540         public String MethodName
4541         {
4542             [System.Security.SecurityCritical]
4543             get { return methodName; }
4544         }
4545         /// <internalonly/>
4546         public String TypeName
4547         {
4548             [System.Security.SecurityCritical]
4549             get { return typeName; }
4550         }
4551         /// <internalonly/>
4552         public Object MethodSignature
4553         {
4554             [System.Security.SecurityCritical]
4555             get { return methodSignature; }
4556         }
4557         /// <internalonly/>
4558         public MethodBase MethodBase
4559         {
4560             [System.Security.SecurityCritical]
4561             get { return MI; }
4562         }
4563
4564         
4565         /// <internalonly/>
4566         public bool   HasVarArgs                      
4567         {
4568             [System.Security.SecurityCritical]
4569             get
4570             {
4571                 // Var args nyi..
4572                 return false;
4573             }
4574         }
4575
4576     /// <internalonly/>
4577         public int ArgCount
4578         {
4579             [System.Security.SecurityCritical]
4580             get 
4581             {
4582                 if (outArgs == null)
4583                     return 0;
4584                 else                
4585                     return outArgs.Length;
4586             }
4587         }
4588     /// <internalonly/>
4589         [System.Security.SecurityCritical]
4590         public Object GetArg(int argNum) { return outArgs[argNum]; }
4591     /// <internalonly/>
4592         [System.Security.SecurityCritical]  // auto-generated
4593         public String GetArgName(int index)           
4594         {
4595             if (MI != null)
4596             {
4597                 RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(MI);
4598                 ParameterInfo[] paramInfo = methodCache.Parameters;
4599                 if (index < 0 || index >= paramInfo.Length)
4600                     throw new ArgumentOutOfRangeException("index");
4601                 
4602                 return methodCache.Parameters[index].Name;
4603             }
4604             else
4605                 return "__param" + index;
4606         }
4607     /// <internalonly/>
4608         public Object[] Args
4609         {
4610             [System.Security.SecurityCritical]
4611             get { return outArgs; }
4612         }
4613
4614     /// <internalonly/>
4615         public int OutArgCount                        
4616         {
4617             [System.Security.SecurityCritical]
4618             get 
4619             {
4620                 if (argMapper == null) argMapper = new ArgMapper(this, true);
4621                 return argMapper.ArgCount;
4622             }
4623         }
4624
4625     /// <internalonly/>
4626         [System.Security.SecurityCritical]
4627         public Object GetOutArg(int argNum)   
4628         {   
4629             if (argMapper == null) argMapper = new ArgMapper(this, true);
4630             return argMapper.GetArg(argNum);
4631         }
4632
4633     /// <internalonly/>
4634         [System.Security.SecurityCritical]
4635         public String GetOutArgName(int index) 
4636         { 
4637             if (argMapper == null) argMapper = new ArgMapper(this, true);
4638             return argMapper.GetArgName(index);
4639         }
4640     /// <internalonly/>
4641         public Object[] OutArgs                       
4642         {
4643             [System.Security.SecurityCritical]
4644             get
4645             {
4646                 if (argMapper == null) argMapper = new ArgMapper(this, true);
4647                 return argMapper.Args;
4648             }
4649         }
4650
4651     /// <internalonly/>
4652         public Exception Exception
4653         {
4654             [System.Security.SecurityCritical]
4655             get { return fault; }
4656         }
4657     /// <internalonly/>
4658         public Object ReturnValue
4659         {
4660             [System.Security.SecurityCritical]
4661             get { return retVal; }
4662         }
4663
4664
4665     /// <internalonly/>
4666         public virtual IDictionary Properties
4667         {
4668             [System.Security.SecurityCritical]
4669             get
4670             {
4671                 lock(this)
4672                 {
4673                     if (InternalProperties == null)
4674                     {
4675                         InternalProperties = new Hashtable();
4676                     }
4677                     if (ExternalProperties == null)
4678                     {
4679                         ExternalProperties = new MRMDictionary(this, InternalProperties);
4680                     }
4681                     return ExternalProperties;
4682                 }
4683             }
4684         }
4685
4686     /// <internalonly/>
4687         public LogicalCallContext LogicalCallContext
4688         {
4689             [System.Security.SecurityCritical]  // auto-generated
4690             get { return GetLogicalCallContext();}
4691         }
4692
4693         //
4694         // helpers
4695         //
4696         [System.Security.SecurityCritical]  // auto-generated
4697         internal void FillHeaders(Header[] h)
4698         {
4699             FillHeaders(h, false);
4700         } // FillHeaders
4701
4702         
4703         [System.Security.SecurityCritical]  // auto-generated
4704         private void FillHeaders(Header[] h, bool bFromHeaderHandler)
4705         {
4706             if (h == null)
4707                 return;
4708         
4709             if (bFromHeaderHandler && fSoap)
4710             {            
4711                 // Handle the case of headers coming off the wire in SOAP.
4712
4713                 // look for message properties
4714                 int co;
4715                 for (co = 0; co < h.Length; co++)
4716                 {
4717                     Header header = h[co];
4718                     if (header.HeaderNamespace == "http://schemas.microsoft.com/clr/soap/messageProperties")
4719                     {
4720                         // add property to the message
4721                         FillHeader(header.Name, header.Value);
4722                     }
4723                     else
4724                     {
4725                         // add header to the message as a header
4726                         String name = LogicalCallContext.GetPropertyKeyForHeader(header);
4727                         FillHeader(name, header);
4728                     }
4729                 }
4730             }
4731             else
4732             {        
4733                 for (int i=0; i<h.Length; i++)
4734                 {
4735                     FillHeader(h[i].Name, h[i].Value);
4736                 }
4737             }
4738         } // FillHeaders
4739         
4740
4741         [System.Security.SecurityCritical]  // auto-generated
4742         internal void FillHeader(String name, Object value)
4743         {
4744             Message.DebugOut("MethodCall::FillHeaders: name: " + (name == null ? "NULL" : name) + "\n");
4745             Message.DebugOut("MethodCall::FillHeaders: Value.GetClass: " + (value == null ? "NULL" : value.GetType().FullName) + "\n");
4746             Message.DebugOut("MethodCall::FillHeaders: Value.ToString: " + (value == null ? "NULL" : value.ToString()) + "\n");
4747
4748             if (name.Equals("__MethodName"))
4749             {
4750                 methodName = (String) value;
4751             }
4752             else if (name.Equals("__Uri"))
4753             {
4754                 uri = (String) value;
4755             }
4756             else if (name.Equals("__MethodSignature"))
4757             {
4758                 methodSignature = (Type[]) value;
4759             }            
4760             else if (name.Equals("__TypeName"))
4761             {
4762                 typeName = (String) value;
4763             }
4764             else if (name.Equals("__OutArgs"))
4765             {
4766                 outArgs = (Object[]) value;
4767             }
4768             else if (name.Equals("__CallContext"))
4769             {
4770                 // if the value is a string, then its the LogicalCallId
4771                 if (value is String)
4772                 {
4773                     callContext = new LogicalCallContext();
4774                     callContext.RemotingData.LogicalCallID = (String) value;
4775                 }
4776                 else
4777                     callContext = (LogicalCallContext) value;
4778             }
4779             else if (name.Equals("__Return"))
4780             {
4781                 retVal = value;
4782             }
4783             else
4784             {
4785                 if (InternalProperties == null)
4786                 {
4787                     InternalProperties = new Hashtable();
4788                 }
4789                 InternalProperties[name] = value;
4790             }
4791         }
4792
4793         //
4794         // IInternalMessage
4795         //
4796
4797         /// <internalonly/>
4798         ServerIdentity IInternalMessage.ServerIdentityObject
4799         {
4800             [System.Security.SecurityCritical]
4801             get { return null; }
4802             [System.Security.SecurityCritical]
4803             set { }
4804         }
4805
4806         /// <internalonly/>
4807         Identity IInternalMessage.IdentityObject
4808         {
4809             [System.Security.SecurityCritical]
4810             get { return null; }
4811             [System.Security.SecurityCritical]
4812             set { }
4813         }
4814
4815         /// <internalonly/>
4816         [System.Security.SecurityCritical]
4817         void IInternalMessage.SetURI(String val)
4818         {
4819             uri = val;
4820         }
4821         
4822         /// <internalonly/>
4823
4824         [System.Security.SecurityCritical]
4825         void IInternalMessage.SetCallContext(LogicalCallContext newCallContext)
4826         {
4827             callContext = newCallContext;
4828         }
4829
4830         /// <internalonly/>
4831         [System.Security.SecurityCritical]
4832         bool IInternalMessage.HasProperties()
4833         {
4834             return (ExternalProperties != null) || (InternalProperties != null);
4835         }
4836         
4837     } // class MethodResponse
4838
4839     internal interface ISerializationRootObject
4840     {
4841         [System.Security.SecurityCritical]  // auto-generated_required
4842         void RootSetObjectData(SerializationInfo info, StreamingContext ctx);
4843     }
4844
4845     [Serializable]
4846     internal class SerializationMonkey : ISerializable, IFieldInfo
4847     {
4848         internal ISerializationRootObject       _obj;
4849         internal String[] fieldNames = null;
4850         internal Type[] fieldTypes = null;
4851
4852         [System.Security.SecurityCritical]  // auto-generated
4853         internal SerializationMonkey(SerializationInfo info, StreamingContext ctx)
4854         {
4855             Contract.Assert(_obj != null, "SerializationMonkey's _obj field should have been initialized elsewhere with a special hack.");
4856             _obj.RootSetObjectData(info, ctx);
4857         }
4858
4859         [System.Security.SecurityCritical]  // auto-generated_required
4860         public void GetObjectData(SerializationInfo info, StreamingContext context)
4861         {
4862             throw new NotSupportedException(
4863                 Environment.GetResourceString(
4864                     "NotSupported_Method"));
4865         }
4866
4867         public String[] FieldNames
4868         {
4869             [System.Security.SecurityCritical]  // auto-generated
4870             get {return fieldNames;}
4871             [System.Security.SecurityCritical]  // auto-generated
4872             set {fieldNames = value;}
4873         }
4874
4875         public Type[] FieldTypes
4876         {
4877             [System.Security.SecurityCritical]  // auto-generated
4878             get {return fieldTypes;}
4879             [System.Security.SecurityCritical]  // auto-generated
4880             set {fieldTypes = value;}
4881         }
4882
4883                 
4884     }
4885
4886     //+================================================================================
4887     //
4888     // Synopsis:   Message used for deserialization of a method construction
4889     //
4890     //-================================================================================
4891     /// <internalonly/>
4892     [System.Security.SecurityCritical]  // auto-generated_required
4893     [Serializable]
4894     [CLSCompliant(false)]
4895     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
4896     [System.Runtime.InteropServices.ComVisible(true)]
4897     public class ConstructionResponse : MethodResponse, IConstructionReturnMessage
4898     {
4899     /// <internalonly/>
4900         public ConstructionResponse(Header[] h, IMethodCallMessage mcm) : base(h, mcm) {}
4901         internal ConstructionResponse(SerializationInfo info, StreamingContext context) : base (info, context) {}
4902
4903     /// <internalonly/>
4904         public override IDictionary Properties
4905         {
4906             [System.Security.SecurityCritical]
4907             get
4908             {
4909                 lock(this)
4910                 {
4911                     if (InternalProperties == null)
4912                     {
4913                         InternalProperties = new Hashtable();
4914                     }
4915                     if (ExternalProperties == null)
4916                     {
4917                         ExternalProperties = new CRMDictionary(this, InternalProperties);
4918                     }
4919                     return ExternalProperties;
4920                 }
4921             }
4922         }
4923     }
4924
4925     // This is a special message used for helping someone make a transition
4926     // into a Context (or AppDomain) and back out. This is intended as a replacement
4927     // of the callBack object mechanism which is expensive since it involves
4928     // 2 round trips (one to get the callback object) and one to make the call
4929     // on it. Furthermore the callBack object scheme in cross domain cases would
4930     // involve unnecessary marshal/unmarshal-s of vari'ous callBack objects.
4931     //
4932     // We implement IInternalMessage and do our own magic when various
4933     // infrastructure sinks ask for serverID etc. Bottomline intent is to make
4934     // everything look like a complete remote call with all the entailing transitions
4935     // and executing some delegate in another context (or appdomain) without
4936     // actually having a proxy to call "Invoke" on or a server object to "Dispatch"
4937     // on.
4938     [Serializable]
4939     internal class TransitionCall
4940         :IMessage, IInternalMessage, IMessageSink, ISerializable
4941     {
4942         IDictionary _props;             // For IMessage::GetDictionary
4943         IntPtr _sourceCtxID;            // Where the request emerged
4944         IntPtr _targetCtxID;            // Where the request should execute
4945         int _targetDomainID;            // Non zero if we are going to another domain
4946         ServerIdentity _srvID;          // Created serverID
4947         Identity _ID;                   // Created ID
4948
4949         CrossContextDelegate _delegate; // The delegate to execute for the cross context case
4950         IntPtr _eeData; // Used for DoCallbackInEE
4951
4952         // The _delegate should really be on an agile object otherwise
4953         // the whole point of doing a callBack is moot. However, even if it
4954         // is not, remoting and serialization together will ensure that
4955         // everything happens as expected and there is no smuggling.
4956
4957         [System.Security.SecurityCritical]  // auto-generated
4958         internal TransitionCall(
4959             IntPtr targetCtxID, 
4960             CrossContextDelegate deleg)
4961         {
4962             Contract.Assert(targetCtxID!=IntPtr.Zero, "bad target ctx for call back");
4963             _sourceCtxID = Thread.CurrentContext.InternalContextID;
4964             _targetCtxID = targetCtxID;
4965             _delegate = deleg;
4966             _targetDomainID = 0;
4967             _eeData = IntPtr.Zero;
4968
4969             // We are going to another context in the same app domain
4970             _srvID = new ServerIdentity(
4971                 null, 
4972                 Thread.GetContextInternal(_targetCtxID));
4973             _ID = _srvID;
4974             _ID.RaceSetChannelSink(CrossContextChannel.MessageSink);
4975             _srvID.RaceSetServerObjectChain(this);
4976                 
4977             //DBG Console.WriteLine("### TransitionCall ctor: " + Int32.Format(_sourceCtxID,"x") + ":" + Int32.Format(_targetCtxID,"x"));
4978         } // TransitionCall
4979
4980
4981         // This constructor should be used for cross appdomain case.
4982         [System.Security.SecurityCritical]  // auto-generated
4983         internal TransitionCall(IntPtr targetCtxID, IntPtr eeData, int targetDomainID)
4984             {
4985             Contract.Assert(targetCtxID != IntPtr.Zero, "bad target ctx for call back");
4986             Contract.Assert(targetDomainID !=0, "bad target ctx for call back");
4987
4988             _sourceCtxID = Thread.CurrentContext.InternalContextID;
4989             _targetCtxID = targetCtxID;
4990             _delegate = null;
4991             _targetDomainID = targetDomainID;
4992             _eeData = eeData;
4993             
4994
4995             // In the cross domain case, the client side just has a base Identity
4996             // and the server domain has the Server identity. We fault in the latter
4997             // when requested later.
4998
4999             // We are going to a context in another app domain
5000             _srvID = null;
5001             _ID = new Identity("TransitionCallURI", null);
5002
5003                 // Create the data needed for the channel sink creation
5004             CrossAppDomainData data = 
5005                 new CrossAppDomainData(_targetCtxID,
5006                     _targetDomainID,
5007                     Identity.ProcessGuid);
5008             String unUsed;
5009             IMessageSink channelSink =
5010             CrossAppDomainChannel.AppDomainChannel.CreateMessageSink(
5011                 null, //uri
5012                 data, //channelData
5013                 out unUsed);//out objURI
5014
5015             Contract.Assert(channelSink != null, "X-domain transition failure");
5016             _ID.RaceSetChannelSink(channelSink);
5017         } // TransitionCall
5018         
5019
5020         internal TransitionCall(SerializationInfo info, StreamingContext context) 
5021         {
5022             if (info == null || (context.State != StreamingContextStates.CrossAppDomain))
5023             {
5024                 throw new ArgumentNullException("info");
5025             }
5026             Contract.EndContractBlock();
5027             
5028             _props = (IDictionary)info.GetValue("props", typeof(IDictionary));
5029             _delegate = (CrossContextDelegate) info.GetValue("delegate", typeof(CrossContextDelegate));            
5030             _sourceCtxID  = (IntPtr) info.GetValue("sourceCtxID", typeof(IntPtr));
5031             _targetCtxID  = (IntPtr) info.GetValue("targetCtxID", typeof(IntPtr));
5032             _eeData = (IntPtr) info.GetValue("eeData", typeof(IntPtr));
5033             
5034             _targetDomainID = info.GetInt32("targetDomainID");
5035             Contract.Assert(_targetDomainID != 0, "target domain should be non-zero");
5036         }
5037
5038         //IMessage::GetProperties
5039         public IDictionary Properties
5040         {
5041             [System.Security.SecurityCritical]  // auto-generated
5042             get
5043             {
5044                 if (_props == null)
5045                 {
5046                     lock(this)
5047                     {
5048                         if (_props == null)
5049                         {
5050                             _props = new Hashtable();
5051                         }
5052                     }
5053                 }
5054                 return _props;
5055             }
5056         }
5057
5058         //IInternalMessage::ServerIdentityObject
5059         ServerIdentity IInternalMessage.ServerIdentityObject
5060         {
5061             [System.Security.SecurityCritical]
5062             get
5063             {
5064                 if ( (_targetDomainID!=0) && _srvID == null)
5065                 {
5066                     // We should now be in the target context! (We should not be
5067                     // attempting to get the server identity in the client domain).
5068                     Contract.Assert(Thread.CurrentContext.InternalContextID
5069                                         == _targetCtxID,
5070                                 "ServerID requested in wrong appDomain!");
5071                     lock(this)
5072                     {
5073                         /*DBG Console.WriteLine("### Get SrvID: thrdCtxID== " + Int32.Format(Thread.CurrentContext.InternalContextID,"x"));
5074                         Console.WriteLine("### Get SrvID: _targetCtxID" + Int32.Format(_targetCtxID,"x")); DBG*/
5075
5076                         // NOTE: if we don't have a managed context object 
5077                         // corresponding to the targetCtxID ... we just use 
5078                         // the default context for the AppDomain. This could 
5079                         // be a problem if by some means we could have
5080                         // a non-default target VM context without a managed
5081                         // context object associated with it.
5082                         Context ctx = Thread.GetContextInternal(_targetCtxID);                        
5083                         if (ctx == null)
5084                         {
5085                             ctx = Context.DefaultContext;                            
5086                         }
5087                         Contract.Assert(ctx != null, "Null target context unexpected!");
5088                         _srvID = new ServerIdentity(
5089                                     null,
5090                                     Thread.GetContextInternal(_targetCtxID));
5091
5092                         _srvID.RaceSetServerObjectChain(this);
5093                     }
5094                 }
5095                 return _srvID;
5096             }
5097             [System.Security.SecurityCritical]
5098             set
5099             {
5100                 throw new RemotingException(
5101                     Environment.GetResourceString(
5102                         "Remoting_Default"));
5103             }
5104         }
5105
5106         //IInternalMessage::IdentityObject
5107         Identity IInternalMessage.IdentityObject
5108         {
5109             [System.Security.SecurityCritical]
5110             get
5111             {
5112                 return _ID;
5113             }
5114             [System.Security.SecurityCritical]
5115             set
5116             {
5117                 throw new RemotingException(
5118                     Environment.GetResourceString(
5119                         "Remoting_Default"));
5120             }
5121         }
5122
5123         //IInternalMessage::SetURI
5124         [System.Security.SecurityCritical]
5125         void IInternalMessage.SetURI(String uri)
5126         {
5127             throw new RemotingException(
5128                 Environment.GetResourceString(
5129                     "Remoting_Default"));
5130         }
5131
5132         [System.Security.SecurityCritical]
5133         void IInternalMessage.SetCallContext(LogicalCallContext callContext)
5134         {
5135             throw new RemotingException(
5136                 Environment.GetResourceString(
5137                     "Remoting_Default"));
5138         }
5139
5140         [System.Security.SecurityCritical]
5141         bool IInternalMessage.HasProperties()
5142         {
5143             throw new RemotingException(
5144                 Environment.GetResourceString(
5145                     "Remoting_Default"));
5146         }
5147
5148
5149         //IMessage::SyncProcessMessage
5150         [System.Security.SecurityCritical]  // auto-generated
5151         public IMessage SyncProcessMessage(IMessage msg)
5152         {
5153             Contract.Assert(
5154                 Thread.CurrentContext.InternalContextID == _targetCtxID,
5155                 "Transition message routed to wrong context");
5156
5157             try
5158             {
5159                 LogicalCallContext oldcctx = Message.PropagateCallContextFromMessageToThread(msg);
5160                 if (_delegate != null)
5161                 {
5162                     _delegate();            
5163                 }
5164                 else
5165                 {
5166                     // This is the cross appdomain case, so we need to construct
5167                     //   the delegate and call on it.
5168                     CallBackHelper cb = new CallBackHelper(
5169                                             _eeData,
5170                                             true /*fromEE*/,
5171                                             _targetDomainID); 
5172                     CrossContextDelegate ctxDel = new CrossContextDelegate(cb.Func);
5173                     ctxDel(); 
5174                 }
5175                 Message.PropagateCallContextFromThreadToMessage(msg, oldcctx);
5176             }
5177
5178             catch (Exception e)
5179             {
5180                 ReturnMessage retMsg = new ReturnMessage(e, new ErrorMessage());
5181                 retMsg.SetLogicalCallContext(
5182                     (LogicalCallContext) msg.Properties[Message.CallContextKey]);
5183                 return retMsg;
5184             }
5185
5186             return this;    
5187         }
5188
5189         //IMessage::AsyncProcessMessage
5190         [System.Security.SecurityCritical]  // auto-generated
5191         public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
5192         {
5193             IMessage retMsg = SyncProcessMessage(msg);
5194             replySink.SyncProcessMessage(retMsg);
5195             return null;
5196         }
5197
5198         //IMessage::GetNextSink()
5199         public IMessageSink NextSink
5200         {
5201             [System.Security.SecurityCritical]  // auto-generated
5202             get{return null;}
5203         }
5204
5205         //ISerializable::GetObjectData
5206         [System.Security.SecurityCritical]  // auto-generated_required
5207         public void GetObjectData(SerializationInfo info, StreamingContext context)
5208         {
5209             if (info == null || (context.State != StreamingContextStates.CrossAppDomain))
5210             {
5211                 throw new ArgumentNullException("info");
5212             }
5213             Contract.EndContractBlock();
5214             info.AddValue("props", _props, typeof(IDictionary));
5215             info.AddValue("delegate", _delegate, typeof(CrossContextDelegate));
5216             info.AddValue("sourceCtxID", _sourceCtxID);
5217             info.AddValue("targetCtxID", _targetCtxID);
5218             info.AddValue("targetDomainID", _targetDomainID);
5219             info.AddValue("eeData", _eeData);
5220         }
5221
5222     }// class TransitionCall
5223
5224     internal class ArgMapper
5225     {
5226         int[] _map;
5227         IMethodMessage _mm;
5228         RemotingMethodCachedData _methodCachedData;
5229
5230         [System.Security.SecurityCritical]  // auto-generated
5231         internal ArgMapper(IMethodMessage mm, bool fOut)
5232         {
5233             _mm = mm;
5234             MethodBase mb = (MethodBase)_mm.MethodBase;
5235             _methodCachedData = 
5236                 InternalRemotingServices.GetReflectionCachedData(mb);
5237
5238             if (fOut)
5239                 _map = _methodCachedData.MarshalResponseArgMap;
5240             else
5241                 _map = _methodCachedData.MarshalRequestArgMap;
5242         } // ArgMapper
5243
5244         [System.Security.SecurityCritical]  // auto-generated
5245         internal ArgMapper(MethodBase mb, bool fOut)
5246         {
5247             _methodCachedData = 
5248                 InternalRemotingServices.GetReflectionCachedData(mb);
5249
5250             if (fOut)
5251                 _map = _methodCachedData.MarshalResponseArgMap;
5252             else
5253                 _map = _methodCachedData.MarshalRequestArgMap;
5254         } // ArgMapper
5255
5256         
5257         internal int[] Map
5258         { 
5259             get { return _map; }
5260         }
5261             
5262         internal int ArgCount                        
5263         { 
5264             get 
5265             {
5266             if (_map == null) 
5267             {
5268                 return 0;
5269             }
5270             else
5271             {
5272                 return _map.Length;
5273             }
5274             }
5275         }
5276             
5277         [System.Security.SecurityCritical]  // auto-generated
5278         internal Object  GetArg(int argNum)   
5279         { 
5280             
5281             if (_map == null || argNum < 0 || argNum >= _map.Length) 
5282             {
5283                 throw new InvalidOperationException(
5284                     Environment.GetResourceString(
5285                         "InvalidOperation_InternalState"));
5286             }
5287             else
5288             {
5289                 return _mm.GetArg(_map[argNum]);
5290             }
5291         }
5292
5293         [System.Security.SecurityCritical]  // auto-generated
5294         internal String GetArgName(int argNum) 
5295         { 
5296             if (_map == null || argNum < 0 || argNum >= _map.Length) 
5297             {
5298                 throw new InvalidOperationException(
5299                     Environment.GetResourceString(
5300                         "InvalidOperation_InternalState"));
5301             }
5302             else
5303             {
5304                 return _mm.GetArgName(_map[argNum]);
5305             }
5306         }
5307
5308         internal Object[] Args                       
5309         {
5310             [System.Security.SecurityCritical]  // auto-generated
5311             get 
5312             {
5313                 if (_map == null)
5314                 {
5315                     return null;
5316                 }
5317                 else
5318                 {
5319                     Object[] ret = new Object[_map.Length];
5320                     for(int i=0; i<_map.Length; i++) 
5321                     {
5322                     ret[i] = _mm.GetArg(_map[i]);
5323                     }
5324                     return ret;
5325                 }
5326             }
5327         }
5328
5329         internal Type[] ArgTypes
5330         {
5331             get
5332             {
5333                 Type[] ret = null;
5334                 if (_map != null)
5335                 {
5336                     ParameterInfo[] pi = _methodCachedData.Parameters;
5337                     ret = new Type[_map.Length];
5338                     for (int i=0; i<_map.Length; i++)
5339                     {
5340                         ret[i] = pi[_map[i]].ParameterType;
5341                     }
5342                 }
5343                 return ret;
5344             }
5345         }
5346
5347         internal String[] ArgNames
5348         {
5349             get
5350             {
5351                 String[] ret = null;
5352                 if (_map != null)
5353                 {
5354                     ParameterInfo[] pi = _methodCachedData.Parameters;
5355                     ret = new String[_map.Length];
5356                     for (int i=0; i<_map.Length; i++)
5357                     {
5358                         ret[i] = pi[_map[i]].Name;
5359                     }
5360                 }
5361                 return ret;
5362             }
5363         }
5364
5365
5366         //
5367         // Helper functions for getting argument maps
5368         //
5369
5370         internal static void GetParameterMaps(ParameterInfo[] parameters,
5371                                               out int[] inRefArgMap,
5372                                               out int[] outRefArgMap,
5373                                               out int[] outOnlyArgMap,
5374                                               out int[] nonRefOutArgMap,
5375                                               out int[] marshalRequestMap,
5376                                               out int[] marshalResponseMap)
5377         {
5378             int co;
5379         
5380             int inRefCount = 0;
5381             int outRefCount = 0;
5382             int outOnlyCount = 0;
5383             int nonRefOutCount = 0;
5384
5385             int marshalRequestCount = 0;
5386             int marshalResponseCount = 0;
5387             int[] tempMarshalRequestMap = new int[parameters.Length];
5388             int[] tempMarshalResponseMap = new int[parameters.Length];
5389
5390             // count instances of each type of parameter
5391             co = 0;
5392             foreach (ParameterInfo param in parameters)
5393             {
5394                 bool bIsIn = param.IsIn;    // [In]
5395                 bool bIsOut = param.IsOut;  // [Out]  note: out int a === [Out] ref int b
5396                 
5397                 bool bIsByRef = param.ParameterType.IsByRef; // (ref or normal)                
5398
5399                 if (!bIsByRef)
5400                 {
5401                     // it's a normal parameter (always passed in)
5402                     inRefCount++;
5403                     if (bIsOut)
5404                         nonRefOutCount++;
5405                 }
5406                 else
5407                 if (bIsOut)
5408                 {
5409                     outRefCount++;
5410                     outOnlyCount++;
5411                 }
5412                 else 
5413                 {                    
5414                     inRefCount++;
5415
5416                     outRefCount++;
5417                 }
5418
5419                 // create maps for marshaling
5420                 bool bMarshalIn = false;
5421                 bool bMarshalOut = false;
5422                 if (bIsByRef)
5423                 {
5424                     if (bIsIn == bIsOut)
5425                     {
5426                         // "ref int a" or "[In, Out] ref int a"
5427                         bMarshalIn = true;
5428                         bMarshalOut = true;
5429                     }
5430                     else
5431                     {
5432                         // "[In] ref int a" or "out int a"
5433                         bMarshalIn = bIsIn;     
5434                         bMarshalOut = bIsOut;  
5435                     }
5436                 }
5437                 else
5438                 {
5439                     // "int a" or "[In, Out] a"
5440                     bMarshalIn = true;     
5441                     bMarshalOut = bIsOut;
5442                 }
5443                 
5444            
5445                 if (bMarshalIn)
5446                     tempMarshalRequestMap[marshalRequestCount++] = co;
5447                     
5448                 if (bMarshalOut)
5449                     tempMarshalResponseMap[marshalResponseCount++] = co;
5450
5451                 co++; // parameter index
5452             } // foreach (ParameterInfo param in parameters)
5453
5454             inRefArgMap = new int[inRefCount];
5455             outRefArgMap = new int[outRefCount];
5456             outOnlyArgMap = new int[outOnlyCount];
5457             nonRefOutArgMap = new int[nonRefOutCount];
5458
5459             inRefCount = 0;
5460             outRefCount = 0;
5461             outOnlyCount = 0;
5462             nonRefOutCount = 0;
5463
5464             // build up parameter maps
5465             for (co = 0; co < parameters.Length; co++)
5466             {
5467                 ParameterInfo param = parameters[co];
5468
5469                 bool bIsOut = param.IsOut;  // [Out]  note: out int a === [Out] ref int b
5470                 
5471                 bool bIsByRef = param.ParameterType.IsByRef; // (ref or normal) 
5472
5473                 if (!bIsByRef)
5474                 {
5475                     // it's an in parameter
5476                     inRefArgMap[inRefCount++] = co;
5477                     if (bIsOut)
5478                         nonRefOutArgMap[nonRefOutCount++] = co;
5479                 }
5480                 else
5481                 if (bIsOut)
5482                 {
5483                     outRefArgMap[outRefCount++] = co;
5484                     outOnlyArgMap[outOnlyCount++] = co;
5485                 }    
5486                 else 
5487                 {                    
5488                     inRefArgMap[inRefCount++] = co;
5489
5490                     outRefArgMap[outRefCount++] = co;
5491                 }
5492             }
5493         
5494             // copy over marshal maps
5495             marshalRequestMap = new int[marshalRequestCount];
5496             Array.Copy(tempMarshalRequestMap, marshalRequestMap, marshalRequestCount);
5497             
5498             marshalResponseMap = new int[marshalResponseCount];
5499             Array.Copy(tempMarshalResponseMap, marshalResponseMap, marshalResponseCount);
5500         
5501         } // GetParameterMaps
5502         
5503         // 
5504         // Helper methods for expanding and contracting argument lists
5505         //   when translating from async methods to sync methods and back.
5506         //
5507
5508         internal static Object[] ExpandAsyncEndArgsToSyncArgs(RemotingMethodCachedData syncMethod,
5509                                                               Object[] asyncEndArgs)
5510         {
5511             // This is when we have a list of args associated with EndFoo(), and
5512             //   we want to size it to a list of args associated with Foo();
5513
5514             Object[] args = new Object[syncMethod.Parameters.Length];
5515
5516             int[] outRefArgMap = syncMethod.OutRefArgMap;
5517             
5518             for (int co = 0; co < outRefArgMap.Length; co++)
5519             {
5520                 args[outRefArgMap[co]] = asyncEndArgs[co];
5521             }
5522
5523             return args;            
5524         } // ExpandAsyncEndArgsToSyncArgs
5525                 
5526     } // class ArgMapper
5527
5528     internal class ErrorMessage: IMethodCallMessage
5529     {
5530
5531         // IMessage
5532         public IDictionary Properties
5533         {
5534             [System.Security.SecurityCritical]  // auto-generated
5535             get{ return null;}
5536         }
5537
5538         // IMethodMessage
5539         public String Uri
5540         {
5541             [System.Security.SecurityCritical]  // auto-generated
5542             get{ return m_URI; }
5543         }
5544
5545         public String MethodName
5546         {
5547             [System.Security.SecurityCritical]  // auto-generated
5548             get{ return m_MethodName; }
5549         }
5550
5551         public String TypeName
5552         {
5553             [System.Security.SecurityCritical]  // auto-generated
5554             get{ return m_TypeName; }
5555         }
5556
5557         public Object MethodSignature
5558         {
5559             [System.Security.SecurityCritical]  // auto-generated
5560             get { return m_MethodSignature; }
5561         }
5562
5563         public MethodBase MethodBase
5564         {
5565             [System.Security.SecurityCritical]  // auto-generated
5566             get { return null; }
5567         }
5568         
5569         public int ArgCount
5570         {
5571             [System.Security.SecurityCritical]  // auto-generated
5572             get { return m_ArgCount;}
5573         }
5574
5575         [System.Security.SecurityCritical]  // auto-generated
5576         public String GetArgName(int index)     { return m_ArgName; }
5577         [System.Security.SecurityCritical]  // auto-generated
5578         public Object GetArg(int argNum)        { return null;}
5579         public Object[] Args
5580         {
5581             [System.Security.SecurityCritical]  // auto-generated
5582             get { return null;}
5583         }
5584
5585         public bool HasVarArgs
5586         {
5587             [System.Security.SecurityCritical]  // auto-generated
5588             get { return false;}
5589         }
5590
5591
5592         // IMethodCallMessage
5593         public int InArgCount
5594         {
5595             [System.Security.SecurityCritical]  // auto-generated
5596             get { return m_ArgCount;}
5597         }
5598         [System.Security.SecurityCritical]  // auto-generated
5599         public String GetInArgName(int index)   { return null; }
5600         [System.Security.SecurityCritical]  // auto-generated
5601         public Object GetInArg(int argNum)      { return null;}
5602         public Object[] InArgs
5603         {
5604             [System.Security.SecurityCritical]  // auto-generated
5605             get { return null; }
5606         }
5607         public LogicalCallContext LogicalCallContext
5608         {
5609             [System.Security.SecurityCritical]  // auto-generated
5610             get { return null; }
5611         }
5612
5613         String m_URI = "Exception";
5614         String m_MethodName = "Unknown";
5615         String m_TypeName = "Unknown";
5616         Object m_MethodSignature = null;
5617         int m_ArgCount = 0;
5618         String m_ArgName = "Unknown";
5619     }
5620
5621
5622
5623     //+================================================================================
5624     //
5625     // Synopsis:  Message wrapper used as base class for all exposed message wrappers.
5626     //   This is needed so that we can extract the identity object from a custom message.
5627     //
5628     //-================================================================================
5629     /// <internalonly/>
5630     [System.Security.SecurityCritical]  // auto-generated
5631     [System.Runtime.InteropServices.ComVisible(true)]
5632     public class InternalMessageWrapper
5633     {
5634     /// <internalonly/>
5635         protected IMessage WrappedMessage;
5636     
5637     /// <internalonly/>
5638         public InternalMessageWrapper(IMessage msg)
5639         {
5640             WrappedMessage = msg;
5641         } // InternalMessageWrapper
5642
5643         [System.Security.SecurityCritical]  // auto-generated
5644         internal Object GetIdentityObject()
5645         {      
5646             IInternalMessage iim = WrappedMessage as IInternalMessage;
5647             if (null != iim)
5648             {
5649                 return iim.IdentityObject;
5650             }                
5651             else
5652             {
5653                 InternalMessageWrapper imw = WrappedMessage as InternalMessageWrapper;
5654                 if(null != imw)
5655                 {
5656                     return imw.GetIdentityObject();
5657                 }
5658             else
5659                 {
5660                 return null;
5661                 }
5662             }                
5663         } // GetIdentityObject
5664
5665         [System.Security.SecurityCritical]  // auto-generated
5666         internal Object GetServerIdentityObject()
5667         {      
5668             IInternalMessage iim = WrappedMessage as IInternalMessage;
5669             if (null != iim)
5670             {
5671                 return iim.ServerIdentityObject;
5672             }                
5673             else
5674             {
5675                 InternalMessageWrapper imw = WrappedMessage as InternalMessageWrapper;
5676                 if (null != imw)
5677                 {
5678                     return imw.GetServerIdentityObject();
5679                 }
5680             else
5681                 {
5682                 return null;
5683                 }                    
5684             }
5685         } // GetServerIdentityObject
5686     
5687     } // class InternalMessageWrapper
5688
5689
5690
5691     //+================================================================================
5692     //
5693     // Synopsis:  Message wrapper used for creating custom method call messages.
5694     //
5695     //-================================================================================
5696     /// <internalonly/>
5697     [System.Security.SecurityCritical]  // auto-generated_required
5698     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
5699     [System.Runtime.InteropServices.ComVisible(true)]
5700     public class MethodCallMessageWrapper : InternalMessageWrapper, IMethodCallMessage
5701     {
5702         // we need to overload the dictionary to delegate special values to this class
5703         private class MCMWrapperDictionary : Hashtable
5704         {
5705             private IMethodCallMessage _mcmsg; // pointer to this message object
5706             private IDictionary        _idict; // point to contained message's dictionary
5707
5708             public MCMWrapperDictionary(IMethodCallMessage msg, IDictionary idict)
5709             {
5710                 _mcmsg = msg;
5711                 _idict = idict;
5712             }
5713
5714             public override Object this[Object key]
5715             {
5716                 [System.Security.SecuritySafeCritical] // overrides transparent public member
5717                 get
5718                 {   
5719                     System.String strKey = key as System.String;
5720                     if (null != strKey)
5721                     {
5722                         switch (strKey)
5723                         {
5724                         case "__Uri": return _mcmsg.Uri;
5725                         case "__MethodName": return _mcmsg.MethodName;
5726                         case "__MethodSignature": return _mcmsg.MethodSignature;
5727                         case "__TypeName": return _mcmsg.TypeName;
5728                         case "__Args": return _mcmsg.Args;
5729                         }
5730                     }
5731                     return _idict[key];
5732                 }
5733                 [System.Security.SecuritySafeCritical] // overrides transparent public member
5734                 set
5735                 {
5736                     System.String strKey = key as System.String;
5737                     if (null != strKey)
5738                     {
5739                         switch (strKey)
5740                         {
5741                         case "__MethodName": 
5742                         case "__MethodSignature": 
5743                         case "__TypeName": 
5744                         case "__Args": 
5745                             throw new RemotingException(
5746                                 Environment.GetResourceString("Remoting_Default")); 
5747                         }
5748                         _idict[key] = value;
5749                     }
5750                 }
5751             } 
5752         } // class MCMWrapperDictionary
5753
5754
5755         IMethodCallMessage _msg;
5756         IDictionary _properties;
5757         ArgMapper  _argMapper = null;
5758         Object[] _args;    
5759         
5760
5761     /// <internalonly/>
5762         public MethodCallMessageWrapper(IMethodCallMessage msg) : base(msg) 
5763         {
5764             _msg = msg;
5765             _args = _msg.Args;
5766         } // MethodCallMessageWrapper
5767         
5768
5769         // IMethodMessage implementation
5770         
5771     /// <internalonly/>
5772         public virtual String Uri 
5773         {
5774             [System.Security.SecurityCritical]
5775             get 
5776             {
5777                 return _msg.Uri;
5778             } 
5779             set 
5780             { 
5781                 _msg.Properties[Message.UriKey] = value;
5782             }
5783         }
5784
5785     /// <internalonly/>
5786         public virtual String MethodName
5787         {
5788             [System.Security.SecurityCritical]
5789             get { return _msg.MethodName; }
5790         }
5791     /// <internalonly/>
5792         public virtual String TypeName
5793         {
5794             [System.Security.SecurityCritical]
5795             get { return _msg.TypeName; }
5796         }
5797     /// <internalonly/>
5798         public virtual Object MethodSignature
5799         {
5800             [System.Security.SecurityCritical]
5801             get { return _msg.MethodSignature; }
5802         }
5803     /// <internalonly/>
5804         public virtual LogicalCallContext LogicalCallContext
5805         {
5806             [System.Security.SecurityCritical]
5807             get { return _msg.LogicalCallContext; }
5808         }   
5809     /// <internalonly/>
5810         public virtual MethodBase MethodBase
5811         {
5812             [System.Security.SecurityCritical]
5813             get { return _msg.MethodBase; }
5814         }        
5815            
5816     /// <internalonly/>
5817         public virtual int ArgCount 
5818         {
5819             [System.Security.SecurityCritical]
5820             get
5821             {
5822                 if (_args != null)
5823                     return _args.Length;
5824                 else
5825                     return 0;
5826             }
5827         }
5828     /// <internalonly/>
5829         [System.Security.SecurityCritical]
5830         public virtual String GetArgName(int index) { return _msg.GetArgName(index); }
5831     /// <internalonly/>
5832         [System.Security.SecurityCritical]
5833         public virtual Object GetArg(int argNum) { return _args[argNum]; }
5834     /// <internalonly/>
5835         public virtual Object[] Args 
5836         {
5837             [System.Security.SecurityCritical]
5838             get { return _args; }
5839             set { _args = value; }
5840         }
5841
5842     /// <internalonly/>
5843         public virtual bool HasVarArgs
5844         {
5845             [System.Security.SecurityCritical]
5846             get { return _msg.HasVarArgs; }
5847         }
5848         
5849         // end of IMethodMessage implementation
5850
5851
5852         // IMethodCallMessage implementation
5853         //   (We cannot simply delegate to the internal message
5854         //    since we override the definition of Args and create our own array
5855         //    which can be modified.)
5856     /// <internalonly/>
5857         public virtual int InArgCount                        
5858         {
5859             [System.Security.SecurityCritical]
5860             get 
5861             {
5862                 if (_argMapper == null) _argMapper = new ArgMapper(this, false);
5863                 return _argMapper.ArgCount;
5864             }
5865         } // InArgCount
5866
5867     /// <internalonly/>
5868         [System.Security.SecurityCritical]
5869         public virtual Object GetInArg(int argNum)   
5870         {
5871             if (_argMapper == null) _argMapper = new ArgMapper(this, false);
5872             return _argMapper.GetArg(argNum);
5873         } // GetInArg
5874         
5875     /// <internalonly/>
5876         [System.Security.SecurityCritical]
5877         public virtual String GetInArgName(int index) 
5878         { 
5879             if (_argMapper == null) _argMapper = new ArgMapper(this, false);
5880             return _argMapper.GetArgName(index);
5881         } // GetInArgName
5882         
5883     /// <internalonly/>
5884         public virtual Object[] InArgs                       
5885         {
5886             [System.Security.SecurityCritical]
5887             get
5888             {
5889                 if (_argMapper == null) _argMapper = new ArgMapper(this, false);
5890                 return _argMapper.Args;
5891             }
5892         } // InArgs
5893  
5894         // end of IMethodCallMessage implementation
5895
5896
5897     /// <internalonly/>
5898         public virtual IDictionary Properties 
5899         {
5900             [System.Security.SecurityCritical]
5901             get 
5902             {
5903                 if (_properties == null)
5904                     _properties = new MCMWrapperDictionary(this, _msg.Properties);
5905                 return _properties;
5906             }
5907         }
5908
5909     } // class MethodCallMessageWrapper
5910
5911
5912
5913     //+================================================================================
5914     //
5915     // Synopsis:  Message wrapper used for creating custom method return messages.
5916     //
5917     //-================================================================================
5918     /// <internalonly/>
5919     [System.Security.SecurityCritical]  // auto-generated_required
5920     [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]    
5921     [System.Runtime.InteropServices.ComVisible(true)]
5922     public class MethodReturnMessageWrapper : InternalMessageWrapper, IMethodReturnMessage
5923     {
5924         // we need to overload the dictionary to delegate special values to this class
5925         private class MRMWrapperDictionary : Hashtable
5926         {
5927             private IMethodReturnMessage _mrmsg; // pointer to this message object
5928             private IDictionary          _idict; // point to contained message's dictionary
5929
5930             public MRMWrapperDictionary(IMethodReturnMessage msg, IDictionary idict)
5931             {
5932                 _mrmsg = msg;
5933                 _idict = idict;
5934             }
5935
5936             public override Object this[Object key]
5937             {
5938                 [System.Security.SecuritySafeCritical] // overrides transparent public member
5939                 get
5940                 {   
5941                     System.String strKey = key as System.String;
5942                     if (null != strKey)
5943                     {
5944                         switch (strKey)
5945                         {
5946                         case "__Uri": return _mrmsg.Uri;
5947                         case "__MethodName": return _mrmsg.MethodName;
5948                         case "__MethodSignature": return _mrmsg.MethodSignature;
5949                         case "__TypeName": return _mrmsg.TypeName;
5950                         case "__Return": return _mrmsg.ReturnValue;
5951                         case "__OutArgs": return _mrmsg.OutArgs;
5952                         }
5953                     }
5954                     return _idict[key];
5955                 }
5956                 [System.Security.SecuritySafeCritical] // overrides transparent public member
5957                 set
5958                 {
5959                     System.String strKey = key as System.String;
5960                     if (null != strKey)
5961                     {
5962                         switch (strKey)
5963                         {
5964                         case "__MethodName":
5965                         case "__MethodSignature":
5966                         case "__TypeName":
5967                         case "__Return":
5968                         case "__OutArgs":
5969                             throw new RemotingException(
5970                                 Environment.GetResourceString("Remoting_Default")); 
5971                         }
5972                         _idict[key] = value;
5973                     }
5974                 }
5975             } 
5976         } // class MCMWrapperDictionary
5977
5978
5979         IMethodReturnMessage _msg;
5980         IDictionary _properties;
5981         ArgMapper  _argMapper = null;
5982         Object[] _args = null;    
5983         Object _returnValue = null;
5984         Exception _exception = null;
5985         
5986
5987     /// <internalonly/>
5988         public MethodReturnMessageWrapper(IMethodReturnMessage msg) : base(msg) 
5989         {
5990             _msg = msg;
5991             _args = _msg.Args;
5992             _returnValue = _msg.ReturnValue; // be careful if you decide to lazily assign _returnValue 
5993                                              //   since the return value might actually be null
5994             _exception = _msg.Exception; // (same thing as above goes for _exception)
5995         } // MethodReturnMessageWrapper
5996         
5997
5998         // IMethodMessage implementation
5999         
6000     /// <internalonly/>
6001         public String Uri 
6002         {
6003             [System.Security.SecurityCritical]
6004             get 
6005             {
6006                 return _msg.Uri;
6007             } 
6008
6009             set
6010             {
6011                 _msg.Properties[Message.UriKey] = value;
6012             }
6013         }
6014
6015     /// <internalonly/>
6016         public virtual String MethodName
6017         {
6018             [System.Security.SecurityCritical]
6019             get { return _msg.MethodName; }
6020         }
6021     /// <internalonly/>
6022         public virtual String TypeName
6023         {
6024             [System.Security.SecurityCritical]
6025             get { return _msg.TypeName; }
6026         }
6027     /// <internalonly/>
6028         public virtual Object MethodSignature
6029         {
6030             [System.Security.SecurityCritical]
6031             get { return _msg.MethodSignature; }
6032         }
6033     /// <internalonly/>
6034         public virtual LogicalCallContext LogicalCallContext
6035         {
6036             [System.Security.SecurityCritical]
6037             get { return _msg.LogicalCallContext; }
6038         }                       
6039     /// <internalonly/>
6040         public virtual MethodBase MethodBase
6041         {
6042             [System.Security.SecurityCritical]
6043             get { return _msg.MethodBase; }
6044         }
6045            
6046     /// <internalonly/>
6047         public virtual int ArgCount 
6048         {
6049             [System.Security.SecurityCritical]
6050             get
6051             {
6052                 if (_args != null)
6053                     return _args.Length;
6054                 else
6055                     return 0;
6056             }
6057         }
6058         
6059     /// <internalonly/>
6060         [System.Security.SecurityCritical]
6061         public virtual String GetArgName(int index) { return _msg.GetArgName(index); }
6062     /// <internalonly/>
6063         [System.Security.SecurityCritical]
6064         public virtual Object GetArg(int argNum) { return _args[argNum]; }
6065     /// <internalonly/>
6066         public virtual Object[] Args 
6067         {
6068             [System.Security.SecurityCritical]
6069             get { return _args; }
6070             set { _args = value; }
6071         }
6072
6073     /// <internalonly/>
6074         public virtual bool HasVarArgs
6075         {
6076             [System.Security.SecurityCritical]
6077             get { return _msg.HasVarArgs; }
6078         }
6079         
6080         // end of IMethodMessage implementation
6081
6082
6083         // IMethodReturnMessage implementation
6084         //   (We cannot simply delegate to the internal message
6085         //    since we override the definition of Args and create our own array
6086         //    which can be modified.)
6087     /// <internalonly/>
6088         public virtual int OutArgCount                        
6089         {
6090             [System.Security.SecurityCritical]
6091             get 
6092             {
6093                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
6094                 return _argMapper.ArgCount;
6095             }
6096         }
6097
6098     /// <internalonly/>
6099         [System.Security.SecurityCritical]
6100         public virtual Object GetOutArg(int argNum)   
6101         {   
6102             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
6103             return _argMapper.GetArg(argNum);
6104         }
6105
6106     /// <internalonly/>
6107         [System.Security.SecurityCritical]
6108         public virtual String GetOutArgName(int index) 
6109         { 
6110             if (_argMapper == null) _argMapper = new ArgMapper(this, true);
6111             return _argMapper.GetArgName(index);
6112         }
6113         
6114     /// <internalonly/>
6115         public virtual Object[] OutArgs                       
6116         {
6117             [System.Security.SecurityCritical]
6118             get
6119             {
6120                 if (_argMapper == null) _argMapper = new ArgMapper(this, true);
6121                 return _argMapper.Args;
6122             }
6123         }
6124         
6125     /// <internalonly/>
6126         public virtual Exception Exception
6127         {
6128             [System.Security.SecurityCritical]
6129             get { return _exception; }
6130             set { _exception = value; }
6131         }
6132         
6133     /// <internalonly/>
6134         public virtual Object ReturnValue 
6135         {
6136             [System.Security.SecurityCritical]
6137             get { return _returnValue; }
6138             set { _returnValue = value; }
6139         }
6140  
6141         // end of IMethodReturnMessage implementation
6142
6143         // IMessage
6144     /// <internalonly/>
6145         public virtual IDictionary Properties 
6146         {
6147             [System.Security.SecurityCritical]
6148             get 
6149             {
6150                 if (_properties == null)
6151                     _properties = new MRMWrapperDictionary(this, _msg.Properties);
6152                 return _properties;
6153             }
6154         }
6155
6156
6157     } // class MethodReturnMessageWrapper
6158
6159 } // namespace Remoting
6160
6161