ContractDescriptionGenerator.cs 15 KB

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