ContractDescriptionGenerator.cs 15 KB

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