2 // ContractDescriptionGenerator.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
6 // Atsushi Enomoto <atsushi@xamarin.com>
8 // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
9 // Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.ObjectModel;
35 using System.Net.Security;
36 using System.Reflection;
37 using System.Runtime.Serialization;
38 using System.ServiceModel;
39 using System.ServiceModel.Channels;
41 namespace System.ServiceModel.Description
43 internal static class ContractDescriptionGenerator
45 public delegate bool GetOperationContractAttributeExtender (MethodBase method, object[] customAttributes, ref OperationContractAttribute oca);
47 static List <GetOperationContractAttributeExtender> getOperationContractAttributeExtenders;
49 public static void RegisterGetOperationContractAttributeExtender (GetOperationContractAttributeExtender extender)
54 if (getOperationContractAttributeExtenders == null)
55 getOperationContractAttributeExtenders = new List <GetOperationContractAttributeExtender> ();
57 if (getOperationContractAttributeExtenders.Contains (extender))
60 getOperationContractAttributeExtenders.Add (extender);
63 public static OperationContractAttribute GetOperationContractAttribute (MethodBase method)
65 object [] matts = method.GetCustomAttributes (typeof (OperationContractAttribute), false);
66 OperationContractAttribute oca;
68 if (matts.Length == 0)
71 oca = matts [0] as OperationContractAttribute;
73 if (getOperationContractAttributeExtenders != null && getOperationContractAttributeExtenders.Count > 0) {
74 foreach (var extender in getOperationContractAttributeExtenders)
75 if (extender (method, matts, ref oca))
82 static void GetServiceContractAttribute (Type type, Dictionary<Type,ServiceContractAttribute> table)
84 for (; type != null; type = type.BaseType) {
85 foreach (ServiceContractAttribute i in
86 type.GetCustomAttributes (
87 typeof (ServiceContractAttribute), true))
89 foreach (Type t in type.GetInterfaces ())
90 GetServiceContractAttribute (t, table);
93 public static Dictionary<Type, ServiceContractAttribute> GetServiceContractAttributes (Type type)
95 Dictionary<Type, ServiceContractAttribute> table = new Dictionary<Type, ServiceContractAttribute> ();
96 GetServiceContractAttribute (type, table);
100 public static ContractDescription GetContract (Type contractType) {
101 return GetContract (contractType, (Type) null);
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 ());
112 public static MessageContractAttribute GetMessageContractAttribute (Type type)
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];
123 public static ContractDescription GetCallbackContract (Type serviceType, Type callbackType)
125 return GetContract (callbackType, null, serviceType);
128 public static ContractDescription GetContract (
129 Type givenContractType, Type givenServiceType)
131 return GetContract (givenContractType, givenServiceType, null);
134 static ContractDescription GetContract (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
136 var ret = GetContractInternal (givenContractType, givenServiceType, serviceTypeForCallback);
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));
142 internal static ContractDescription GetContractInternal (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
144 if (givenContractType == null)
145 throw new ArgumentNullException ("givenContractType");
146 // FIXME: serviceType should be used for specifying attributes like OperationBehavior.
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];
156 foreach (Type t in contracts.Keys)
157 if (t.IsAssignableFrom(givenContractType)) {
158 if (t.IsAssignableFrom (exactContractType)) // exact = IDerived, t = IBase
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;
166 if (exactContractType == null)
167 exactContractType = givenContractType;
169 if (serviceTypeForCallback != null)
170 sca = contracts.Values.First ();
172 return null; // no contract
174 string name = sca.Name ?? exactContractType.Name;
175 string ns = sca.Namespace ?? "http://tempuri.org/";
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;
185 cd.ConfigurationName = exactContractType.FullName;
186 if (sca.HasProtectionLevel)
187 cd.ProtectionLevel = sca.ProtectionLevel;
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).
194 * Therefor, we manually iterate over the list of interfaces here instead of
195 * using ContractDescription.GetInheritedContracts().
199 var inherited = new Collection<ContractDescription> ();
200 foreach (var it in cd.ContractType.GetInterfaces ()) {
201 var icd = GetContractInternal (it, givenServiceType, null);
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);
213 FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false);
215 if (cd.CallbackContractType != null)
216 FillOperationsForInterface (cd, cd.CallbackContractType, null, true);
218 // FIXME: enable this when I found where this check is needed.
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));
226 static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback)
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 ();
238 for (int i = 0; i < contractMethods.Length; ++i)
240 MethodInfo mi = contractMethods [i];
241 OperationContractAttribute oca = GetOperationContractAttribute (mi);
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);
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.");
255 OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end, isCallback, givenServiceType);
261 static MethodInfo [] GetAllMethods (Type type)
263 var l = new List<MethodInfo> ();
264 foreach (var t in GetAllInterfaceTypes (type)) {
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;
272 l.AddRange (t.GetMethods ());
277 static IEnumerable<Type> GetAllInterfaceTypes (Type type)
280 foreach (var t in type.GetInterfaces ())
281 foreach (var tt in GetAllInterfaceTypes (t))
285 static OperationDescription GetOrCreateOperation (
286 ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
287 OperationContractAttribute oca,
288 MethodInfo endMethod,
290 Type givenServiceType)
292 string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
294 OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback);
296 od = new OperationDescription (name, cd);
297 od.IsOneWay = oca.IsOneWay;
298 if (oca.HasProtectionLevel)
299 od.ProtectionLevel = oca.ProtectionLevel;
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));
304 var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false);
306 od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa));
307 var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false);
309 od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa));
311 od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null));
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);
318 var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name);
320 md.Body.Parts.Remove (mpd);
321 md.Body.ReturnValue = mpd;
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));
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 };
340 if (a.HasProtectionLevel)
341 fd.ProtectionLevel = a.ProtectionLevel;
345 cd.Operations.Add (od);
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));
351 if (oca.AsyncPattern)
355 od.IsInitiating = oca.IsInitiating;
356 od.IsTerminating = oca.IsTerminating;
358 if (mi != serviceMethod)
359 foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
360 od.Behaviors.Add ((IOperationBehavior) obj);
362 if (serviceMethod != null) {
363 foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
364 od.Behaviors.Add ((IOperationBehavior) obj);
367 if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
368 od.Behaviors.Add (new OperationBehaviorAttribute ());
370 // FIXME: fill KnownTypes, Behaviors and Faults.
373 od.InCallbackContract = true;
375 od.InOrdinalContract = true;
380 static bool HasInvalidMessageContract (MethodInfo mi, bool async)
382 var pars = mi.GetParameters ();
384 if (pars.Length > 3) {
385 if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
389 if (pars.Length > 1) {
390 if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
397 static MessageDescription GetMessage (
398 OperationDescription od, MethodInfo mi,
399 OperationContractAttribute oca, bool isRequest,
400 bool isCallback, Type asyncReturnType)
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;
408 Type retType = asyncReturnType;
409 if (!isRequest && retType == null)
410 retType = mi.ReturnType;
412 // If the argument is only one and has [MessageContract]
413 // then infer it as a typed messsage
415 int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
416 mca = plist.Length != len ? null :
417 GetMessageContractAttribute (plist [0].ParameterType);
419 messageType = plist [0].ParameterType;
422 mca = GetMessageContractAttribute (retType);
424 messageType = retType;
428 action = String.Concat (cd.Namespace,
429 cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
430 od.Name, isRequest ? String.Empty : "Response");
432 MessageDescription md;
434 md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
436 md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
440 MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
442 mp.Type = mca != null ? typeof (void) : retType;
443 md.Body.ReturnValue = mp;
449 public static MessageDescription CreateMessageDescription (
450 Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca)
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;
457 MessageBodyDescription mb = md.Body;
459 mb.WrapperName = mca.WrapperName ?? messageType.Name;
460 mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
464 foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
467 if (bmi is FieldInfo) {
468 FieldInfo fi = (FieldInfo) bmi;
469 mtype = fi.FieldType;
472 else if (bmi is PropertyInfo) {
473 PropertyInfo pi = (PropertyInfo) bmi;
474 mtype = pi.PropertyType;
480 var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false);
482 var pd = CreateHeaderDescription (mha, mname, defaultNamespace);
483 pd.Type = MessageFilterOutByRef (mtype);
487 var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
489 var pd = new MessagePropertyDescription (mpa.Name ?? mname);
490 pd.Type = MessageFilterOutByRef (mtype);
492 md.Properties.Add (pd);
494 var mba = GetMessageBodyMemberAttribute (bmi);
496 var pd = CreatePartCore (mba, mname, defaultNamespace);
499 pd.Type = MessageFilterOutByRef (mtype);
508 public static MessageDescription CreateMessageDescription (
509 OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
511 var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
512 MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
514 MessageBodyDescription mb = md.Body;
515 mb.WrapperName = name + (isRequest ? String.Empty : "Response");
516 mb.WrapperNamespace = defaultNamespace;
518 if (oca.HasProtectionLevel)
519 md.ProtectionLevel = oca.ProtectionLevel;
523 foreach (ParameterInfo pi in plist) {
524 // AsyncCallback and state are extraneous.
525 if (oca.AsyncPattern) {
526 if (isRequest && pi.Position == plist.Length - 2)
528 if (!isRequest && pi.Position == plist.Length - 1)
533 // - out parameter in request
534 // - neither out nor ref parameter in reply
535 if (isRequest && pi.IsOut)
537 if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
540 MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
542 pd.Type = MessageFilterOutByRef (pi.ParameterType);
549 // public static void FillMessageBodyDescriptionByContract (
550 // Type messageType, MessageBodyDescription mb)
554 static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace)
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;
563 static MessagePartDescription CreatePartCore (
564 MessageParameterAttribute mpa, string defaultName,
565 string defaultNamespace)
568 if (mpa != null && mpa.Name != null)
572 return new MessagePartDescription (pname, defaultNamespace);
575 static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace)
577 var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); });
578 ret.Index = mba.Order;
582 static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator)
584 string pname = null, pns = null;
586 if (mba.Name != null)
588 if (mba.Namespace != null)
594 pns = defaultNamespace;
596 return creator (pname, pns);
599 static Type MessageFilterOutByRef (Type type)
601 return type == null ? null :
602 type.IsByRef ? type.GetElementType () : type;
605 static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
607 object [] attrs = provider.GetCustomAttributes (
608 typeof (MessageParameterAttribute), true);
609 return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
612 static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
614 object [] matts = mi.GetCustomAttributes (
615 typeof (MessageBodyMemberAttribute), true);
616 return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;