Merge remote-tracking branch 'joncham/sgen-msvc2'
[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
241                                 MethodInfo mi = contractMethods [i];
242                                 OperationContractAttribute oca = GetOperationContractAttribute (mi);
243                                 if (oca == null)
244                                         continue;
245                                 MethodInfo end = null;
246                                 if (oca.AsyncPattern) {
247                                         if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0)
248                                                 throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'.");
249                                         string endName = "End" + mi.Name.Substring (5);
250                                         end = mi.DeclaringType.GetMethod (endName);
251                                         if (end == null)
252                                                 throw new InvalidOperationException (String.Format ("'{0}' method is missing. For async operation contract patterns, corresponding End method is required for each Begin method.", endName));
253                                         if (GetOperationContractAttribute (end) != null)
254                                                 throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
255                                 }
256                                 OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end != null ? end.ReturnType : null, isCallback, givenServiceType);
257                                 if (end != null)
258                                         od.EndMethod = end;
259                         }
260                 }
261
262                 static MethodInfo [] GetAllMethods (Type type)
263                 {
264                         var l = new List<MethodInfo> ();
265                         foreach (var t in GetAllInterfaceTypes (type)) {
266 #if MONOTOUCH
267                                 // The MethodBase[] from t.GetMethods () is cast to a IEnumerable <MethodInfo>
268                                 // when passed to List<MethodInfo>.AddRange, which in turn casts it to 
269                                 // ICollection <MethodInfo>.  The full-aot compiler has no idea of this, so
270                                 // we're going to make it aware.
271                                 int c = ((ICollection <MethodInfo>) t.GetMethods ()).Count;
272 #endif
273                                 l.AddRange (t.GetMethods ());
274                         }
275                         return l.ToArray ();
276                 }
277
278                 static IEnumerable<Type> GetAllInterfaceTypes (Type type)
279                 {
280                         yield return type;
281                         foreach (var t in type.GetInterfaces ())
282                                 foreach (var tt in GetAllInterfaceTypes (t))
283                                         yield return tt;
284                 }
285
286                 static OperationDescription GetOrCreateOperation (
287                         ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
288                         OperationContractAttribute oca,
289                         Type asyncReturnType,
290                         bool isCallback,
291                         Type givenServiceType)
292                 {
293                         string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
294
295                         OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback);
296                         if (od == null) {
297                                 od = new OperationDescription (name, cd);
298                                 od.IsOneWay = oca.IsOneWay;
299                                 if (oca.HasProtectionLevel)
300                                         od.ProtectionLevel = oca.ProtectionLevel;
301
302                                 if (HasInvalidMessageContract (mi, oca.AsyncPattern))
303                                         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));
304
305 #if !MOONLIGHT
306                                 var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false);
307                                 if (xfa != null)
308                                         od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa));
309 #endif
310                                 var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false);
311                                 if (dfa != null)
312                                         od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa));
313
314                                 od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null));
315                                 if (!od.IsOneWay) {
316                                         var md = GetMessage (od, mi, oca, false, isCallback, asyncReturnType);
317                                         od.Messages.Add (md);
318                                         var mpa = mi.ReturnParameter.GetCustomAttribute<MessageParameterAttribute> (true);
319                                         if (mpa != null) {
320                                                 var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name);
321                                                 if (mpd != null) {
322                                                         md.Body.Parts.Remove (mpd);
323                                                         md.Body.ReturnValue = mpd;
324                                                         mpd.Name = mpa.Name;
325                                                 }
326                                                 else if (md.Body.ReturnValue == null)
327                                                         throw new InvalidOperationException (String.Format ("Specified message part '{0}' in MessageParameterAttribute on the return value, was not found", mpa.Name));
328                                         }
329                                 }
330                                 var knownTypeAtts =
331                                                     cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false).Union (
332                                                     mi.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false)).Union (
333                                                     serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false));
334                                 foreach (ServiceKnownTypeAttribute a in knownTypeAtts)
335                                         foreach (Type t in a.GetTypes (givenServiceType))
336                                                 od.KnownTypes.Add (t);
337                                 foreach (FaultContractAttribute a in mi.GetCustomAttributes (typeof (FaultContractAttribute), false)) {
338                                         var fname = a.Name ?? a.DetailType.Name + "Fault";
339                                         var fns = a.Namespace ?? cd.Namespace;
340                                         var fd = new FaultDescription (a.Action ?? cd.Namespace + cd.Name + "/" + od.Name + fname) { DetailType = a.DetailType, Name = fname, Namespace = fns };
341 #if !NET_2_1
342                                         if (a.HasProtectionLevel)
343                                                 fd.ProtectionLevel = a.ProtectionLevel;
344 #endif
345                                         od.Faults.Add (fd);
346                                 }
347                                 cd.Operations.Add (od);
348                         }
349                         else if ((oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi ||
350                                  !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi) && od.InCallbackContract == isCallback)
351                                 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));
352
353                         if (oca.AsyncPattern)
354                                 od.BeginMethod = mi;
355                         else
356                                 od.SyncMethod = mi;
357                         od.IsInitiating = oca.IsInitiating;
358                         od.IsTerminating = oca.IsTerminating;
359
360                         if (mi != serviceMethod)
361                                 foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
362                                         od.Behaviors.Add ((IOperationBehavior) obj);
363
364                         if (serviceMethod != null) {
365                                 foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
366                                         od.Behaviors.Add ((IOperationBehavior) obj);
367                         }
368 #if !NET_2_1
369                         if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
370                                 od.Behaviors.Add (new OperationBehaviorAttribute ());
371 #endif
372                         // FIXME: fill KnownTypes, Behaviors and Faults.
373
374                         if (isCallback)
375                                 od.InCallbackContract = true;
376                         else
377                                 od.InOrdinalContract = true;
378
379                         return od;
380                 }
381
382                 static bool HasInvalidMessageContract (MethodInfo mi, bool async)
383                 {
384                         var pars = mi.GetParameters ();
385                         if (async) {
386                                 if (pars.Length > 3) {
387                                         if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
388                                                 return true;
389                                 }
390                         } else {
391                                 if (pars.Length > 1) {
392                                         if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
393                                                 return true;
394                                 }
395                         }
396                         return false;
397                 }
398
399                 static MessageDescription GetMessage (
400                         OperationDescription od, MethodInfo mi,
401                         OperationContractAttribute oca, bool isRequest,
402                         bool isCallback, Type asyncReturnType)
403                 {
404                         ContractDescription cd = od.DeclaringContract;
405                         ParameterInfo [] plist = mi.GetParameters ();
406                         Type messageType = null;
407                         string action = isRequest ? oca.Action : oca.ReplyAction;
408                         MessageContractAttribute mca;
409
410                         Type retType = asyncReturnType;
411                         if (!isRequest && retType == null)
412                                 retType =  mi.ReturnType;
413
414                         // If the argument is only one and has [MessageContract]
415                         // then infer it as a typed messsage
416                         if (isRequest) {
417                                 int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
418                                 mca = plist.Length != len ? null :
419                                         GetMessageContractAttribute (plist [0].ParameterType);
420                                 if (mca != null)
421                                         messageType = plist [0].ParameterType;
422                         }
423                         else {
424                                 mca = GetMessageContractAttribute (retType);
425                                 if (mca != null)
426                                         messageType = retType;
427                         }
428
429                         if (action == null)
430                                 action = String.Concat (cd.Namespace, 
431                                         cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
432                                         od.Name, isRequest ? String.Empty : "Response");
433
434                         MessageDescription md;
435                         if (mca != null)
436                                 md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
437                         else
438                                 md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
439
440                         // ReturnValue
441                         if (!isRequest) {
442                                 MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
443                                 mp.Index = 0;
444                                 mp.Type = mca != null ? typeof (void) : retType;
445                                 md.Body.ReturnValue = mp;
446                         }
447
448                         return md;
449                 }
450
451                 public static MessageDescription CreateMessageDescription (
452                         Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca)
453                 {
454                         MessageDescription md = new MessageDescription (action, isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output) { IsRequest = isRequest };
455                         md.MessageType = MessageFilterOutByRef (messageType);
456                         if (mca.HasProtectionLevel)
457                                 md.ProtectionLevel = mca.ProtectionLevel;
458
459                         MessageBodyDescription mb = md.Body;
460                         if (mca.IsWrapped) {
461                                 mb.WrapperName = mca.WrapperName ?? messageType.Name;
462                                 mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
463                         }
464
465                         int index = 0;
466                         foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
467                                 Type mtype = null;
468                                 string mname = null;
469                                 if (bmi is FieldInfo) {
470                                         FieldInfo fi = (FieldInfo) bmi;
471                                         mtype = fi.FieldType;
472                                         mname = fi.Name;
473                                 }
474                                 else if (bmi is PropertyInfo) {
475                                         PropertyInfo pi = (PropertyInfo) bmi;
476                                         mtype = pi.PropertyType;
477                                         mname = pi.Name;
478                                 }
479                                 else
480                                         continue;
481
482                                 var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false);
483                                 if (mha != null) {
484                                         var pd = CreateHeaderDescription (mha, mname, defaultNamespace);
485                                         pd.Type = MessageFilterOutByRef (mtype);
486                                         pd.MemberInfo = bmi;
487                                         md.Headers.Add (pd);
488                                 }
489                                 var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
490                                 if (mpa != null) {
491                                         var pd = new MessagePropertyDescription (mpa.Name ?? mname);
492                                         pd.Type = MessageFilterOutByRef (mtype);
493                                         pd.MemberInfo = bmi;
494                                         md.Properties.Add (pd);
495                                 }
496                                 var mba = GetMessageBodyMemberAttribute (bmi);
497                                 if (mba != null) {
498                                         var pd = CreatePartCore (mba, mname, defaultNamespace);
499                                         if (pd.Index <= 0)
500                                                 pd.Index = index++;
501                                         pd.Type = MessageFilterOutByRef (mtype);
502                                         pd.MemberInfo = bmi;
503                                         mb.Parts.Add (pd);
504                                 }
505                         }
506
507                         return md;
508                 }
509
510                 public static MessageDescription CreateMessageDescription (
511                         OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
512                 {
513                         var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
514                         MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
515
516                         MessageBodyDescription mb = md.Body;
517                         mb.WrapperName = name + (isRequest ? String.Empty : "Response");
518                         mb.WrapperNamespace = defaultNamespace;
519
520                         if (oca.HasProtectionLevel)
521                                 md.ProtectionLevel = oca.ProtectionLevel;
522
523                         // Parts
524                         int index = 0;
525                         foreach (ParameterInfo pi in plist) {
526                                 // AsyncCallback and state are extraneous.
527                                 if (oca.AsyncPattern && pi.Position == plist.Length - 2)
528                                         break;
529
530                                 // They are ignored:
531                                 // - out parameter in request
532                                 // - neither out nor ref parameter in reply
533                                 if (isRequest && pi.IsOut)
534                                         continue;
535                                 if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
536                                         continue;
537
538                                 MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
539                                 pd.Index = index++;
540                                 pd.Type = MessageFilterOutByRef (pi.ParameterType);
541                                 mb.Parts.Add (pd);                      
542                         }
543
544                         return md;
545                 }
546
547 //              public static void FillMessageBodyDescriptionByContract (
548 //                      Type messageType, MessageBodyDescription mb)
549 //              {
550 //              }
551
552                 static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace)
553                 {
554                         var ret = CreatePartCore<MessageHeaderDescription> (mha, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessageHeaderDescription (n, ns); });
555                         ret.Actor = mha.Actor;
556                         ret.MustUnderstand = mha.MustUnderstand;
557                         ret.Relay = mha.Relay;
558                         return ret;
559                 }
560
561                 static MessagePartDescription CreatePartCore (
562                         MessageParameterAttribute mpa, string defaultName,
563                         string defaultNamespace)
564                 {
565                         string pname = null;
566                         if (mpa != null && mpa.Name != null)
567                                 pname = mpa.Name;
568                         if (pname == null)
569                                 pname = defaultName;
570                         return new MessagePartDescription (pname, defaultNamespace);
571                 }
572
573                 static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace)
574                 {
575                         var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); });
576                         ret.Index = mba.Order;
577                         return ret;
578                 }
579
580                 static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator)
581                 {
582                         string pname = null, pns = null;
583                         if (mba != null) {
584                                 if (mba.Name != null)
585                                         pname = mba.Name;
586                                 if (mba.Namespace != null)
587                                         pns = mba.Namespace;
588                         }
589                         if (pname == null)
590                                 pname = defaultName;
591                         if (pns == null)
592                                 pns = defaultNamespace;
593
594                         return creator (pname, pns);
595                 }
596
597                 static Type MessageFilterOutByRef (Type type)
598                 {
599                         return type == null ? null :
600                                 type.IsByRef ? type.GetElementType () : type;
601                 }
602
603                 static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
604                 {
605                         object [] attrs = provider.GetCustomAttributes (
606                                 typeof (MessageParameterAttribute), true);
607                         return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
608                 }
609
610                 static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
611                 {
612                         object [] matts = mi.GetCustomAttributes (
613                                 typeof (MessageBodyMemberAttribute), true);
614                         return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
615                 }
616         }
617 }