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