ContractDescriptionGenerator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. [MonoTODO]
  68. public static ContractDescription GetContract (
  69. Type contractType) {
  70. return GetContract (contractType, (Type) null);
  71. }
  72. [MonoTODO]
  73. public static ContractDescription GetContract (
  74. Type contractType, object serviceImplementation) {
  75. if (serviceImplementation == null)
  76. throw new ArgumentNullException ("serviceImplementation");
  77. return GetContract (contractType,
  78. serviceImplementation.GetType ());
  79. }
  80. public static MessageContractAttribute GetMessageContractAttribute (Type type)
  81. {
  82. for (Type t = type; t != null; t = t.BaseType) {
  83. object [] matts = t.GetCustomAttributes (
  84. typeof (MessageContractAttribute), true);
  85. if (matts.Length > 0)
  86. return (MessageContractAttribute) matts [0];
  87. }
  88. return null;
  89. }
  90. [MonoTODO]
  91. public static ContractDescription GetContract (
  92. Type givenContractType, Type givenServiceType)
  93. {
  94. // FIXME: serviceType should be used for specifying attributes like OperationBehavior.
  95. Type exactContractType = null;
  96. ServiceContractAttribute sca = null;
  97. Dictionary<Type, ServiceContractAttribute> contracts =
  98. GetServiceContractAttributes (givenServiceType ?? givenContractType);
  99. if (contracts.ContainsKey(givenContractType)) {
  100. exactContractType = givenContractType;
  101. sca = contracts[givenContractType];
  102. } else {
  103. foreach (Type t in contracts.Keys)
  104. if (t.IsAssignableFrom(givenContractType)) {
  105. if (t.IsAssignableFrom (exactContractType)) // exact = IDerived, t = IBase
  106. continue;
  107. if (sca != null && (exactContractType == null || !exactContractType.IsAssignableFrom (t))) // t = IDerived, exact = IBase
  108. throw new InvalidOperationException ("The contract type of " + givenContractType + " is ambiguous: can be either " + exactContractType + " or " + t);
  109. exactContractType = t;
  110. sca = contracts [t];
  111. }
  112. }
  113. if (sca == null) {
  114. 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));
  115. }
  116. string name = sca.Name ?? exactContractType.Name;
  117. string ns = sca.Namespace ?? "http://tempuri.org/";
  118. ContractDescription cd =
  119. new ContractDescription (name, ns);
  120. cd.ContractType = exactContractType;
  121. cd.CallbackContractType = sca.CallbackContract;
  122. cd.SessionMode = sca.SessionMode;
  123. if (sca.ConfigurationName != null)
  124. cd.ConfigurationName = sca.ConfigurationName;
  125. else
  126. cd.ConfigurationName = exactContractType.FullName;
  127. if (sca.HasProtectionLevel)
  128. cd.ProtectionLevel = sca.ProtectionLevel;
  129. // FIXME: load Behaviors
  130. MethodInfo [] contractMethods = exactContractType.IsInterface ? GetAllMethods (exactContractType) : exactContractType.GetMethods ();
  131. MethodInfo [] serviceMethods = contractMethods;
  132. if (givenServiceType != null && exactContractType.IsInterface) {
  133. var l = new List<MethodInfo> ();
  134. foreach (Type t in GetAllInterfaceTypes (exactContractType))
  135. l.AddRange (givenServiceType.GetInterfaceMap (t).TargetMethods);
  136. serviceMethods = l.ToArray ();
  137. }
  138. for (int i = 0; i < contractMethods.Length; ++i)
  139. {
  140. MethodInfo mi = contractMethods [i];
  141. OperationContractAttribute oca = GetOperationContractAttribute (mi);
  142. if (oca == null)
  143. continue;
  144. MethodInfo end = null;
  145. if (oca.AsyncPattern) {
  146. if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0)
  147. throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'.");
  148. end = givenContractType.GetMethod ("End" + mi.Name.Substring (5));
  149. if (end == null)
  150. throw new InvalidOperationException ("For async operation contract patterns, corresponding End method is required for each Begin method.");
  151. if (GetOperationContractAttribute (end) != null)
  152. throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
  153. }
  154. OperationDescription od = GetOrCreateOperation (cd,
  155. mi,
  156. serviceMethods [i],
  157. oca,
  158. end != null ? end.ReturnType : null);
  159. if (end != null)
  160. od.EndMethod = end;
  161. }
  162. // FIXME: enable this when I found where this check is needed.
  163. /*
  164. if (cd.Operations.Count == 0)
  165. throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType));
  166. */
  167. return cd;
  168. }
  169. static MethodInfo [] GetAllMethods (Type type)
  170. {
  171. var l = new List<MethodInfo> ();
  172. foreach (var t in GetAllInterfaceTypes (type))
  173. l.AddRange (t.GetMethods ());
  174. return l.ToArray ();
  175. }
  176. static IEnumerable<Type> GetAllInterfaceTypes (Type type)
  177. {
  178. yield return type;
  179. foreach (var t in type.GetInterfaces ())
  180. foreach (var tt in GetAllInterfaceTypes (t))
  181. yield return tt;
  182. }
  183. static OperationDescription GetOrCreateOperation (
  184. ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
  185. OperationContractAttribute oca,
  186. Type asyncReturnType)
  187. {
  188. string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
  189. OperationDescription od = null;
  190. foreach (OperationDescription iter in cd.Operations) {
  191. if (iter.Name == name) {
  192. od = iter;
  193. break;
  194. }
  195. }
  196. if (od == null) {
  197. od = new OperationDescription (name, cd);
  198. od.IsOneWay = oca.IsOneWay;
  199. if (oca.HasProtectionLevel)
  200. od.ProtectionLevel = oca.ProtectionLevel;
  201. od.Messages.Add (GetMessage (od, mi, oca, true, null));
  202. if (!od.IsOneWay)
  203. od.Messages.Add (GetMessage (od, mi, oca, false, asyncReturnType));
  204. foreach (ServiceKnownTypeAttribute a in cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  205. foreach (Type t in a.GetTypes ())
  206. od.KnownTypes.Add (t);
  207. foreach (ServiceKnownTypeAttribute a in serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
  208. foreach (Type t in a.GetTypes ())
  209. od.KnownTypes.Add (t);
  210. cd.Operations.Add (od);
  211. }
  212. else if (oca.AsyncPattern && od.BeginMethod != null ||
  213. !oca.AsyncPattern && od.SyncMethod != null)
  214. throw new InvalidOperationException ("A contract cannot have two operations that have the identical names and different set of parameters.");
  215. if (oca.AsyncPattern)
  216. od.BeginMethod = mi;
  217. else
  218. od.SyncMethod = mi;
  219. od.IsInitiating = oca.IsInitiating;
  220. od.IsTerminating = oca.IsTerminating;
  221. if (mi != serviceMethod)
  222. foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
  223. od.Behaviors.Add ((IOperationBehavior) obj);
  224. if (serviceMethod != null) {
  225. foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
  226. od.Behaviors.Add ((IOperationBehavior) obj);
  227. }
  228. #if !NET_2_1
  229. if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
  230. od.Behaviors.Add (new OperationBehaviorAttribute ());
  231. #endif
  232. // FIXME: fill KnownTypes, Behaviors and Faults.
  233. return od;
  234. }
  235. static MessageDescription GetMessage (
  236. OperationDescription od, MethodInfo mi,
  237. OperationContractAttribute oca, bool isRequest,
  238. Type asyncReturnType)
  239. {
  240. ContractDescription cd = od.DeclaringContract;
  241. ParameterInfo [] plist = mi.GetParameters ();
  242. Type messageType = null;
  243. string action = isRequest ? oca.Action : oca.ReplyAction;
  244. MessageContractAttribute mca;
  245. Type retType = asyncReturnType;
  246. if (!isRequest && retType == null)
  247. retType = mi.ReturnType;
  248. // If the argument is only one and has [MessageContract]
  249. // then infer it as a typed messsage
  250. if (isRequest) {
  251. int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
  252. mca = plist.Length != len ? null :
  253. GetMessageContractAttribute (plist [0].ParameterType);
  254. if (mca != null)
  255. messageType = plist [0].ParameterType;
  256. }
  257. else {
  258. mca = GetMessageContractAttribute (retType);
  259. if (mca != null)
  260. messageType = retType;
  261. }
  262. if (action == null)
  263. action = String.Concat (cd.Namespace,
  264. cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
  265. od.Name, isRequest ? String.Empty : "Response");
  266. if (mca != null)
  267. return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, mca);
  268. return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, retType, mi.ReturnTypeCustomAttributes);
  269. }
  270. public static MessageDescription CreateMessageDescription (
  271. Type messageType, string defaultNamespace, string action, bool isRequest, MessageContractAttribute mca)
  272. {
  273. MessageDescription md = new MessageDescription (
  274. action, isRequest ? MessageDirection.Input :
  275. MessageDirection.Output);
  276. md.MessageType = MessageFilterOutByRef (messageType);
  277. if (mca.HasProtectionLevel)
  278. md.ProtectionLevel = mca.ProtectionLevel;
  279. MessageBodyDescription mb = md.Body;
  280. if (mca.IsWrapped) {
  281. mb.WrapperName = mca.WrapperName ?? messageType.Name;
  282. mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
  283. }
  284. int index = 0;
  285. foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  286. Type mtype = null;
  287. string mname = null;
  288. if (bmi is FieldInfo) {
  289. FieldInfo fi = (FieldInfo) bmi;
  290. mtype = fi.FieldType;
  291. mname = fi.Name;
  292. }
  293. else if (bmi is PropertyInfo) {
  294. PropertyInfo pi = (PropertyInfo) bmi;
  295. mtype = pi.PropertyType;
  296. mname = pi.Name;
  297. }
  298. else
  299. continue;
  300. MessageBodyMemberAttribute mba = GetMessageBodyMemberAttribute (bmi);
  301. if (mba == null)
  302. continue;
  303. MessagePartDescription pd = CreatePartCore (mba, mname, defaultNamespace);
  304. pd.Index = index++;
  305. pd.Type = MessageFilterOutByRef (mtype);
  306. pd.MemberInfo = bmi;
  307. mb.Parts.Add (pd);
  308. }
  309. // FIXME: fill headers and properties.
  310. return md;
  311. }
  312. public static MessageDescription CreateMessageDescription (
  313. OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, Type retType, ICustomAttributeProvider retTypeAttributes)
  314. {
  315. MessageDescription md = new MessageDescription (
  316. action, isRequest ? MessageDirection.Input :
  317. MessageDirection.Output);
  318. MessageBodyDescription mb = md.Body;
  319. mb.WrapperName = name + (isRequest ? String.Empty : "Response");
  320. mb.WrapperNamespace = defaultNamespace;
  321. if (oca.HasProtectionLevel)
  322. md.ProtectionLevel = oca.ProtectionLevel;
  323. // Parts
  324. int index = 0;
  325. foreach (ParameterInfo pi in plist) {
  326. // AsyncCallback and state are extraneous.
  327. if (oca.AsyncPattern && pi.Position == plist.Length - 2)
  328. break;
  329. // They are ignored:
  330. // - out parameter in request
  331. // - neither out nor ref parameter in reply
  332. if (isRequest && pi.IsOut)
  333. continue;
  334. if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
  335. continue;
  336. MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
  337. pd.Index = index++;
  338. pd.Type = MessageFilterOutByRef (pi.ParameterType);
  339. mb.Parts.Add (pd);
  340. }
  341. // ReturnValue
  342. if (!isRequest) {
  343. MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
  344. mp.Index = 0;
  345. mp.Type = retType;
  346. mb.ReturnValue = mp;
  347. }
  348. // FIXME: fill properties.
  349. return md;
  350. }
  351. public static void FillMessageBodyDescriptionByContract (
  352. Type messageType, MessageBodyDescription mb)
  353. {
  354. }
  355. static MessagePartDescription CreatePartCore (
  356. MessageParameterAttribute mpa, string defaultName,
  357. string defaultNamespace)
  358. {
  359. string pname = null;
  360. if (mpa != null && mpa.Name != null)
  361. pname = mpa.Name;
  362. if (pname == null)
  363. pname = defaultName;
  364. return new MessagePartDescription (pname, defaultNamespace);
  365. }
  366. static MessagePartDescription CreatePartCore (
  367. MessageBodyMemberAttribute mba, string defaultName,
  368. string defaultNamespace)
  369. {
  370. string pname = null, pns = null;
  371. if (mba != null) {
  372. if (mba.Name != null)
  373. pname = mba.Name;
  374. if (mba.Namespace != null)
  375. pns = mba.Namespace;
  376. }
  377. if (pname == null)
  378. pname = defaultName;
  379. if (pns == null)
  380. pns = defaultNamespace;
  381. return new MessagePartDescription (pname, pns);
  382. }
  383. static Type MessageFilterOutByRef (Type type)
  384. {
  385. return type == null ? null :
  386. type.IsByRef ? type.GetElementType () : type;
  387. }
  388. static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
  389. {
  390. object [] attrs = provider.GetCustomAttributes (
  391. typeof (MessageParameterAttribute), true);
  392. return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
  393. }
  394. static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
  395. {
  396. object [] matts = mi.GetCustomAttributes (
  397. typeof (MessageBodyMemberAttribute), true);
  398. return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
  399. }
  400. }
  401. }