ContractDescriptionGenerator.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // ContractDescriptionGenerator.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.ObjectModel;
  32. using System.Net.Security;
  33. using System.Reflection;
  34. using System.Runtime.Serialization;
  35. using System.ServiceModel;
  36. using System.ServiceModel.Channels;
  37. namespace System.ServiceModel.Description
  38. {
  39. internal static class ContractDescriptionGenerator
  40. {
  41. public static OperationContractAttribute
  42. GetOperationContractAttribute (MethodBase method)
  43. {
  44. object [] matts = method.GetCustomAttributes (
  45. typeof (OperationContractAttribute), false);
  46. if (matts.Length == 0)
  47. return null;
  48. return (OperationContractAttribute) matts [0];
  49. }
  50. static void GetServiceContractAttribute (Type type, Dictionary<Type,ServiceContractAttribute> table)
  51. {
  52. for (; type != null; type = type.BaseType) {
  53. foreach (ServiceContractAttribute i in
  54. type.GetCustomAttributes (
  55. typeof (ServiceContractAttribute), true))
  56. table [type] = i;
  57. foreach (Type t in type.GetInterfaces ())
  58. GetServiceContractAttribute (t, table);
  59. }
  60. }
  61. public static Dictionary<Type, ServiceContractAttribute> GetServiceContractAttributes (Type type)
  62. {
  63. Dictionary<Type, ServiceContractAttribute> table = new Dictionary<Type, ServiceContractAttribute> ();
  64. GetServiceContractAttribute (type, table);
  65. return table;
  66. }
  67. public static ContractDescription GetContract (
  68. Type contractType) {
  69. return GetContract (contractType, (Type) null);
  70. }
  71. public static ContractDescription GetContract (
  72. Type contractType, object serviceImplementation) {
  73. if (serviceImplementation == null)
  74. throw new ArgumentNullException ("serviceImplementation");
  75. return GetContract (contractType,
  76. serviceImplementation.GetType ());
  77. }
  78. public static MessageContractAttribute GetMessageContractAttribute (Type type)
  79. {
  80. for (Type t = type; t != null; t = t.BaseType) {
  81. object [] matts = t.GetCustomAttributes (
  82. typeof (MessageContractAttribute), true);
  83. if (matts.Length > 0)
  84. return (MessageContractAttribute) matts [0];
  85. }
  86. return null;
  87. }
  88. public static ContractDescription GetCallbackContract (Type type)
  89. {
  90. return GetContract (type, null, true);
  91. }
  92. public static ContractDescription GetContract (
  93. Type givenContractType, Type givenServiceType)
  94. {
  95. return GetContract (givenContractType, givenServiceType, false);
  96. }
  97. static ContractDescription GetContract (Type givenContractType, Type givenServiceType, bool assumeServiceContract)
  98. {
  99. // FIXME: serviceType should be used for specifying attributes like OperationBehavior.
  100. Type exactContractType = null;
  101. ServiceContractAttribute sca = null;
  102. Dictionary<Type, ServiceContractAttribute> contracts =
  103. GetServiceContractAttributes (givenServiceType ?? givenContractType);
  104. if (contracts.ContainsKey(givenContractType)) {
  105. exactContractType = givenContractType;
  106. sca = contracts[givenContractType];
  107. } else {
  108. foreach (Type t in contracts.Keys)
  109. if (t.IsAssignableFrom(givenContractType)) {
  110. if (t.IsAssignableFrom (exactContractType)) // exact = IDerived, t = IBase
  111. continue;
  112. if (sca != null && (exactContractType == null || !exactContractType.IsAssignableFrom (t))) // t = IDerived, exact = IBase
  113. throw new InvalidOperationException ("The contract type of " + givenContractType + " is ambiguous: can be either " + exactContractType + " or " + t);
  114. exactContractType = t;
  115. sca = contracts [t];
  116. }
  117. }
  118. if (exactContractType == null)
  119. exactContractType = givenContractType;
  120. if (sca == null) {
  121. if (assumeServiceContract)
  122. sca = new ServiceContractAttribute ();
  123. else
  124. throw new InvalidOperationException (String.Format ("Attempted to get contract type from '{0}' which neither is a service contract nor does it inherit service contract.", givenContractType));
  125. }
  126. string name = sca.Name ?? exactContractType.Name;
  127. string ns = sca.Namespace ?? "http://tempuri.org/";
  128. ContractDescription cd =
  129. new ContractDescription (name, ns);
  130. cd.ContractType = exactContractType;
  131. cd.CallbackContractType = sca.CallbackContract;
  132. cd.SessionMode = sca.SessionMode;
  133. if (sca.ConfigurationName != null)
  134. cd.ConfigurationName = sca.ConfigurationName;
  135. else
  136. cd.ConfigurationName = exactContractType.FullName;
  137. if (sca.HasProtectionLevel)
  138. cd.ProtectionLevel = sca.ProtectionLevel;
  139. // FIXME: load Behaviors
  140. MethodInfo [] contractMethods = exactContractType.IsInterface ? GetAllMethods (exactContractType) : exactContractType.GetMethods ();
  141. MethodInfo [] serviceMethods = contractMethods;
  142. if (givenServiceType != null && exactContractType.IsInterface) {
  143. var l = new List<MethodInfo> ();
  144. foreach (Type t in GetAllInterfaceTypes (exactContractType))
  145. l.AddRange (givenServiceType.GetInterfaceMap (t).TargetMethods);
  146. serviceMethods = l.ToArray ();
  147. }
  148. for (int i = 0; i < contractMethods.Length; ++i)
  149. {
  150. MethodInfo mi = contractMethods [i];
  151. OperationContractAttribute oca = GetOperationContractAttribute (mi);
  152. if (oca == null)
  153. continue;
  154. MethodInfo end = null;
  155. if (oca.AsyncPattern) {
  156. if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0)
  157. throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'.");
  158. string endName = "End" + mi.Name.Substring (5);
  159. end = mi.DeclaringType.GetMethod (endName);
  160. if (end == null)
  161. throw new InvalidOperationException (String.Format ("'{0}' method is missing. For async operation contract patterns, corresponding End method is required for each Begin method.", endName));
  162. if (GetOperationContractAttribute (end) != null)
  163. throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
  164. }
  165. OperationDescription od = GetOrCreateOperation (cd,
  166. mi,
  167. serviceMethods [i],
  168. oca,
  169. end != null ? end.ReturnType : null);
  170. if (end != null)
  171. od.EndMethod = end;
  172. }
  173. // FIXME: enable this when I found where this check is needed.
  174. /*
  175. if (cd.Operations.Count == 0)
  176. throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType));
  177. */
  178. return cd;
  179. }
  180. static MethodInfo [] GetAllMethods (Type type)
  181. {
  182. var l = new List<MethodInfo> ();
  183. foreach (var t in GetAllInterfaceTypes (type))
  184. l.AddRange (t.GetMethods ());
  185. return l.ToArray ();
  186. }
  187. static IEnumerable<Type> GetAllInterfaceTypes (Type type)
  188. {
  189. yield return type;
  190. foreach (var t in type.GetInterfaces ())
  191. foreach (var tt in GetAllInterfaceTypes (t))
  192. yield return tt;
  193. }
  194. static OperationDescription GetOrCreateOperation (
  195. ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
  196. OperationContractAttribute oca,
  197. Type asyncReturnType)
  198. {
  199. string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
  200. OperationDescription od = null;
  201. foreach (OperationDescription iter in cd.Operations) {
  202. if (iter.Name == name) {
  203. od = iter;
  204. break;
  205. }
  206. }
  207. if (od == null) {
  208. od = new OperationDescription (name, cd);
  209. od.IsOneWay = oca.IsOneWay;
  210. if (oca.HasProtectionLevel)
  211. od.ProtectionLevel = oca.ProtectionLevel;
  212. od.Messages.Add (GetMessage (od, mi, oca, true, null));
  213. if (!od.IsOneWay)
  214. od.Messages.Add (GetMessage (od, mi, oca, false, asyncReturnType));
  215. foreach (ServiceKnownTypeAttribute a in cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  216. foreach (Type t in a.GetTypes ())
  217. od.KnownTypes.Add (t);
  218. foreach (ServiceKnownTypeAttribute a in serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  219. foreach (Type t in a.GetTypes ())
  220. od.KnownTypes.Add (t);
  221. cd.Operations.Add (od);
  222. }
  223. else if (oca.AsyncPattern && od.BeginMethod != null ||
  224. !oca.AsyncPattern && od.SyncMethod != null)
  225. throw new InvalidOperationException ("A contract cannot have two operations that have the identical names and different set of parameters.");
  226. if (oca.AsyncPattern)
  227. od.BeginMethod = mi;
  228. else
  229. od.SyncMethod = mi;
  230. od.IsInitiating = oca.IsInitiating;
  231. od.IsTerminating = oca.IsTerminating;
  232. if (mi != serviceMethod)
  233. foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
  234. od.Behaviors.Add ((IOperationBehavior) obj);
  235. if (serviceMethod != null) {
  236. foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
  237. od.Behaviors.Add ((IOperationBehavior) obj);
  238. }
  239. #if !NET_2_1
  240. if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
  241. od.Behaviors.Add (new OperationBehaviorAttribute ());
  242. #endif
  243. // FIXME: fill KnownTypes, Behaviors and Faults.
  244. return od;
  245. }
  246. static MessageDescription GetMessage (
  247. OperationDescription od, MethodInfo mi,
  248. OperationContractAttribute oca, bool isRequest,
  249. Type asyncReturnType)
  250. {
  251. ContractDescription cd = od.DeclaringContract;
  252. ParameterInfo [] plist = mi.GetParameters ();
  253. Type messageType = null;
  254. string action = isRequest ? oca.Action : oca.ReplyAction;
  255. MessageContractAttribute mca;
  256. Type retType = asyncReturnType;
  257. if (!isRequest && retType == null)
  258. retType = mi.ReturnType;
  259. // If the argument is only one and has [MessageContract]
  260. // then infer it as a typed messsage
  261. if (isRequest) {
  262. int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
  263. mca = plist.Length != len ? null :
  264. GetMessageContractAttribute (plist [0].ParameterType);
  265. if (mca != null)
  266. messageType = plist [0].ParameterType;
  267. }
  268. else {
  269. mca = GetMessageContractAttribute (retType);
  270. if (mca != null)
  271. messageType = retType;
  272. }
  273. if (action == null)
  274. action = String.Concat (cd.Namespace,
  275. cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
  276. od.Name, isRequest ? String.Empty : "Response");
  277. if (mca != null)
  278. return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, mca);
  279. return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, retType, mi.ReturnTypeCustomAttributes);
  280. }
  281. public static MessageDescription CreateMessageDescription (
  282. Type messageType, string defaultNamespace, string action, bool isRequest, MessageContractAttribute mca)
  283. {
  284. MessageDescription md = new MessageDescription (
  285. action, isRequest ? MessageDirection.Input :
  286. MessageDirection.Output);
  287. md.MessageType = MessageFilterOutByRef (messageType);
  288. if (mca.HasProtectionLevel)
  289. md.ProtectionLevel = mca.ProtectionLevel;
  290. MessageBodyDescription mb = md.Body;
  291. if (mca.IsWrapped) {
  292. mb.WrapperName = mca.WrapperName ?? messageType.Name;
  293. mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
  294. }
  295. int index = 0;
  296. foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  297. Type mtype = null;
  298. string mname = null;
  299. if (bmi is FieldInfo) {
  300. FieldInfo fi = (FieldInfo) bmi;
  301. mtype = fi.FieldType;
  302. mname = fi.Name;
  303. }
  304. else if (bmi is PropertyInfo) {
  305. PropertyInfo pi = (PropertyInfo) bmi;
  306. mtype = pi.PropertyType;
  307. mname = pi.Name;
  308. }
  309. else
  310. continue;
  311. MessageBodyMemberAttribute mba = GetMessageBodyMemberAttribute (bmi);
  312. if (mba == null)
  313. continue;
  314. MessagePartDescription pd = CreatePartCore (mba, mname, defaultNamespace);
  315. pd.Index = index++;
  316. pd.Type = MessageFilterOutByRef (mtype);
  317. pd.MemberInfo = bmi;
  318. mb.Parts.Add (pd);
  319. }
  320. // FIXME: fill headers and properties.
  321. return md;
  322. }
  323. public static MessageDescription CreateMessageDescription (
  324. OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, Type retType, ICustomAttributeProvider retTypeAttributes)
  325. {
  326. MessageDescription md = new MessageDescription (
  327. action, isRequest ? MessageDirection.Input :
  328. MessageDirection.Output);
  329. MessageBodyDescription mb = md.Body;
  330. mb.WrapperName = name + (isRequest ? String.Empty : "Response");
  331. mb.WrapperNamespace = defaultNamespace;
  332. if (oca.HasProtectionLevel)
  333. md.ProtectionLevel = oca.ProtectionLevel;
  334. // Parts
  335. int index = 0;
  336. foreach (ParameterInfo pi in plist) {
  337. // AsyncCallback and state are extraneous.
  338. if (oca.AsyncPattern && pi.Position == plist.Length - 2)
  339. break;
  340. // They are ignored:
  341. // - out parameter in request
  342. // - neither out nor ref parameter in reply
  343. if (isRequest && pi.IsOut)
  344. continue;
  345. if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
  346. continue;
  347. MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
  348. pd.Index = index++;
  349. pd.Type = MessageFilterOutByRef (pi.ParameterType);
  350. mb.Parts.Add (pd);
  351. }
  352. // ReturnValue
  353. if (!isRequest) {
  354. MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
  355. mp.Index = 0;
  356. mp.Type = retType;
  357. mb.ReturnValue = mp;
  358. }
  359. // FIXME: fill properties.
  360. return md;
  361. }
  362. public static void FillMessageBodyDescriptionByContract (
  363. Type messageType, MessageBodyDescription mb)
  364. {
  365. }
  366. static MessagePartDescription CreatePartCore (
  367. MessageParameterAttribute mpa, string defaultName,
  368. string defaultNamespace)
  369. {
  370. string pname = null;
  371. if (mpa != null && mpa.Name != null)
  372. pname = mpa.Name;
  373. if (pname == null)
  374. pname = defaultName;
  375. return new MessagePartDescription (pname, defaultNamespace);
  376. }
  377. static MessagePartDescription CreatePartCore (
  378. MessageBodyMemberAttribute mba, string defaultName,
  379. string defaultNamespace)
  380. {
  381. string pname = null, pns = null;
  382. if (mba != null) {
  383. if (mba.Name != null)
  384. pname = mba.Name;
  385. if (mba.Namespace != null)
  386. pns = mba.Namespace;
  387. }
  388. if (pname == null)
  389. pname = defaultName;
  390. if (pns == null)
  391. pns = defaultNamespace;
  392. return new MessagePartDescription (pname, pns);
  393. }
  394. static Type MessageFilterOutByRef (Type type)
  395. {
  396. return type == null ? null :
  397. type.IsByRef ? type.GetElementType () : type;
  398. }
  399. static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
  400. {
  401. object [] attrs = provider.GetCustomAttributes (
  402. typeof (MessageParameterAttribute), true);
  403. return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
  404. }
  405. static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
  406. {
  407. object [] matts = mi.GetCustomAttributes (
  408. typeof (MessageBodyMemberAttribute), true);
  409. return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
  410. }
  411. }
  412. }