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;
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);
197 FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false);
199 if (cd.CallbackContractType != null)
200 FillOperationsForInterface (cd, cd.CallbackContractType, null, true);
202 // FIXME: enable this when I found where this check is needed.
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));
210 static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback)
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 ();
222 for (int i = 0; i < contractMethods.Length; ++i)
225 MethodInfo mi = contractMethods [i];
226 OperationContractAttribute oca = GetOperationContractAttribute (mi);
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);
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.");
240 OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end != null ? end.ReturnType : null, isCallback, givenServiceType);
246 static MethodInfo [] GetAllMethods (Type type)
248 var l = new List<MethodInfo> ();
249 foreach (var t in GetAllInterfaceTypes (type)) {
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;
257 l.AddRange (t.GetMethods ());
262 static IEnumerable<Type> GetAllInterfaceTypes (Type type)
265 foreach (var t in type.GetInterfaces ())
266 foreach (var tt in GetAllInterfaceTypes (t))
270 static OperationDescription GetOrCreateOperation (
271 ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
272 OperationContractAttribute oca,
273 Type asyncReturnType,
275 Type givenServiceType)
277 string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
279 OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback);
281 od = new OperationDescription (name, cd);
282 od.IsOneWay = oca.IsOneWay;
283 if (oca.HasProtectionLevel)
284 od.ProtectionLevel = oca.ProtectionLevel;
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));
290 var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false);
292 od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa));
294 var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false);
296 od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa));
298 od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null));
300 var md = GetMessage (od, mi, oca, false, isCallback, asyncReturnType);
301 od.Messages.Add (md);
302 var mpa = mi.ReturnParameter.GetCustomAttribute<MessageParameterAttribute> (true);
304 var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name);
306 md.Body.Parts.Remove (mpd);
307 md.Body.ReturnValue = mpd;
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));
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 };
326 if (a.HasProtectionLevel)
327 fd.ProtectionLevel = a.ProtectionLevel;
331 cd.Operations.Add (od);
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));
337 if (oca.AsyncPattern)
341 od.IsInitiating = oca.IsInitiating;
342 od.IsTerminating = oca.IsTerminating;
344 if (mi != serviceMethod)
345 foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
346 od.Behaviors.Add ((IOperationBehavior) obj);
348 if (serviceMethod != null) {
349 foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
350 od.Behaviors.Add ((IOperationBehavior) obj);
353 if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
354 od.Behaviors.Add (new OperationBehaviorAttribute ());
356 // FIXME: fill KnownTypes, Behaviors and Faults.
359 od.InCallbackContract = true;
361 od.InOrdinalContract = true;
366 static bool HasInvalidMessageContract (MethodInfo mi, bool async)
368 var pars = mi.GetParameters ();
370 if (pars.Length > 3) {
371 if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
375 if (pars.Length > 1) {
376 if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
383 static MessageDescription GetMessage (
384 OperationDescription od, MethodInfo mi,
385 OperationContractAttribute oca, bool isRequest,
386 bool isCallback, Type asyncReturnType)
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;
394 Type retType = asyncReturnType;
395 if (!isRequest && retType == null)
396 retType = mi.ReturnType;
398 // If the argument is only one and has [MessageContract]
399 // then infer it as a typed messsage
401 int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
402 mca = plist.Length != len ? null :
403 GetMessageContractAttribute (plist [0].ParameterType);
405 messageType = plist [0].ParameterType;
408 mca = GetMessageContractAttribute (retType);
410 messageType = retType;
414 action = String.Concat (cd.Namespace,
415 cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
416 od.Name, isRequest ? String.Empty : "Response");
418 MessageDescription md;
420 md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
422 md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
426 MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
428 mp.Type = mca != null ? typeof (void) : retType;
429 md.Body.ReturnValue = mp;
435 public static MessageDescription CreateMessageDescription (
436 Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca)
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;
443 MessageBodyDescription mb = md.Body;
445 mb.WrapperName = mca.WrapperName ?? messageType.Name;
446 mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
450 foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
453 if (bmi is FieldInfo) {
454 FieldInfo fi = (FieldInfo) bmi;
455 mtype = fi.FieldType;
458 else if (bmi is PropertyInfo) {
459 PropertyInfo pi = (PropertyInfo) bmi;
460 mtype = pi.PropertyType;
466 var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false);
468 var pd = CreateHeaderDescription (mha, mname, defaultNamespace);
469 pd.Type = MessageFilterOutByRef (mtype);
473 var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
475 var pd = new MessagePropertyDescription (mpa.Name ?? mname);
476 pd.Type = MessageFilterOutByRef (mtype);
478 md.Properties.Add (pd);
480 var mba = GetMessageBodyMemberAttribute (bmi);
482 var pd = CreatePartCore (mba, mname, defaultNamespace);
485 pd.Type = MessageFilterOutByRef (mtype);
494 public static MessageDescription CreateMessageDescription (
495 OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
497 var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
498 MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
500 MessageBodyDescription mb = md.Body;
501 mb.WrapperName = name + (isRequest ? String.Empty : "Response");
502 mb.WrapperNamespace = defaultNamespace;
504 if (oca.HasProtectionLevel)
505 md.ProtectionLevel = oca.ProtectionLevel;
509 foreach (ParameterInfo pi in plist) {
510 // AsyncCallback and state are extraneous.
511 if (oca.AsyncPattern && pi.Position == plist.Length - 2)
515 // - out parameter in request
516 // - neither out nor ref parameter in reply
517 if (isRequest && pi.IsOut)
519 if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
522 MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
524 pd.Type = MessageFilterOutByRef (pi.ParameterType);
531 // public static void FillMessageBodyDescriptionByContract (
532 // Type messageType, MessageBodyDescription mb)
536 static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace)
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;
545 static MessagePartDescription CreatePartCore (
546 MessageParameterAttribute mpa, string defaultName,
547 string defaultNamespace)
550 if (mpa != null && mpa.Name != null)
554 return new MessagePartDescription (pname, defaultNamespace);
557 static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace)
559 var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); });
560 ret.Index = mba.Order;
564 static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator)
566 string pname = null, pns = null;
568 if (mba.Name != null)
570 if (mba.Namespace != null)
576 pns = defaultNamespace;
578 return creator (pname, pns);
581 static Type MessageFilterOutByRef (Type type)
583 return type == null ? null :
584 type.IsByRef ? type.GetElementType () : type;
587 static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
589 object [] attrs = provider.GetCustomAttributes (
590 typeof (MessageParameterAttribute), true);
591 return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
594 static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
596 object [] matts = mi.GetCustomAttributes (
597 typeof (MessageBodyMemberAttribute), true);
598 return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;