Merge pull request #1304 from slluis/mac-proxy-autoconfig
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Description / ContractDescriptionGenerator.cs
1 //
2 // ContractDescriptionGenerator.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //      Atsushi Enomoto <atsushi@xamarin.com>
7 //
8 // Copyright (C) 2005-2007 Novell, Inc.  http://www.novell.com
9 // Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30 using System;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.ObjectModel;
34 using System.Linq;
35 using System.Net.Security;
36 using System.Reflection;
37 using System.Runtime.Serialization;
38 using System.ServiceModel;
39 using System.ServiceModel.Channels;
40
41 namespace System.ServiceModel.Description
42 {
43         internal static class ContractDescriptionGenerator
44         {
45                 public delegate bool GetOperationContractAttributeExtender (MethodBase method, object[] customAttributes, ref OperationContractAttribute oca);
46
47                 static List <GetOperationContractAttributeExtender> getOperationContractAttributeExtenders;
48
49                 public static void RegisterGetOperationContractAttributeExtender (GetOperationContractAttributeExtender extender)
50                 {
51                         if (extender == null)
52                                 return;
53
54                         if (getOperationContractAttributeExtenders == null)
55                                 getOperationContractAttributeExtenders = new List <GetOperationContractAttributeExtender> ();
56
57                         if (getOperationContractAttributeExtenders.Contains (extender))
58                                 return;
59
60                         getOperationContractAttributeExtenders.Add (extender);
61                 }
62
63                 public static OperationContractAttribute GetOperationContractAttribute (MethodBase method)
64                 {
65                         object [] matts = method.GetCustomAttributes (typeof (OperationContractAttribute), false);
66                         OperationContractAttribute oca;
67                         
68                         if (matts.Length == 0)
69                                 oca = null;
70                         else
71                                 oca = matts [0] as OperationContractAttribute;
72
73                         if (getOperationContractAttributeExtenders != null && getOperationContractAttributeExtenders.Count > 0) {
74                                 foreach (var extender in getOperationContractAttributeExtenders)
75                                         if (extender (method, matts, ref oca))
76                                                 break;
77                         }
78
79                         return oca;
80                 }
81
82                 static void GetServiceContractAttribute (Type type, Dictionary<Type,ServiceContractAttribute> table)
83                 {
84                         for (; type != null; type = type.BaseType) {
85                                 foreach (ServiceContractAttribute i in
86                                         type.GetCustomAttributes (
87                                         typeof (ServiceContractAttribute), true))
88                                         table [type] = i;
89                                 foreach (Type t in type.GetInterfaces ())
90                                         GetServiceContractAttribute (t, table);
91                         }
92                 }
93                 public static Dictionary<Type, ServiceContractAttribute> GetServiceContractAttributes (Type type) 
94                 {
95                         Dictionary<Type, ServiceContractAttribute> table = new Dictionary<Type, ServiceContractAttribute> ();
96                         GetServiceContractAttribute (type, table);
97                         return table;
98                 }
99
100                 public static ContractDescription GetContract (Type contractType) {
101                         return GetContract (contractType, (Type) null);
102                 }
103
104                 public static ContractDescription GetContract (
105                         Type contractType, object serviceImplementation) {
106                         if (serviceImplementation == null)
107                                 throw new ArgumentNullException ("serviceImplementation");
108                         return GetContract (contractType,
109                                 serviceImplementation.GetType ());
110                 }
111
112                 public static MessageContractAttribute GetMessageContractAttribute (Type type)
113                 {
114                         for (Type t = type; t != null; t = t.BaseType) {
115                                 object [] matts = t.GetCustomAttributes (
116                                         typeof (MessageContractAttribute), true);
117                                 if (matts.Length > 0)
118                                         return (MessageContractAttribute) matts [0];
119                         }
120                         return null;
121                 }
122
123                 public static ContractDescription GetCallbackContract (Type serviceType, Type callbackType)
124                 {
125                         return GetContract (callbackType, null, serviceType);
126                 }
127
128                 public static ContractDescription GetContract (
129                         Type givenContractType, Type givenServiceType)
130                 {
131                         return GetContract (givenContractType, givenServiceType, null);
132                 }
133
134                 static ContractDescription GetContract (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
135                 {
136                         var ret = GetContractInternal (givenContractType, givenServiceType, serviceTypeForCallback);
137                         if (ret == null)
138                                 throw new InvalidOperationException (String.Format ("Attempted to get contract type from '{0}' which neither is a service contract nor does it inherit service contract.", serviceTypeForCallback ?? givenContractType));
139                         return ret;
140                 }
141
142                 internal static ContractDescription GetContractInternal (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
143                 {
144                         if (givenContractType == null)
145                                 throw new ArgumentNullException ("givenContractType");
146                         // FIXME: serviceType should be used for specifying attributes like OperationBehavior.
147
148                         Type exactContractType = null;
149                         ServiceContractAttribute sca = null;
150                         Dictionary<Type, ServiceContractAttribute> contracts = 
151                                 GetServiceContractAttributes (serviceTypeForCallback ?? givenServiceType ?? givenContractType);
152                         if (contracts.ContainsKey (givenContractType)) {
153                                 exactContractType = givenContractType;
154                                 sca = contracts [givenContractType];
155                         } else {
156                                 foreach (Type t in contracts.Keys)
157                                         if (t.IsAssignableFrom(givenContractType)) {
158                                                 if (t.IsAssignableFrom (exactContractType)) // exact = IDerived, t = IBase
159                                                         continue;
160                                                 if (sca != null && (exactContractType == null || !exactContractType.IsAssignableFrom (t))) // t = IDerived, exact = IBase
161                                                         throw new InvalidOperationException ("The contract type of " + givenContractType + " is ambiguous: can be either " + exactContractType + " or " + t);
162                                                 exactContractType = t;
163                                                 sca = contracts [t];
164                                         }
165                         }
166                         if (exactContractType == null)
167                                 exactContractType = givenContractType;
168                         if (sca == null) {
169                                 if (serviceTypeForCallback != null)
170                                         sca = contracts.Values.First ();
171                                 else
172                                         return null; // no contract
173                         }
174                         string name = sca.Name ?? exactContractType.Name;
175                         string ns = sca.Namespace ?? "http://tempuri.org/";
176
177                         ContractDescription cd =
178                                 new ContractDescription (name, ns);
179                         cd.ContractType = exactContractType;
180                         cd.CallbackContractType = sca.CallbackContract;
181                         cd.SessionMode = sca.SessionMode;
182                         if (sca.ConfigurationName != null)
183                                 cd.ConfigurationName = sca.ConfigurationName;
184                         else
185                                 cd.ConfigurationName = exactContractType.FullName;
186                         if (sca.HasProtectionLevel)
187                                 cd.ProtectionLevel = sca.ProtectionLevel;
188
189                         /*
190                          * Calling `FillOperationsForInterface(cd, X, null, false)' followed by
191                          * `FillOperationsForInterface(cd, X, Y, false)' would attempt to populate
192                          * the behavior list for 'X' twice (bug #6187).
193                          * 
194                          * Therefor, we manually iterate over the list of interfaces here instead of
195                          * using ContractDescription.GetInheritedContracts().
196                          * 
197                          */
198
199                         var inherited = new Collection<ContractDescription> ();
200                         foreach (var it in cd.ContractType.GetInterfaces ()) {
201                                 var icd = GetContractInternal (it, givenServiceType, null);
202                                 if (icd != null)
203                                         inherited.Add (icd);
204                         }
205
206                         foreach (var icd in inherited) {
207                                 foreach (var od in icd.Operations)
208                                         if (!cd.Operations.Any(o => o.Name == od.Name && o.SyncMethod == od.SyncMethod && 
209                                                                o.BeginMethod == od.BeginMethod && o.InCallbackContract == od.InCallbackContract))
210                                                 cd.Operations.Add (od);
211                         }
212
213                         FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false);
214                         
215                         if (cd.CallbackContractType != null)
216                                 FillOperationsForInterface (cd, cd.CallbackContractType, null, true);
217
218                         // FIXME: enable this when I found where this check is needed.
219                         /*
220                         if (cd.Operations.Count == 0)
221                                 throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType));
222                         */
223                         return cd;
224                 }
225                 
226                 static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback)
227                 {
228                         // FIXME: load Behaviors
229                         MethodInfo [] contractMethods = /*exactContractType.IsInterface ? GetAllMethods (exactContractType) :*/ exactContractType.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
230                         MethodInfo [] serviceMethods = contractMethods;
231                         if (givenServiceType != null && exactContractType.IsInterface) {
232                                 var l = new List<MethodInfo> ();
233                                 foreach (Type t in GetAllInterfaceTypes (exactContractType))
234                                         l.AddRange (givenServiceType.GetInterfaceMap (t).TargetMethods);
235                                 serviceMethods = l.ToArray ();
236                         }
237                         
238                         for (int i = 0; i < contractMethods.Length; ++i)
239                         {
240                                 MethodInfo mi = contractMethods [i];
241                                 OperationContractAttribute oca = GetOperationContractAttribute (mi);
242                                 if (oca == null)
243                                         continue;
244                                 MethodInfo end = null;
245                                 if (oca.AsyncPattern) {
246                                         if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0)
247                                                 throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'.");
248                                         string endName = "End" + mi.Name.Substring (5);
249                                         end = mi.DeclaringType.GetMethod (endName);
250                                         if (end == null)
251                                                 throw new InvalidOperationException (String.Format ("'{0}' method is missing. For async operation contract patterns, corresponding End method is required for each Begin method.", endName));
252                                         if (GetOperationContractAttribute (end) != null)
253                                                 throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
254                                 }
255                                 OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end, isCallback, givenServiceType);
256                                 if (end != null)
257                                         od.EndMethod = end;
258                         }
259                 }
260
261                 static MethodInfo [] GetAllMethods (Type type)
262                 {
263                         var l = new List<MethodInfo> ();
264                         foreach (var t in GetAllInterfaceTypes (type)) {
265 #if FULL_AOT_RUNTIME
266                                 // The MethodBase[] from t.GetMethods () is cast to a IEnumerable <MethodInfo>
267                                 // when passed to List<MethodInfo>.AddRange, which in turn casts it to 
268                                 // ICollection <MethodInfo>.  The full-aot compiler has no idea of this, so
269                                 // we're going to make it aware.
270                                 int c = ((ICollection <MethodInfo>) t.GetMethods ()).Count;
271 #endif
272                                 l.AddRange (t.GetMethods ());
273                         }
274                         return l.ToArray ();
275                 }
276
277                 static IEnumerable<Type> GetAllInterfaceTypes (Type type)
278                 {
279                         yield return type;
280                         foreach (var t in type.GetInterfaces ())
281                                 foreach (var tt in GetAllInterfaceTypes (t))
282                                         yield return tt;
283                 }
284
285                 static OperationDescription GetOrCreateOperation (
286                         ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
287                         OperationContractAttribute oca,
288                         MethodInfo endMethod,
289                         bool isCallback,
290                         Type givenServiceType)
291                 {
292                         string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
293
294                         OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback);
295                         if (od == null) {
296                                 od = new OperationDescription (name, cd);
297                                 od.IsOneWay = oca.IsOneWay;
298                                 if (oca.HasProtectionLevel)
299                                         od.ProtectionLevel = oca.ProtectionLevel;
300
301                                 if (HasInvalidMessageContract (mi, oca.AsyncPattern))
302                                         throw new InvalidOperationException (String.Format ("The operation {0} contains more than one parameters and one or more of them are marked with MessageContractAttribute, but the attribute must be used within an operation that has only one parameter.", od.Name));
303
304                                 var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false);
305                                 if (xfa != null)
306                                         od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa));
307                                 var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false);
308                                 if (dfa != null)
309                                         od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa));
310
311                                 od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null));
312                                 if (!od.IsOneWay) {
313                                         var asyncReturnType = endMethod != null ? endMethod.ReturnType : null;
314                                         var md = GetMessage (od, endMethod ?? mi, oca, false, isCallback, asyncReturnType);
315                                         od.Messages.Add (md);
316                                         var mpa = mi.ReturnParameter.GetCustomAttribute<MessageParameterAttribute> (true);
317                                         if (mpa != null) {
318                                                 var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name);
319                                                 if (mpd != null) {
320                                                         md.Body.Parts.Remove (mpd);
321                                                         md.Body.ReturnValue = mpd;
322                                                         mpd.Name = mpa.Name;
323                                                 }
324                                                 else if (md.Body.ReturnValue == null)
325                                                         throw new InvalidOperationException (String.Format ("Specified message part '{0}' in MessageParameterAttribute on the return value, was not found", mpa.Name));
326                                         }
327                                 }
328                                 var knownTypeAtts =
329                                                     cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false).Union (
330                                                     mi.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false)).Union (
331                                                     serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false));
332                                 foreach (ServiceKnownTypeAttribute a in knownTypeAtts)
333                                         foreach (Type t in a.GetTypes (givenServiceType))
334                                                 od.KnownTypes.Add (t);
335                                 foreach (FaultContractAttribute a in mi.GetCustomAttributes (typeof (FaultContractAttribute), false)) {
336                                         var fname = a.Name ?? a.DetailType.Name + "Fault";
337                                         var fns = a.Namespace ?? cd.Namespace;
338                                         var fd = new FaultDescription (a.Action ?? cd.Namespace + cd.Name + "/" + od.Name + fname) { DetailType = a.DetailType, Name = fname, Namespace = fns };
339 #if !NET_2_1
340                                         if (a.HasProtectionLevel)
341                                                 fd.ProtectionLevel = a.ProtectionLevel;
342 #endif
343                                         od.Faults.Add (fd);
344                                 }
345                                 cd.Operations.Add (od);
346                         }
347                         else if ((oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi ||
348                                  !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi) && od.InCallbackContract == isCallback)
349                                 throw new InvalidOperationException (String.Format ("contract '{1}' cannot have two operations for '{0}' that have the identical names and different set of parameters.", name, cd.Name));
350
351                         if (oca.AsyncPattern)
352                                 od.BeginMethod = mi;
353                         else
354                                 od.SyncMethod = mi;
355                         od.IsInitiating = oca.IsInitiating;
356                         od.IsTerminating = oca.IsTerminating;
357
358                         if (mi != serviceMethod)
359                                 foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
360                                         od.Behaviors.Add ((IOperationBehavior) obj);
361
362                         if (serviceMethod != null) {
363                                 foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
364                                         od.Behaviors.Add ((IOperationBehavior) obj);
365                         }
366 #if !NET_2_1
367                         if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
368                                 od.Behaviors.Add (new OperationBehaviorAttribute ());
369 #endif
370                         // FIXME: fill KnownTypes, Behaviors and Faults.
371
372                         if (isCallback)
373                                 od.InCallbackContract = true;
374                         else
375                                 od.InOrdinalContract = true;
376
377                         return od;
378                 }
379
380                 static bool HasInvalidMessageContract (MethodInfo mi, bool async)
381                 {
382                         var pars = mi.GetParameters ();
383                         if (async) {
384                                 if (pars.Length > 3) {
385                                         if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
386                                                 return true;
387                                 }
388                         } else {
389                                 if (pars.Length > 1) {
390                                         if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
391                                                 return true;
392                                 }
393                         }
394                         return false;
395                 }
396
397                 static MessageDescription GetMessage (
398                         OperationDescription od, MethodInfo mi,
399                         OperationContractAttribute oca, bool isRequest,
400                         bool isCallback, Type asyncReturnType)
401                 {
402                         ContractDescription cd = od.DeclaringContract;
403                         ParameterInfo [] plist = mi.GetParameters ();
404                         Type messageType = null;
405                         string action = isRequest ? oca.Action : oca.ReplyAction;
406                         MessageContractAttribute mca;
407
408                         Type retType = asyncReturnType;
409                         if (!isRequest && retType == null)
410                                 retType =  mi.ReturnType;
411
412                         // If the argument is only one and has [MessageContract]
413                         // then infer it as a typed messsage
414                         if (isRequest) {
415                                 int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
416                                 mca = plist.Length != len ? null :
417                                         GetMessageContractAttribute (plist [0].ParameterType);
418                                 if (mca != null)
419                                         messageType = plist [0].ParameterType;
420                         }
421                         else {
422                                 mca = GetMessageContractAttribute (retType);
423                                 if (mca != null)
424                                         messageType = retType;
425                         }
426
427                         if (action == null)
428                                 action = String.Concat (cd.Namespace, 
429                                         cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
430                                         od.Name, isRequest ? String.Empty : "Response");
431
432                         MessageDescription md;
433                         if (mca != null)
434                                 md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
435                         else
436                                 md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
437
438                         // ReturnValue
439                         if (!isRequest) {
440                                 MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
441                                 mp.Index = 0;
442                                 mp.Type = mca != null ? typeof (void) : retType;
443                                 md.Body.ReturnValue = mp;
444                         }
445
446                         return md;
447                 }
448
449                 public static MessageDescription CreateMessageDescription (
450                         Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca)
451                 {
452                         MessageDescription md = new MessageDescription (action, isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output) { IsRequest = isRequest };
453                         md.MessageType = MessageFilterOutByRef (messageType);
454                         if (mca.HasProtectionLevel)
455                                 md.ProtectionLevel = mca.ProtectionLevel;
456
457                         MessageBodyDescription mb = md.Body;
458                         if (mca.IsWrapped) {
459                                 mb.WrapperName = mca.WrapperName ?? messageType.Name;
460                                 mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
461                         }
462
463                         int index = 0;
464                         foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
465                                 Type mtype = null;
466                                 string mname = null;
467                                 if (bmi is FieldInfo) {
468                                         FieldInfo fi = (FieldInfo) bmi;
469                                         mtype = fi.FieldType;
470                                         mname = fi.Name;
471                                 }
472                                 else if (bmi is PropertyInfo) {
473                                         PropertyInfo pi = (PropertyInfo) bmi;
474                                         mtype = pi.PropertyType;
475                                         mname = pi.Name;
476                                 }
477                                 else
478                                         continue;
479
480                                 var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false);
481                                 if (mha != null) {
482                                         var pd = CreateHeaderDescription (mha, mname, defaultNamespace);
483                                         pd.Type = MessageFilterOutByRef (mtype);
484                                         pd.MemberInfo = bmi;
485                                         md.Headers.Add (pd);
486                                 }
487                                 var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
488                                 if (mpa != null) {
489                                         var pd = new MessagePropertyDescription (mpa.Name ?? mname);
490                                         pd.Type = MessageFilterOutByRef (mtype);
491                                         pd.MemberInfo = bmi;
492                                         md.Properties.Add (pd);
493                                 }
494                                 var mba = GetMessageBodyMemberAttribute (bmi);
495                                 if (mba != null) {
496                                         var pd = CreatePartCore (mba, mname, defaultNamespace);
497                                         if (pd.Index <= 0)
498                                                 pd.Index = index++;
499                                         pd.Type = MessageFilterOutByRef (mtype);
500                                         pd.MemberInfo = bmi;
501                                         mb.Parts.Add (pd);
502                                 }
503                         }
504
505                         return md;
506                 }
507
508                 public static MessageDescription CreateMessageDescription (
509                         OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
510                 {
511                         var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
512                         MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
513
514                         MessageBodyDescription mb = md.Body;
515                         mb.WrapperName = name + (isRequest ? String.Empty : "Response");
516                         mb.WrapperNamespace = defaultNamespace;
517
518                         if (oca.HasProtectionLevel)
519                                 md.ProtectionLevel = oca.ProtectionLevel;
520
521                         // Parts
522                         int index = 0;
523                         foreach (ParameterInfo pi in plist) {
524                                 // AsyncCallback and state are extraneous.
525                                 if (oca.AsyncPattern) {
526                                         if (isRequest && pi.Position == plist.Length - 2)
527                                                 break;
528                                         if (!isRequest && pi.Position == plist.Length - 1)
529                                                 break;
530                                 }
531
532                                 // They are ignored:
533                                 // - out parameter in request
534                                 // - neither out nor ref parameter in reply
535                                 if (isRequest && pi.IsOut)
536                                         continue;
537                                 if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
538                                         continue;
539
540                                 MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
541                                 pd.Index = index++;
542                                 pd.Type = MessageFilterOutByRef (pi.ParameterType);
543                                 mb.Parts.Add (pd);                      
544                         }
545
546                         return md;
547                 }
548
549 //              public static void FillMessageBodyDescriptionByContract (
550 //                      Type messageType, MessageBodyDescription mb)
551 //              {
552 //              }
553
554                 static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace)
555                 {
556                         var ret = CreatePartCore<MessageHeaderDescription> (mha, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessageHeaderDescription (n, ns); });
557                         ret.Actor = mha.Actor;
558                         ret.MustUnderstand = mha.MustUnderstand;
559                         ret.Relay = mha.Relay;
560                         return ret;
561                 }
562
563                 static MessagePartDescription CreatePartCore (
564                         MessageParameterAttribute mpa, string defaultName,
565                         string defaultNamespace)
566                 {
567                         string pname = null;
568                         if (mpa != null && mpa.Name != null)
569                                 pname = mpa.Name;
570                         if (pname == null)
571                                 pname = defaultName;
572                         return new MessagePartDescription (pname, defaultNamespace);
573                 }
574
575                 static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace)
576                 {
577                         var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); });
578                         ret.Index = mba.Order;
579                         return ret;
580                 }
581
582                 static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator)
583                 {
584                         string pname = null, pns = null;
585                         if (mba != null) {
586                                 if (mba.Name != null)
587                                         pname = mba.Name;
588                                 if (mba.Namespace != null)
589                                         pns = mba.Namespace;
590                         }
591                         if (pname == null)
592                                 pname = defaultName;
593                         if (pns == null)
594                                 pns = defaultNamespace;
595
596                         return creator (pname, pns);
597                 }
598
599                 static Type MessageFilterOutByRef (Type type)
600                 {
601                         return type == null ? null :
602                                 type.IsByRef ? type.GetElementType () : type;
603                 }
604
605                 static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
606                 {
607                         object [] attrs = provider.GetCustomAttributes (
608                                 typeof (MessageParameterAttribute), true);
609                         return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
610                 }
611
612                 static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
613                 {
614                         object [] matts = mi.GetCustomAttributes (
615                                 typeof (MessageBodyMemberAttribute), true);
616                         return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
617                 }
618         }
619 }