ContractDescriptionGenerator.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. end = givenContractType.GetMethod ("End" + mi.Name.Substring (5));
  159. if (end == null)
  160. throw new InvalidOperationException ("For async operation contract patterns, corresponding End method is required for each Begin method.");
  161. if (GetOperationContractAttribute (end) != null)
  162. throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
  163. }
  164. OperationDescription od = GetOrCreateOperation (cd,
  165. mi,
  166. serviceMethods [i],
  167. oca,
  168. end != null ? end.ReturnType : null);
  169. if (end != null)
  170. od.EndMethod = end;
  171. }
  172. // FIXME: enable this when I found where this check is needed.
  173. /*
  174. if (cd.Operations.Count == 0)
  175. throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType));
  176. */
  177. return cd;
  178. }
  179. static MethodInfo [] GetAllMethods (Type type)
  180. {
  181. var l = new List<MethodInfo> ();
  182. foreach (var t in GetAllInterfaceTypes (type))
  183. l.AddRange (t.GetMethods ());
  184. return l.ToArray ();
  185. }
  186. static IEnumerable<Type> GetAllInterfaceTypes (Type type)
  187. {
  188. yield return type;
  189. foreach (var t in type.GetInterfaces ())
  190. foreach (var tt in GetAllInterfaceTypes (t))
  191. yield return tt;
  192. }
  193. static OperationDescription GetOrCreateOperation (
  194. ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
  195. OperationContractAttribute oca,
  196. Type asyncReturnType)
  197. {
  198. string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
  199. OperationDescription od = null;
  200. foreach (OperationDescription iter in cd.Operations) {
  201. if (iter.Name == name) {
  202. od = iter;
  203. break;
  204. }
  205. }
  206. if (od == null) {
  207. od = new OperationDescription (name, cd);
  208. od.IsOneWay = oca.IsOneWay;
  209. if (oca.HasProtectionLevel)
  210. od.ProtectionLevel = oca.ProtectionLevel;
  211. od.Messages.Add (GetMessage (od, mi, oca, true, null));
  212. if (!od.IsOneWay)
  213. od.Messages.Add (GetMessage (od, mi, oca, false, asyncReturnType));
  214. foreach (ServiceKnownTypeAttribute a in cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  215. foreach (Type t in a.GetTypes ())
  216. od.KnownTypes.Add (t);
  217. foreach (ServiceKnownTypeAttribute a in serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  218. foreach (Type t in a.GetTypes ())
  219. od.KnownTypes.Add (t);
  220. cd.Operations.Add (od);
  221. }
  222. else if (oca.AsyncPattern && od.BeginMethod != null ||
  223. !oca.AsyncPattern && od.SyncMethod != null)
  224. throw new InvalidOperationException ("A contract cannot have two operations that have the identical names and different set of parameters.");
  225. if (oca.AsyncPattern)
  226. od.BeginMethod = mi;
  227. else
  228. od.SyncMethod = mi;
  229. od.IsInitiating = oca.IsInitiating;
  230. od.IsTerminating = oca.IsTerminating;
  231. if (mi != serviceMethod)
  232. foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
  233. od.Behaviors.Add ((IOperationBehavior) obj);
  234. if (serviceMethod != null) {
  235. foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
  236. od.Behaviors.Add ((IOperationBehavior) obj);
  237. }
  238. #if !NET_2_1
  239. if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
  240. od.Behaviors.Add (new OperationBehaviorAttribute ());
  241. #endif
  242. // FIXME: fill KnownTypes, Behaviors and Faults.
  243. return od;
  244. }
  245. static MessageDescription GetMessage (
  246. OperationDescription od, MethodInfo mi,
  247. OperationContractAttribute oca, bool isRequest,
  248. Type asyncReturnType)
  249. {
  250. ContractDescription cd = od.DeclaringContract;
  251. ParameterInfo [] plist = mi.GetParameters ();
  252. Type messageType = null;
  253. string action = isRequest ? oca.Action : oca.ReplyAction;
  254. MessageContractAttribute mca;
  255. Type retType = asyncReturnType;
  256. if (!isRequest && retType == null)
  257. retType = mi.ReturnType;
  258. // If the argument is only one and has [MessageContract]
  259. // then infer it as a typed messsage
  260. if (isRequest) {
  261. int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
  262. mca = plist.Length != len ? null :
  263. GetMessageContractAttribute (plist [0].ParameterType);
  264. if (mca != null)
  265. messageType = plist [0].ParameterType;
  266. }
  267. else {
  268. mca = GetMessageContractAttribute (retType);
  269. if (mca != null)
  270. messageType = retType;
  271. }
  272. if (action == null)
  273. action = String.Concat (cd.Namespace,
  274. cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
  275. od.Name, isRequest ? String.Empty : "Response");
  276. if (mca != null)
  277. return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, mca);
  278. return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, retType, mi.ReturnTypeCustomAttributes);
  279. }
  280. public static MessageDescription CreateMessageDescription (
  281. Type messageType, string defaultNamespace, string action, bool isRequest, MessageContractAttribute mca)
  282. {
  283. MessageDescription md = new MessageDescription (
  284. action, isRequest ? MessageDirection.Input :
  285. MessageDirection.Output);
  286. md.MessageType = MessageFilterOutByRef (messageType);
  287. if (mca.HasProtectionLevel)
  288. md.ProtectionLevel = mca.ProtectionLevel;
  289. MessageBodyDescription mb = md.Body;
  290. if (mca.IsWrapped) {
  291. mb.WrapperName = mca.WrapperName ?? messageType.Name;
  292. mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
  293. }
  294. int index = 0;
  295. foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  296. Type mtype = null;
  297. string mname = null;
  298. if (bmi is FieldInfo) {
  299. FieldInfo fi = (FieldInfo) bmi;
  300. mtype = fi.FieldType;
  301. mname = fi.Name;
  302. }
  303. else if (bmi is PropertyInfo) {
  304. PropertyInfo pi = (PropertyInfo) bmi;
  305. mtype = pi.PropertyType;
  306. mname = pi.Name;
  307. }
  308. else
  309. continue;
  310. MessageBodyMemberAttribute mba = GetMessageBodyMemberAttribute (bmi);
  311. if (mba == null)
  312. continue;
  313. MessagePartDescription pd = CreatePartCore (mba, mname, defaultNamespace);
  314. pd.Index = index++;
  315. pd.Type = MessageFilterOutByRef (mtype);
  316. pd.MemberInfo = bmi;
  317. mb.Parts.Add (pd);
  318. }
  319. // FIXME: fill headers and properties.
  320. return md;
  321. }
  322. public static MessageDescription CreateMessageDescription (
  323. OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, Type retType, ICustomAttributeProvider retTypeAttributes)
  324. {
  325. MessageDescription md = new MessageDescription (
  326. action, isRequest ? MessageDirection.Input :
  327. MessageDirection.Output);
  328. MessageBodyDescription mb = md.Body;
  329. mb.WrapperName = name + (isRequest ? String.Empty : "Response");
  330. mb.WrapperNamespace = defaultNamespace;
  331. if (oca.HasProtectionLevel)
  332. md.ProtectionLevel = oca.ProtectionLevel;
  333. // Parts
  334. int index = 0;
  335. foreach (ParameterInfo pi in plist) {
  336. // AsyncCallback and state are extraneous.
  337. if (oca.AsyncPattern && pi.Position == plist.Length - 2)
  338. break;
  339. // They are ignored:
  340. // - out parameter in request
  341. // - neither out nor ref parameter in reply
  342. if (isRequest && pi.IsOut)
  343. continue;
  344. if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
  345. continue;
  346. MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
  347. pd.Index = index++;
  348. pd.Type = MessageFilterOutByRef (pi.ParameterType);
  349. mb.Parts.Add (pd);
  350. }
  351. // ReturnValue
  352. if (!isRequest) {
  353. MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
  354. mp.Index = 0;
  355. mp.Type = retType;
  356. mb.ReturnValue = mp;
  357. }
  358. // FIXME: fill properties.
  359. return md;
  360. }
  361. public static void FillMessageBodyDescriptionByContract (
  362. Type messageType, MessageBodyDescription mb)
  363. {
  364. }
  365. static MessagePartDescription CreatePartCore (
  366. MessageParameterAttribute mpa, string defaultName,
  367. string defaultNamespace)
  368. {
  369. string pname = null;
  370. if (mpa != null && mpa.Name != null)
  371. pname = mpa.Name;
  372. if (pname == null)
  373. pname = defaultName;
  374. return new MessagePartDescription (pname, defaultNamespace);
  375. }
  376. static MessagePartDescription CreatePartCore (
  377. MessageBodyMemberAttribute mba, string defaultName,
  378. string defaultNamespace)
  379. {
  380. string pname = null, pns = null;
  381. if (mba != null) {
  382. if (mba.Name != null)
  383. pname = mba.Name;
  384. if (mba.Namespace != null)
  385. pns = mba.Namespace;
  386. }
  387. if (pname == null)
  388. pname = defaultName;
  389. if (pns == null)
  390. pns = defaultNamespace;
  391. return new MessagePartDescription (pname, pns);
  392. }
  393. static Type MessageFilterOutByRef (Type type)
  394. {
  395. return type == null ? null :
  396. type.IsByRef ? type.GetElementType () : type;
  397. }
  398. static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
  399. {
  400. object [] attrs = provider.GetCustomAttributes (
  401. typeof (MessageParameterAttribute), true);
  402. return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
  403. }
  404. static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
  405. {
  406. object [] matts = mi.GetCustomAttributes (
  407. typeof (MessageBodyMemberAttribute), true);
  408. return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
  409. }
  410. }
  411. }