/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs

https://bitbucket.org/steenlund/mono-2.6.7-for-amiga · C# · 472 lines · 374 code · 49 blank · 49 comment · 111 complexity · 1898340a02f3d33601bd77c2d964b224 MD5 · raw file

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