ContractDescriptionGenerator.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. //
  2. // ContractDescriptionGenerator.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
  9. // Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.Collections.Generic;
  33. using System.Collections.ObjectModel;
  34. using System.Linq;
  35. using System.Net.Security;
  36. using System.Reflection;
  37. using System.Runtime.Serialization;
  38. using System.ServiceModel;
  39. using System.ServiceModel.Channels;
  40. namespace System.ServiceModel.Description
  41. {
  42. internal static class ContractDescriptionGenerator
  43. {
  44. public delegate bool GetOperationContractAttributeExtender (MethodBase method, object[] customAttributes, ref OperationContractAttribute oca);
  45. static List <GetOperationContractAttributeExtender> getOperationContractAttributeExtenders;
  46. public static void RegisterGetOperationContractAttributeExtender (GetOperationContractAttributeExtender extender)
  47. {
  48. if (extender == null)
  49. return;
  50. if (getOperationContractAttributeExtenders == null)
  51. getOperationContractAttributeExtenders = new List <GetOperationContractAttributeExtender> ();
  52. if (getOperationContractAttributeExtenders.Contains (extender))
  53. return;
  54. getOperationContractAttributeExtenders.Add (extender);
  55. }
  56. public static OperationContractAttribute GetOperationContractAttribute (MethodBase method)
  57. {
  58. object [] matts = method.GetCustomAttributes (typeof (OperationContractAttribute), false);
  59. OperationContractAttribute oca;
  60. if (matts.Length == 0)
  61. oca = null;
  62. else
  63. oca = matts [0] as OperationContractAttribute;
  64. if (getOperationContractAttributeExtenders != null && getOperationContractAttributeExtenders.Count > 0) {
  65. foreach (var extender in getOperationContractAttributeExtenders)
  66. if (extender (method, matts, ref oca))
  67. break;
  68. }
  69. return oca;
  70. }
  71. static void GetServiceContractAttribute (Type type, Dictionary<Type,ServiceContractAttribute> table)
  72. {
  73. for (; type != null; type = type.BaseType) {
  74. foreach (ServiceContractAttribute i in
  75. type.GetCustomAttributes (
  76. typeof (ServiceContractAttribute), true))
  77. table [type] = i;
  78. foreach (Type t in type.GetInterfaces ())
  79. GetServiceContractAttribute (t, table);
  80. }
  81. }
  82. public static Dictionary<Type, ServiceContractAttribute> GetServiceContractAttributes (Type type)
  83. {
  84. Dictionary<Type, ServiceContractAttribute> table = new Dictionary<Type, ServiceContractAttribute> ();
  85. GetServiceContractAttribute (type, table);
  86. return table;
  87. }
  88. public static ContractDescription GetContract (Type contractType) {
  89. return GetContract (contractType, (Type) null);
  90. }
  91. public static ContractDescription GetContract (
  92. Type contractType, object serviceImplementation) {
  93. if (serviceImplementation == null)
  94. throw new ArgumentNullException ("serviceImplementation");
  95. return GetContract (contractType,
  96. serviceImplementation.GetType ());
  97. }
  98. public static MessageContractAttribute GetMessageContractAttribute (Type type)
  99. {
  100. for (Type t = type; t != null; t = t.BaseType) {
  101. object [] matts = t.GetCustomAttributes (
  102. typeof (MessageContractAttribute), true);
  103. if (matts.Length > 0)
  104. return (MessageContractAttribute) matts [0];
  105. }
  106. return null;
  107. }
  108. public static ContractDescription GetCallbackContract (Type serviceType, Type callbackType)
  109. {
  110. return GetContract (callbackType, null, serviceType);
  111. }
  112. public static ContractDescription GetContract (
  113. Type givenContractType, Type givenServiceType)
  114. {
  115. return GetContract (givenContractType, givenServiceType, null);
  116. }
  117. static ContractDescription GetContract (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
  118. {
  119. var ret = GetContractInternal (givenContractType, givenServiceType, serviceTypeForCallback);
  120. if (ret == null)
  121. 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));
  122. return ret;
  123. }
  124. internal static Type GetContractAssignableToInterfaces(Type given, Type [] givenInterfaces)
  125. {
  126. if ((given != null) && (givenInterfaces.Count() < 1))
  127. return null;
  128. Dictionary<Type,int> interfaceGraph = new Dictionary<Type,int> ();
  129. foreach (var smaller in givenInterfaces) {
  130. interfaceGraph [smaller] = 0;
  131. foreach (var bigger in givenInterfaces) {
  132. if (smaller.IsAssignableFrom (bigger)) {
  133. interfaceGraph [smaller]++;
  134. }
  135. }
  136. }
  137. List<Type> possibleInterfaces = new List<Type> ();
  138. foreach (var node in interfaceGraph) {
  139. if (node.Value == 1) {
  140. possibleInterfaces.Add(node.Key);
  141. }
  142. }
  143. // For this purpose a contract is a set of interfaces. it is necessary to find the interface representative of rest of the set. It will be assignable to all of
  144. // the others but can only be assigned to by itself. This will give it count of ! in its slot in the interfaceGraph. To be a valid set there can be only one with a count of one
  145. // in its slot. More results in InvalidOperation exceptioni with ambigours error message, less means that the interface we want is the one passed in by the parameter given
  146. // and by returning null we give the callign method permission to use it..
  147. switch (possibleInterfaces.Count())
  148. {
  149. case 0:
  150. break;
  151. case 1:
  152. return possibleInterfaces [0];
  153. break;
  154. default:
  155. if (!given.IsInterface)
  156. throw new InvalidOperationException ("The contract type of " + given + " is ambiguous: can be either " + possibleInterfaces[0] + " or " + possibleInterfaces[1]);
  157. break;
  158. }
  159. return null;
  160. }
  161. internal static ContractDescription GetContractInternal (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
  162. {
  163. if (givenContractType == null)
  164. throw new ArgumentNullException ("givenContractType");
  165. // FIXME: serviceType should be used for specifying attributes like OperationBehavior.
  166. Type exactContractType = null;
  167. ServiceContractAttribute sca = null;
  168. Dictionary<Type, ServiceContractAttribute> contracts =
  169. GetServiceContractAttributes (serviceTypeForCallback ?? givenServiceType ?? givenContractType);
  170. if (contracts.ContainsKey (givenContractType)) {
  171. exactContractType = givenContractType;
  172. sca = contracts [givenContractType];
  173. } else {
  174. Type[] contractTypes = contracts.Keys.ToArray() as Type [];
  175. exactContractType = GetContractAssignableToInterfaces(givenContractType, contractTypes);
  176. if (exactContractType != null)
  177. sca = contracts[exactContractType];
  178. }
  179. if (exactContractType == null)
  180. exactContractType = givenContractType;
  181. if (sca == null) {
  182. if (serviceTypeForCallback != null)
  183. sca = contracts.Values.First ();
  184. else
  185. return null; // no contract
  186. }
  187. string name = sca.Name ?? exactContractType.Name;
  188. string ns = sca.Namespace ?? "http://tempuri.org/";
  189. ContractDescription cd =
  190. new ContractDescription (name, ns);
  191. cd.ContractType = exactContractType;
  192. cd.CallbackContractType = sca.CallbackContract;
  193. cd.SessionMode = sca.SessionMode;
  194. if (sca.ConfigurationName != null)
  195. cd.ConfigurationName = sca.ConfigurationName;
  196. else
  197. cd.ConfigurationName = exactContractType.FullName;
  198. if (sca.HasProtectionLevel)
  199. cd.ProtectionLevel = sca.ProtectionLevel;
  200. /*
  201. * Calling `FillOperationsForInterface(cd, X, null, false)' followed by
  202. * `FillOperationsForInterface(cd, X, Y, false)' would attempt to populate
  203. * the behavior list for 'X' twice (bug #6187).
  204. *
  205. * Therefor, we manually iterate over the list of interfaces here instead of
  206. * using ContractDescription.GetInheritedContracts().
  207. *
  208. */
  209. var inherited = new Collection<ContractDescription> ();
  210. var interfaces = cd.ContractType.GetInterfaces ();
  211. foreach (var it in interfaces ) {
  212. var icd = GetContractInternal (it, givenServiceType, null);
  213. if (icd != null)
  214. inherited.Add (icd);
  215. }
  216. foreach (var icd in inherited)
  217. {
  218. foreach (var od in icd.Operations)
  219. {
  220. if (!cd.Operations.Any (o => o.Name == od.Name && o.SyncMethod == od.SyncMethod && o.BeginMethod == od.BeginMethod && o.InCallbackContract == od.InCallbackContract))
  221. cd.Operations.Add (od);
  222. }
  223. }
  224. FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false);
  225. if (cd.CallbackContractType != null)
  226. FillOperationsForInterface (cd, cd.CallbackContractType, null, true);
  227. // FIXME: enable this when I found where this check is needed.
  228. /*
  229. if (cd.Operations.Count == 0)
  230. throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType));
  231. */
  232. return cd;
  233. }
  234. static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback)
  235. {
  236. // FIXME: load Behaviors
  237. MethodInfo [] contractMethods = /*exactContractType.IsInterface ? GetAllMethods (exactContractType) :*/ exactContractType.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  238. MethodInfo [] serviceMethods = contractMethods;
  239. if (givenServiceType != null && exactContractType.IsInterface) {
  240. var l = new List<MethodInfo> ();
  241. foreach (Type t in GetAllInterfaceTypes (exactContractType))
  242. l.AddRange (givenServiceType.GetInterfaceMap (t).TargetMethods);
  243. serviceMethods = l.ToArray ();
  244. }
  245. for (int i = 0; i < contractMethods.Length; ++i)
  246. {
  247. MethodInfo mi = contractMethods [i];
  248. OperationContractAttribute oca = GetOperationContractAttribute (mi);
  249. if (oca == null)
  250. continue;
  251. MethodInfo end = null;
  252. if (oca.AsyncPattern) {
  253. if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0)
  254. throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'.");
  255. string endName = "End" + mi.Name.Substring (5);
  256. end = mi.DeclaringType.GetMethod (endName);
  257. if (end == null)
  258. throw new InvalidOperationException (String.Format ("'{0}' method is missing. For async operation contract patterns, corresponding End method is required for each Begin method.", endName));
  259. if (GetOperationContractAttribute (end) != null)
  260. throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method.");
  261. }
  262. OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end != null ? end.ReturnType : null, isCallback, givenServiceType);
  263. if (end != null)
  264. od.EndMethod = end;
  265. }
  266. }
  267. static MethodInfo [] GetAllMethods (Type type)
  268. {
  269. var l = new List<MethodInfo> ();
  270. foreach (var t in GetAllInterfaceTypes (type)) {
  271. #if FULL_AOT_RUNTIME
  272. // The MethodBase[] from t.GetMethods () is cast to a IEnumerable <MethodInfo>
  273. // when passed to List<MethodInfo>.AddRange, which in turn casts it to
  274. // ICollection <MethodInfo>. The full-aot compiler has no idea of this, so
  275. // we're going to make it aware.
  276. int c = ((ICollection <MethodInfo>) t.GetMethods ()).Count;
  277. #endif
  278. l.AddRange (t.GetMethods ());
  279. }
  280. return l.ToArray ();
  281. }
  282. static IEnumerable<Type> GetAllInterfaceTypes (Type type)
  283. {
  284. yield return type;
  285. foreach (var t in type.GetInterfaces ())
  286. foreach (var tt in GetAllInterfaceTypes (t))
  287. yield return tt;
  288. }
  289. static OperationDescription GetOrCreateOperation (
  290. ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod,
  291. OperationContractAttribute oca,
  292. Type asyncReturnType,
  293. bool isCallback,
  294. Type givenServiceType)
  295. {
  296. string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
  297. OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback);
  298. if (od == null) {
  299. od = new OperationDescription (name, cd);
  300. od.IsOneWay = oca.IsOneWay;
  301. if (oca.HasProtectionLevel)
  302. od.ProtectionLevel = oca.ProtectionLevel;
  303. if (HasInvalidMessageContract (mi, oca.AsyncPattern))
  304. throw new InvalidOperationException (String.Format ("The operation {0} contains more than one parameters and one or more of them are marked with MessageContractAttribute, but the attribute must be used within an operation that has only one parameter.", od.Name));
  305. var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false);
  306. if (xfa != null)
  307. od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa));
  308. var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false);
  309. if (dfa != null)
  310. od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa));
  311. od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null));
  312. if (!od.IsOneWay) {
  313. var md = GetMessage (od, mi, oca, false, isCallback, asyncReturnType);
  314. od.Messages.Add (md);
  315. var mpa = mi.ReturnParameter.GetCustomAttribute<MessageParameterAttribute> (true);
  316. if (mpa != null) {
  317. var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name);
  318. if (mpd != null) {
  319. md.Body.Parts.Remove (mpd);
  320. md.Body.ReturnValue = mpd;
  321. mpd.Name = mpa.Name;
  322. }
  323. else if (md.Body.ReturnValue == null)
  324. throw new InvalidOperationException (String.Format ("Specified message part '{0}' in MessageParameterAttribute on the return value, was not found", mpa.Name));
  325. }
  326. }
  327. var knownTypeAtts =
  328. cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false).Union (
  329. mi.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false)).Union (
  330. serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false));
  331. foreach (ServiceKnownTypeAttribute a in knownTypeAtts)
  332. foreach (Type t in a.GetTypes (givenServiceType))
  333. od.KnownTypes.Add (t);
  334. foreach (FaultContractAttribute a in mi.GetCustomAttributes (typeof (FaultContractAttribute), false)) {
  335. var fname = a.Name ?? a.DetailType.Name + "Fault";
  336. var fns = a.Namespace ?? cd.Namespace;
  337. var fd = new FaultDescription (a.Action ?? cd.Namespace + cd.Name + "/" + od.Name + fname) { DetailType = a.DetailType, Name = fname, Namespace = fns };
  338. #if !NET_2_1
  339. if (a.HasProtectionLevel)
  340. fd.ProtectionLevel = a.ProtectionLevel;
  341. #endif
  342. od.Faults.Add (fd);
  343. }
  344. cd.Operations.Add (od);
  345. }
  346. else if ((oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi ||
  347. !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi) && od.InCallbackContract == isCallback)
  348. throw new InvalidOperationException (String.Format ("contract '{1}' cannot have two operations for '{0}' that have the identical names and different set of parameters.", name, cd.Name));
  349. if (oca.AsyncPattern)
  350. od.BeginMethod = mi;
  351. else
  352. od.SyncMethod = mi;
  353. od.IsInitiating = oca.IsInitiating;
  354. od.IsTerminating = oca.IsTerminating;
  355. if (mi != serviceMethod)
  356. foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true))
  357. od.Behaviors.Add ((IOperationBehavior) obj);
  358. if (serviceMethod != null) {
  359. foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true))
  360. od.Behaviors.Add ((IOperationBehavior) obj);
  361. }
  362. #if !NET_2_1
  363. if (od.Behaviors.Find<OperationBehaviorAttribute>() == null)
  364. od.Behaviors.Add (new OperationBehaviorAttribute ());
  365. #endif
  366. // FIXME: fill KnownTypes, Behaviors and Faults.
  367. if (isCallback)
  368. od.InCallbackContract = true;
  369. else
  370. od.InOrdinalContract = true;
  371. return od;
  372. }
  373. static bool HasInvalidMessageContract (MethodInfo mi, bool async)
  374. {
  375. var pars = mi.GetParameters ();
  376. if (async) {
  377. if (pars.Length > 3) {
  378. if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
  379. return true;
  380. }
  381. } else {
  382. if (pars.Length > 1) {
  383. if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null))
  384. return true;
  385. }
  386. }
  387. return false;
  388. }
  389. static MessageDescription GetMessage (
  390. OperationDescription od, MethodInfo mi,
  391. OperationContractAttribute oca, bool isRequest,
  392. bool isCallback, Type asyncReturnType)
  393. {
  394. ContractDescription cd = od.DeclaringContract;
  395. ParameterInfo [] plist = mi.GetParameters ();
  396. Type messageType = null;
  397. string action = isRequest ? oca.Action : oca.ReplyAction;
  398. MessageContractAttribute mca;
  399. Type retType = asyncReturnType;
  400. if (!isRequest && retType == null)
  401. retType = mi.ReturnType;
  402. // If the argument is only one and has [MessageContract]
  403. // then infer it as a typed messsage
  404. if (isRequest) {
  405. int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1;
  406. mca = plist.Length != len ? null :
  407. GetMessageContractAttribute (plist [0].ParameterType);
  408. if (mca != null)
  409. messageType = plist [0].ParameterType;
  410. }
  411. else {
  412. mca = GetMessageContractAttribute (retType);
  413. if (mca != null)
  414. messageType = retType;
  415. }
  416. if (action == null)
  417. action = String.Concat (cd.Namespace,
  418. cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
  419. od.Name, isRequest ? String.Empty : "Response");
  420. MessageDescription md;
  421. if (mca != null)
  422. md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
  423. else
  424. md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
  425. // ReturnValue
  426. if (!isRequest) {
  427. MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
  428. mp.Index = 0;
  429. mp.Type = mca != null ? typeof (void) : retType;
  430. md.Body.ReturnValue = mp;
  431. }
  432. return md;
  433. }
  434. public static MessageDescription CreateMessageDescription (
  435. Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca)
  436. {
  437. MessageDescription md = new MessageDescription (action, isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output) { IsRequest = isRequest };
  438. md.MessageType = MessageFilterOutByRef (messageType);
  439. if (mca.HasProtectionLevel)
  440. md.ProtectionLevel = mca.ProtectionLevel;
  441. MessageBodyDescription mb = md.Body;
  442. if (mca.IsWrapped) {
  443. mb.WrapperName = mca.WrapperName ?? messageType.Name;
  444. mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace;
  445. }
  446. int index = 0;
  447. foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  448. Type mtype = null;
  449. string mname = null;
  450. if (bmi is FieldInfo) {
  451. FieldInfo fi = (FieldInfo) bmi;
  452. mtype = fi.FieldType;
  453. mname = fi.Name;
  454. }
  455. else if (bmi is PropertyInfo) {
  456. PropertyInfo pi = (PropertyInfo) bmi;
  457. mtype = pi.PropertyType;
  458. mname = pi.Name;
  459. }
  460. else
  461. continue;
  462. var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false);
  463. if (mha != null) {
  464. var pd = CreateHeaderDescription (mha, mname, defaultNamespace);
  465. pd.Type = MessageFilterOutByRef (mtype);
  466. pd.MemberInfo = bmi;
  467. md.Headers.Add (pd);
  468. }
  469. var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
  470. if (mpa != null) {
  471. var pd = new MessagePropertyDescription (mpa.Name ?? mname);
  472. pd.Type = MessageFilterOutByRef (mtype);
  473. pd.MemberInfo = bmi;
  474. md.Properties.Add (pd);
  475. }
  476. var mba = GetMessageBodyMemberAttribute (bmi);
  477. if (mba != null) {
  478. var pd = CreatePartCore (mba, mname, defaultNamespace);
  479. if (pd.Index <= 0)
  480. pd.Index = index++;
  481. pd.Type = MessageFilterOutByRef (mtype);
  482. pd.MemberInfo = bmi;
  483. mb.Parts.Add (pd);
  484. }
  485. }
  486. return md;
  487. }
  488. public static MessageDescription CreateMessageDescription (
  489. OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
  490. {
  491. var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
  492. MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
  493. MessageBodyDescription mb = md.Body;
  494. mb.WrapperName = name + (isRequest ? String.Empty : "Response");
  495. mb.WrapperNamespace = defaultNamespace;
  496. if (oca.HasProtectionLevel)
  497. md.ProtectionLevel = oca.ProtectionLevel;
  498. // Parts
  499. int index = 0;
  500. foreach (ParameterInfo pi in plist) {
  501. // AsyncCallback and state are extraneous.
  502. if (oca.AsyncPattern && pi.Position == plist.Length - 2)
  503. break;
  504. // They are ignored:
  505. // - out parameter in request
  506. // - neither out nor ref parameter in reply
  507. if (isRequest && pi.IsOut)
  508. continue;
  509. if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
  510. continue;
  511. MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace);
  512. pd.Index = index++;
  513. pd.Type = MessageFilterOutByRef (pi.ParameterType);
  514. mb.Parts.Add (pd);
  515. }
  516. return md;
  517. }
  518. // public static void FillMessageBodyDescriptionByContract (
  519. // Type messageType, MessageBodyDescription mb)
  520. // {
  521. // }
  522. static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace)
  523. {
  524. var ret = CreatePartCore<MessageHeaderDescription> (mha, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessageHeaderDescription (n, ns); });
  525. ret.Actor = mha.Actor;
  526. ret.MustUnderstand = mha.MustUnderstand;
  527. ret.Relay = mha.Relay;
  528. return ret;
  529. }
  530. static MessagePartDescription CreatePartCore (
  531. MessageParameterAttribute mpa, string defaultName,
  532. string defaultNamespace)
  533. {
  534. string pname = null;
  535. if (mpa != null && mpa.Name != null)
  536. pname = mpa.Name;
  537. if (pname == null)
  538. pname = defaultName;
  539. return new MessagePartDescription (pname, defaultNamespace);
  540. }
  541. static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace)
  542. {
  543. var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); });
  544. ret.Index = mba.Order;
  545. return ret;
  546. }
  547. static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator)
  548. {
  549. string pname = null, pns = null;
  550. if (mba != null) {
  551. if (mba.Name != null)
  552. pname = mba.Name;
  553. if (mba.Namespace != null)
  554. pns = mba.Namespace;
  555. }
  556. if (pname == null)
  557. pname = defaultName;
  558. if (pns == null)
  559. pns = defaultNamespace;
  560. return creator (pname, pns);
  561. }
  562. static Type MessageFilterOutByRef (Type type)
  563. {
  564. return type == null ? null :
  565. type.IsByRef ? type.GetElementType () : type;
  566. }
  567. static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider)
  568. {
  569. object [] attrs = provider.GetCustomAttributes (
  570. typeof (MessageParameterAttribute), true);
  571. return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null;
  572. }
  573. static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi)
  574. {
  575. object [] matts = mi.GetCustomAttributes (
  576. typeof (MessageBodyMemberAttribute), true);
  577. return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null;
  578. }
  579. }
  580. }