ContractDescriptionGenerator.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. cd.Operations.Add (od);
  186. }
  187. else if (oca.AsyncPattern && od.BeginMethod != null ||
  188. !oca.AsyncPattern && od.SyncMethod != null)
  189. throw new InvalidOperationException ("A contract cannot have two operations that have the identical names and different set of parameters.");
  190. if (oca.AsyncPattern)
  191. od.BeginMethod = mi;
  192. else
  193. od.SyncMethod = mi;
  194. od.IsInitiating = oca.IsInitiating;
  195. od.IsTerminating = oca.IsTerminating;
  196. if (mi != serviceMethod)
  197. foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
  198. od.Behaviors.Add ((IOperationBehavior) obj);
  199. if (serviceMethod != null) {
  200. foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
  201. od.Behaviors.Add ((IOperationBehavior) obj);
  202. }
  203. #if !NET_2_1
  204. if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
  205. od.Behaviors.Add (new OperationBehaviorAttribute ());
  206. #endif
  207. // FIXME: fill KnownTypes, Behaviors and Faults.
  208. return od;
  209. }
  210. static MessageDescription GetMessage (
  211. OperationDescription od, MethodInfo mi,
  212. OperationContractAttribute oca, bool isRequest,
  213. Type asyncReturnType)
  214. {
  215. ContractDescription cd = od.DeclaringContract;
  216. ParameterInfo [] plist = mi.GetParameters ();
  217. Type messageType = null;
  218. string action = isRequest ? oca.Action : oca.ReplyAction;
  219. MessageContractAttribute mca;
  220. Type retType = asyncReturnType;
  221. if (!isRequest && retType == null)
  222. retType = mi.ReturnType;
  223. // If the argument is only one and has [MessageContract]
  224. // then infer it as a typed messsage
  225. if (isRequest) {
  226. mca = plist.Length != 1 ? null :
  227. GetMessageContractAttribute (plist [0].ParameterType);
  228. if (mca != null)
  229. messageType = plist [0].ParameterType;
  230. }
  231. else {
  232. mca = GetMessageContractAttribute (retType);
  233. if (mca != null)
  234. messageType = retType;
  235. }
  236. if (action == null)
  237. action = String.Concat (cd.Namespace,
  238. cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
  239. od.Name, isRequest ? String.Empty : "Response");
  240. if (mca != null)
  241. return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, mca);
  242. return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, retType, mi.ReturnTypeCustomAttributes);
  243. }
  244. public static MessageDescription CreateMessageDescription (
  245. Type messageType, string defaultNamespace, string action, bool isRequest, MessageContractAttribute mca)
  246. {
  247. MessageDescription md = new MessageDescription (
  248. action, isRequest ? MessageDirection.Input :
  249. MessageDirection.Output);
  250. md.MessageType = MessageFilterOutByRef (messageType);
  251. if (mca.HasProtectionLevel)
  252. md.ProtectionLevel = mca.ProtectionLevel;
  253. MessageBodyDescription mb = md.Body;
  254. mb.WrapperName = mca.WrapperName ?? messageType.Name;
  255. mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
  256. int index = 0;
  257. foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  258. Type mtype = null;
  259. string mname = null;
  260. if (bmi is FieldInfo) {
  261. FieldInfo fi = (FieldInfo) bmi;
  262. mtype = fi.FieldType;
  263. mname = fi.Name;
  264. }
  265. else if (bmi is PropertyInfo) {
  266. PropertyInfo pi = (PropertyInfo) bmi;
  267. mtype = pi.PropertyType;
  268. mname = pi.Name;
  269. }
  270. else
  271. continue;
  272. MessageBodyMemberAttribute mba = GetMessageBodyMemberAttribute (bmi);
  273. if (mba == null)
  274. continue;
  275. MessagePartDescription pd = CreatePartCore (mba, mname, defaultNamespace);
  276. pd.Index = index++;
  277. pd.Type = MessageFilterOutByRef (mtype);
  278. pd.MemberInfo = bmi;
  279. mb.Parts.Add (pd);
  280. }
  281. // FIXME: fill headers and properties.
  282. return md;
  283. }
  284. public static MessageDescription CreateMessageDescription (
  285. OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, Type retType, ICustomAttributeProvider retTypeAttributes)
  286. {
  287. MessageDescription md = new MessageDescription (
  288. action, isRequest ? MessageDirection.Input :
  289. MessageDirection.Output);
  290. MessageBodyDescription mb = md.Body;
  291. mb.WrapperName = name + (isRequest ? String.Empty : "Response");
  292. mb.WrapperNamespace = defaultNamespace;
  293. // FIXME: anything to do for ProtectionLevel?
  294. // Parts
  295. int index = 0;
  296. foreach (ParameterInfo pi in plist) {
  297. // AsyncCallback and state are extraneous.
  298. if (oca.AsyncPattern && pi.Position == plist.Length - 2)
  299. break;
  300. // They are ignored:
  301. // - out parameter in request
  302. // - neither out nor ref parameter in reply
  303. if (isRequest && pi.IsOut)
  304. continue;
  305. if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
  306. continue;
  307. MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
  308. pd.Index = index++;
  309. pd.Type = MessageFilterOutByRef (pi.ParameterType);
  310. mb.Parts.Add (pd);
  311. }
  312. // ReturnValue
  313. if (!isRequest) {
  314. MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
  315. mp.Index = 0;
  316. mp.Type = retType;
  317. mb.ReturnValue = mp;
  318. }
  319. // FIXME: fill properties.
  320. return md;
  321. }
  322. public static void FillMessageBodyDescriptionByContract (
  323. Type messageType, MessageBodyDescription mb)
  324. {
  325. }
  326. static MessagePartDescription CreatePartCore (
  327. MessageParameterAttribute mpa, string defaultName,
  328. string defaultNamespace)
  329. {
  330. string pname = null;
  331. if (mpa != null && mpa.Name != null)
  332. pname = mpa.Name;
  333. if (pname == null)
  334. pname = defaultName;
  335. return new MessagePartDescription (pname, defaultNamespace);
  336. }
  337. static MessagePartDescription CreatePartCore (
  338. MessageBodyMemberAttribute mba, string defaultName,
  339. string defaultNamespace)
  340. {
  341. string pname = null, pns = null;
  342. if (mba != null) {
  343. if (mba.Name != null)
  344. pname = mba.Name;
  345. if (mba.Namespace != null)
  346. pns = mba.Namespace;
  347. }
  348. if (pname == null)
  349. pname = defaultName;
  350. if (pns == null)
  351. pns = defaultNamespace;
  352. return new MessagePartDescription (pname, pns);
  353. }
  354. static Type MessageFilterOutByRef (Type type)
  355. {
  356. return type == null ? null :
  357. type.IsByRef ? type.GetElementType () : type;
  358. }
  359. static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
  360. {
  361. object [] attrs = provider.GetCustomAttributes (
  362. typeof (MessageParameterAttribute), true);
  363. return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
  364. }
  365. static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
  366. {
  367. object [] matts = mi.GetCustomAttributes (
  368. typeof (MessageBodyMemberAttribute), true);
  369. return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
  370. }
  371. }
  372. }