ServiceReflector.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Description
  5. {
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.Reflection;
  9. using System.Runtime;
  10. using System.ServiceModel;
  11. using System.Xml;
  12. using System.Threading.Tasks;
  13. using System.Threading;
  14. static class NamingHelper
  15. {
  16. internal const string DefaultNamespace = "http://tempuri.org/";
  17. internal const string DefaultServiceName = "service";
  18. internal const string MSNamespace = "http://schemas.microsoft.com/2005/07/ServiceModel";
  19. // simplified rules for appending paths to base URIs. note that this differs from new Uri(baseUri, string)
  20. // 1) CombineUriStrings("http://foo/bar/z", "baz") ==> "http://foo/bar/z/baz"
  21. // 2) CombineUriStrings("http://foo/bar/z/", "baz") ==> "http://foo/bar/z/baz"
  22. // 3) CombineUriStrings("http://foo/bar/z", "/baz") ==> "http://foo/bar/z/baz"
  23. // 4) CombineUriStrings("http://foo/bar/z", "http://baz/q") ==> "http://baz/q"
  24. // 5) CombineUriStrings("http://foo/bar/z", "") ==> ""
  25. internal static string CombineUriStrings(string baseUri, string path)
  26. {
  27. if (Uri.IsWellFormedUriString(path, UriKind.Absolute) || path == String.Empty)
  28. {
  29. return path;
  30. }
  31. else
  32. {
  33. // combine
  34. if (baseUri.EndsWith("/", StringComparison.Ordinal))
  35. {
  36. return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path.Substring(1) : path);
  37. }
  38. else
  39. {
  40. return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path : "/" + path);
  41. }
  42. }
  43. }
  44. internal static string TypeName(Type t)
  45. {
  46. if (t.IsGenericType || t.ContainsGenericParameters)
  47. {
  48. Type[] args = t.GetGenericArguments();
  49. int nameEnd = t.Name.IndexOf('`');
  50. string result = nameEnd > 0 ? t.Name.Substring(0, nameEnd) : t.Name;
  51. result += "Of";
  52. for (int i = 0; i < args.Length; ++i)
  53. {
  54. result = result + "_" + TypeName(args[i]);
  55. }
  56. return result;
  57. }
  58. else if (t.IsArray)
  59. {
  60. return "ArrayOf" + TypeName(t.GetElementType());
  61. }
  62. else
  63. {
  64. return t.Name;
  65. }
  66. }
  67. // name, ns could have any combination of nulls
  68. internal static XmlQualifiedName GetContractName(Type contractType, string name, string ns)
  69. {
  70. XmlName xmlName = new XmlName(name ?? TypeName(contractType));
  71. // ns can be empty
  72. if (ns == null)
  73. {
  74. ns = DefaultNamespace;
  75. }
  76. return new XmlQualifiedName(xmlName.EncodedName, ns);
  77. }
  78. // name could be null
  79. // logicalMethodName is MethodInfo.Name with Begin removed for async pattern
  80. // return encoded version to be used in OperationDescription
  81. internal static XmlName GetOperationName(string logicalMethodName, string name)
  82. {
  83. return new XmlName(String.IsNullOrEmpty(name) ? logicalMethodName : name);
  84. }
  85. internal static string GetMessageAction(OperationDescription operation, bool isResponse)
  86. {
  87. ContractDescription contract = operation.DeclaringContract;
  88. XmlQualifiedName contractQname = new XmlQualifiedName(contract.Name, contract.Namespace);
  89. return GetMessageAction(contractQname, operation.CodeName, null, isResponse);
  90. }
  91. // name could be null
  92. // logicalMethodName is MethodInfo.Name with Begin removed for async pattern
  93. internal static string GetMessageAction(XmlQualifiedName contractName, string opname, string action, bool isResponse)
  94. {
  95. if (action != null)
  96. {
  97. return action;
  98. }
  99. System.Text.StringBuilder actionBuilder = new System.Text.StringBuilder(64);
  100. if (String.IsNullOrEmpty(contractName.Namespace))
  101. {
  102. actionBuilder.Append("urn:");
  103. }
  104. else
  105. {
  106. actionBuilder.Append(contractName.Namespace);
  107. if (!contractName.Namespace.EndsWith("/", StringComparison.Ordinal))
  108. {
  109. actionBuilder.Append('/');
  110. }
  111. }
  112. actionBuilder.Append(contractName.Name);
  113. actionBuilder.Append('/');
  114. action = isResponse ? opname + "Response" : opname;
  115. return CombineUriStrings(actionBuilder.ToString(), action);
  116. }
  117. internal delegate bool DoesNameExist(string name, object nameCollection);
  118. internal static string GetUniqueName(string baseName, DoesNameExist doesNameExist, object nameCollection)
  119. {
  120. for (int i = 0; i < Int32.MaxValue; i++)
  121. {
  122. string name = i > 0 ? baseName + i : baseName;
  123. if (!doesNameExist(name, nameCollection))
  124. {
  125. return name;
  126. }
  127. }
  128. Fx.Assert("Too Many Names");
  129. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Cannot generate unique name for name {0}", baseName)));
  130. }
  131. internal static void CheckUriProperty(string ns, string propName)
  132. {
  133. Uri uri;
  134. if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri))
  135. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFXUnvalidNamespaceValue, ns, propName));
  136. }
  137. internal static void CheckUriParameter(string ns, string paramName)
  138. {
  139. Uri uri;
  140. if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri))
  141. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(paramName, SR.GetString(SR.SFXUnvalidNamespaceParam, ns));
  142. }
  143. // Converts names that contain characters that are not permitted in XML names to valid names.
  144. internal static string XmlName(string name)
  145. {
  146. if (string.IsNullOrEmpty(name))
  147. return name;
  148. if (IsAsciiLocalName(name))
  149. return name;
  150. if (IsValidNCName(name))
  151. return name;
  152. return XmlConvert.EncodeLocalName(name);
  153. }
  154. // Transforms an XML name into an object name.
  155. internal static string CodeName(string name)
  156. {
  157. return XmlConvert.DecodeName(name);
  158. }
  159. static bool IsAlpha(char ch)
  160. {
  161. return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z');
  162. }
  163. static bool IsDigit(char ch)
  164. {
  165. return (ch >= '0' && ch <= '9');
  166. }
  167. static bool IsAsciiLocalName(string localName)
  168. {
  169. Fx.Assert(null != localName, "");
  170. if (!IsAlpha(localName[0]))
  171. return false;
  172. for (int i = 1; i < localName.Length; i++)
  173. {
  174. char ch = localName[i];
  175. if (!IsAlpha(ch) && !IsDigit(ch))
  176. return false;
  177. }
  178. return true;
  179. }
  180. internal static bool IsValidNCName(string name)
  181. {
  182. try
  183. {
  184. XmlConvert.VerifyNCName(name);
  185. return true;
  186. }
  187. catch (XmlException)
  188. {
  189. return false;
  190. }
  191. }
  192. }
  193. internal class XmlName
  194. {
  195. string decoded;
  196. string encoded;
  197. internal XmlName(string name)
  198. : this(name, false)
  199. {
  200. }
  201. internal XmlName(string name, bool isEncoded)
  202. {
  203. if (isEncoded)
  204. {
  205. ValidateEncodedName(name, true /*allowNull*/);
  206. encoded = name;
  207. }
  208. else
  209. {
  210. decoded = name;
  211. }
  212. }
  213. internal string EncodedName
  214. {
  215. get
  216. {
  217. if (encoded == null)
  218. encoded = NamingHelper.XmlName(decoded);
  219. return encoded;
  220. }
  221. }
  222. internal string DecodedName
  223. {
  224. get
  225. {
  226. if (decoded == null)
  227. decoded = NamingHelper.CodeName(encoded);
  228. return decoded;
  229. }
  230. }
  231. static void ValidateEncodedName(string name, bool allowNull)
  232. {
  233. if (allowNull && name == null)
  234. return;
  235. try
  236. {
  237. XmlConvert.VerifyNCName(name);
  238. }
  239. catch (XmlException e)
  240. {
  241. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(e.Message, "name"));
  242. }
  243. }
  244. bool IsEmpty { get { return string.IsNullOrEmpty(encoded) && string.IsNullOrEmpty(decoded); } }
  245. internal static bool IsNullOrEmpty(XmlName xmlName)
  246. {
  247. return xmlName == null || xmlName.IsEmpty;
  248. }
  249. bool Matches(XmlName xmlName)
  250. {
  251. return string.Equals(this.EncodedName, xmlName.EncodedName, StringComparison.Ordinal);
  252. }
  253. public override bool Equals(object obj)
  254. {
  255. if (object.ReferenceEquals(obj, this))
  256. {
  257. return true;
  258. }
  259. if (object.ReferenceEquals(obj, null))
  260. {
  261. return false;
  262. }
  263. XmlName xmlName = obj as XmlName;
  264. if (xmlName == null)
  265. {
  266. return false;
  267. }
  268. return Matches(xmlName);
  269. }
  270. public override int GetHashCode()
  271. {
  272. if (string.IsNullOrEmpty(EncodedName))
  273. return 0;
  274. return EncodedName.GetHashCode();
  275. }
  276. public override string ToString()
  277. {
  278. if (encoded == null && decoded == null)
  279. return null;
  280. if (encoded != null)
  281. return encoded;
  282. return decoded;
  283. }
  284. public static bool operator ==(XmlName a, XmlName b)
  285. {
  286. if (object.ReferenceEquals(a, null))
  287. {
  288. return object.ReferenceEquals(b, null);
  289. }
  290. return (a.Equals(b));
  291. }
  292. public static bool operator !=(XmlName a, XmlName b)
  293. {
  294. return !(a == b);
  295. }
  296. }
  297. static internal class ServiceReflector
  298. {
  299. internal const BindingFlags ServiceModelBindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
  300. internal const string BeginMethodNamePrefix = "Begin";
  301. internal const string EndMethodNamePrefix = "End";
  302. internal static readonly Type VoidType = typeof(void);
  303. internal const string AsyncMethodNameSuffix = "Async";
  304. internal static readonly Type taskType = typeof(Task);
  305. internal static readonly Type taskTResultType = typeof(Task<>);
  306. internal static readonly Type CancellationTokenType = typeof(CancellationToken);
  307. internal static readonly Type IProgressType = typeof(IProgress<>);
  308. static readonly Type asyncCallbackType = typeof(AsyncCallback);
  309. static readonly Type asyncResultType = typeof(IAsyncResult);
  310. static readonly Type objectType = typeof(object);
  311. static readonly Type OperationContractAttributeType = typeof(OperationContractAttribute);
  312. static internal Type GetOperationContractProviderType(MethodInfo method)
  313. {
  314. if (GetSingleAttribute<OperationContractAttribute>(method) != null)
  315. {
  316. return OperationContractAttributeType;
  317. }
  318. IOperationContractAttributeProvider provider = GetFirstAttribute<IOperationContractAttributeProvider>(method);
  319. if (provider != null)
  320. {
  321. return provider.GetType();
  322. }
  323. return null;
  324. }
  325. // returns the set of root interfaces for the service class (meaning doesn't include callback ifaces)
  326. static internal List<Type> GetInterfaces(Type service)
  327. {
  328. List<Type> types = new List<Type>();
  329. bool implicitContract = false;
  330. if (service.IsDefined(typeof(ServiceContractAttribute), false))
  331. {
  332. implicitContract = true;
  333. types.Add(service);
  334. }
  335. if (!implicitContract)
  336. {
  337. Type t = GetAncestorImplicitContractClass(service);
  338. if (t != null)
  339. {
  340. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxContractInheritanceRequiresInterfaces2, service, t)));
  341. }
  342. foreach (MethodInfo method in GetMethodsInternal(service))
  343. {
  344. Type operationContractProviderType = GetOperationContractProviderType(method);
  345. if (operationContractProviderType == OperationContractAttributeType)
  346. {
  347. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ServicesWithoutAServiceContractAttributeCan2, operationContractProviderType.Name, method.Name, service.FullName)));
  348. }
  349. }
  350. }
  351. foreach (Type t in service.GetInterfaces())
  352. {
  353. if (t.IsDefined(typeof(ServiceContractAttribute), false))
  354. {
  355. if (implicitContract)
  356. {
  357. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxContractInheritanceRequiresInterfaces, service, t)));
  358. }
  359. types.Add(t);
  360. }
  361. }
  362. return types;
  363. }
  364. static Type GetAncestorImplicitContractClass(Type service)
  365. {
  366. for (service = service.BaseType; service != null; service = service.BaseType)
  367. {
  368. if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null)
  369. {
  370. return service;
  371. }
  372. }
  373. return null;
  374. }
  375. static internal List<Type> GetInheritedContractTypes(Type service)
  376. {
  377. List<Type> types = new List<Type>();
  378. foreach (Type t in service.GetInterfaces())
  379. {
  380. if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(t) != null)
  381. {
  382. types.Add(t);
  383. }
  384. }
  385. for (service = service.BaseType; service != null; service = service.BaseType)
  386. {
  387. if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null)
  388. {
  389. types.Add(service);
  390. }
  391. }
  392. return types;
  393. }
  394. static internal object[] GetCustomAttributes(ICustomAttributeProvider attrProvider, Type attrType)
  395. {
  396. return GetCustomAttributes(attrProvider, attrType, false);
  397. }
  398. static internal object[] GetCustomAttributes(ICustomAttributeProvider attrProvider, Type attrType, bool inherit)
  399. {
  400. try
  401. {
  402. return attrProvider.GetCustomAttributes(attrType, inherit);
  403. }
  404. catch (Exception e)
  405. {
  406. if (Fx.IsFatal(e))
  407. {
  408. throw;
  409. }
  410. // where the exception is CustomAttributeFormatException and the InnerException is a TargetInvocationException,
  411. // drill into the InnerException as this will provide a better error experience (fewer nested InnerExceptions)
  412. if (e is CustomAttributeFormatException && e.InnerException != null)
  413. {
  414. e = e.InnerException;
  415. if (e is TargetInvocationException && e.InnerException != null)
  416. {
  417. e = e.InnerException;
  418. }
  419. }
  420. Type type = attrProvider as Type;
  421. MethodInfo method = attrProvider as MethodInfo;
  422. ParameterInfo param = attrProvider as ParameterInfo;
  423. // there is no good way to know if this is a return type attribute
  424. if (type != null)
  425. {
  426. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  427. SR.GetString(SR.SFxErrorReflectingOnType2, attrType.Name, type.Name), e));
  428. }
  429. else if (method != null)
  430. {
  431. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  432. SR.GetString(SR.SFxErrorReflectingOnMethod3,
  433. attrType.Name, method.Name, method.ReflectedType.Name), e));
  434. }
  435. else if (param != null)
  436. {
  437. method = param.Member as MethodInfo;
  438. if (method != null)
  439. {
  440. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  441. SR.GetString(SR.SFxErrorReflectingOnParameter4,
  442. attrType.Name, param.Name, method.Name, method.ReflectedType.Name), e));
  443. }
  444. }
  445. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  446. SR.GetString(SR.SFxErrorReflectionOnUnknown1, attrType.Name), e));
  447. }
  448. }
  449. static internal T GetFirstAttribute<T>(ICustomAttributeProvider attrProvider)
  450. where T : class
  451. {
  452. Type attrType = typeof(T);
  453. object[] attrs = GetCustomAttributes(attrProvider, attrType);
  454. if (attrs.Length == 0)
  455. {
  456. return null;
  457. }
  458. else
  459. {
  460. return attrs[0] as T;
  461. }
  462. }
  463. #if !NO_GENERIC
  464. static internal T GetSingleAttribute<T>(ICustomAttributeProvider attrProvider)
  465. where T : class
  466. {
  467. Type attrType = typeof(T);
  468. object[] attrs = GetCustomAttributes(attrProvider, attrType);
  469. if (attrs.Length == 0)
  470. {
  471. return null;
  472. }
  473. else if (attrs.Length > 1)
  474. {
  475. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.tooManyAttributesOfTypeOn2, attrType, attrProvider.ToString())));
  476. }
  477. else
  478. {
  479. return attrs[0] as T;
  480. }
  481. }
  482. #else
  483. static internal object GetSingleAttribute(Type attrType, ICustomAttributeProvider attrProvider)
  484. {
  485. object[] attrs = GetCustomAttributes(attrProvider, attrType);
  486. if (attrs.Length == 0)
  487. {
  488. return null;
  489. }
  490. else if (attrs.Length > 1)
  491. {
  492. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.tooManyAttributesOfTypeOn2, attrType, attrProvider.ToString())));
  493. }
  494. else
  495. {
  496. return attrs[0];
  497. }
  498. }
  499. #endif
  500. #if !NO_GENERIC
  501. static internal T GetRequiredSingleAttribute<T>(ICustomAttributeProvider attrProvider)
  502. where T : class
  503. {
  504. T result = GetSingleAttribute<T>(attrProvider);
  505. if (result == null)
  506. {
  507. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString())));
  508. }
  509. return result;
  510. }
  511. #else
  512. static internal object GetRequiredSingleAttribute(Type attrType, ICustomAttributeProvider attrProvider)
  513. {
  514. object result = GetSingleAttribute(attrType, attrProvider);
  515. if (result == null)
  516. {
  517. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.couldnTFindRequiredAttributeOfTypeOn2, attrType, attrProvider.ToString())));
  518. }
  519. return result;
  520. }
  521. #endif
  522. #if !NO_GENERIC
  523. static internal T GetSingleAttribute<T>(ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
  524. where T : class
  525. {
  526. T result = GetSingleAttribute<T>(attrProvider);
  527. if (result != null)
  528. {
  529. Type attrType = typeof(T);
  530. foreach (Type otherType in attrTypeGroup)
  531. {
  532. if (otherType == attrType)
  533. {
  534. continue;
  535. }
  536. object[] attrs = GetCustomAttributes(attrProvider, otherType);
  537. if (attrs != null && attrs.Length > 0)
  538. {
  539. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxDisallowedAttributeCombination, attrProvider, attrType.FullName, otherType.FullName)));
  540. }
  541. }
  542. }
  543. return result;
  544. }
  545. #else
  546. static internal object GetSingleAttribute(Type attrType, ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
  547. {
  548. object result = GetSingleAttribute(attrType, attrProvider);
  549. if (result != null)
  550. {
  551. foreach (Type otherType in attrTypeGroup)
  552. {
  553. if (otherType == attrType)
  554. {
  555. continue;
  556. }
  557. object[] attrs = GetCustomAttributes(attrProvider, otherType);
  558. if (attrs != null && attrs.Length > 0)
  559. {
  560. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxDisallowedAttributeCombination, attrProvider, attrType.FullName, otherType.FullName)));
  561. }
  562. }
  563. }
  564. return result;
  565. }
  566. #endif
  567. #if !NO_GENERIC
  568. static internal T GetRequiredSingleAttribute<T>(ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
  569. where T : class
  570. {
  571. T result = GetSingleAttribute<T>(attrProvider, attrTypeGroup);
  572. if (result == null)
  573. {
  574. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString())));
  575. }
  576. return result;
  577. }
  578. #else
  579. static internal object GetRequiredSingleAttribute(Type attrType, ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
  580. {
  581. object result = GetSingleAttribute(attrType, attrProvider, attrTypeGroup);
  582. if (result == null)
  583. {
  584. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.couldnTFindRequiredAttributeOfTypeOn2, attrType, attrProvider.ToString())));
  585. }
  586. return result;
  587. }
  588. #endif
  589. static internal Type GetContractType(Type interfaceType)
  590. {
  591. ServiceContractAttribute contractAttribute;
  592. return GetContractTypeAndAttribute(interfaceType, out contractAttribute);
  593. }
  594. static internal Type GetContractTypeAndAttribute(Type interfaceType, out ServiceContractAttribute contractAttribute)
  595. {
  596. contractAttribute = GetSingleAttribute<ServiceContractAttribute>(interfaceType);
  597. if (contractAttribute != null)
  598. {
  599. return interfaceType;
  600. }
  601. List<Type> types = new List<Type>(GetInheritedContractTypes(interfaceType));
  602. if (types.Count == 0)
  603. {
  604. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.AttemptedToGetContractTypeForButThatTypeIs1, interfaceType.Name)));
  605. }
  606. foreach (Type potentialContractRoot in types)
  607. {
  608. bool mayBeTheRoot = true;
  609. foreach (Type t in types)
  610. {
  611. if (!t.IsAssignableFrom(potentialContractRoot))
  612. {
  613. mayBeTheRoot = false;
  614. }
  615. }
  616. if (mayBeTheRoot)
  617. {
  618. contractAttribute = GetSingleAttribute<ServiceContractAttribute>(potentialContractRoot);
  619. return potentialContractRoot;
  620. }
  621. }
  622. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  623. SR.GetString(SR.SFxNoMostDerivedContract, interfaceType.Name)));
  624. }
  625. static List<MethodInfo> GetMethodsInternal(Type interfaceType)
  626. {
  627. List<MethodInfo> methods = new List<MethodInfo>();
  628. foreach (MethodInfo mi in interfaceType.GetMethods(ServiceModelBindingFlags))
  629. {
  630. if (GetSingleAttribute<OperationContractAttribute>(mi) != null)
  631. {
  632. methods.Add(mi);
  633. }
  634. else if (GetFirstAttribute<IOperationContractAttributeProvider>(mi) != null)
  635. {
  636. methods.Add(mi);
  637. }
  638. }
  639. return methods;
  640. }
  641. // The metadata for "in" versus "out" seems to be inconsistent, depending upon what compiler generates it.
  642. // The following code assumes this is the truth table that all compilers will obey:
  643. //
  644. // True Parameter Type .IsIn .IsOut .ParameterType.IsByRef
  645. //
  646. // in F F F ...OR...
  647. // in T F F
  648. //
  649. // in/out T T T ...OR...
  650. // in/out F F T
  651. //
  652. // out F T T
  653. static internal void ValidateParameterMetadata(MethodInfo methodInfo)
  654. {
  655. ParameterInfo[] parameters = methodInfo.GetParameters();
  656. foreach (ParameterInfo parameter in parameters)
  657. {
  658. if (!parameter.ParameterType.IsByRef)
  659. {
  660. if (parameter.IsOut)
  661. {
  662. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  663. new InvalidOperationException(SR.GetString(SR.SFxBadByValueParameterMetadata,
  664. methodInfo.Name, methodInfo.DeclaringType.Name)));
  665. }
  666. }
  667. else
  668. {
  669. if (parameter.IsIn && !parameter.IsOut)
  670. {
  671. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  672. new InvalidOperationException(SR.GetString(SR.SFxBadByReferenceParameterMetadata,
  673. methodInfo.Name, methodInfo.DeclaringType.Name)));
  674. }
  675. }
  676. }
  677. }
  678. static internal bool FlowsIn(ParameterInfo paramInfo) // conceptually both "in" and "in/out" params return true
  679. {
  680. return !paramInfo.IsOut || paramInfo.IsIn;
  681. }
  682. static internal bool FlowsOut(ParameterInfo paramInfo) // conceptually both "out" and "in/out" params return true
  683. {
  684. return paramInfo.ParameterType.IsByRef;
  685. }
  686. // for async method is the begin method
  687. static internal ParameterInfo[] GetInputParameters(MethodInfo method, bool asyncPattern)
  688. {
  689. int count = 0;
  690. ParameterInfo[] parameters = method.GetParameters();
  691. // length of parameters we care about (-2 for async)
  692. int len = parameters.Length;
  693. if (asyncPattern)
  694. {
  695. len -= 2;
  696. }
  697. // count the ins
  698. for (int i = 0; i < len; i++)
  699. {
  700. if (FlowsIn(parameters[i]))
  701. {
  702. count++;
  703. }
  704. }
  705. // grab the ins
  706. ParameterInfo[] result = new ParameterInfo[count];
  707. int pos = 0;
  708. for (int i = 0; i < len; i++)
  709. {
  710. ParameterInfo param = parameters[i];
  711. if (FlowsIn(param))
  712. {
  713. result[pos++] = param;
  714. }
  715. }
  716. return result;
  717. }
  718. // for async method is the end method
  719. static internal ParameterInfo[] GetOutputParameters(MethodInfo method, bool asyncPattern)
  720. {
  721. int count = 0;
  722. ParameterInfo[] parameters = method.GetParameters();
  723. // length of parameters we care about (-1 for async)
  724. int len = parameters.Length;
  725. if (asyncPattern)
  726. {
  727. len -= 1;
  728. }
  729. // count the outs
  730. for (int i = 0; i < len; i++)
  731. {
  732. if (FlowsOut(parameters[i]))
  733. {
  734. count++;
  735. }
  736. }
  737. // grab the outs
  738. ParameterInfo[] result = new ParameterInfo[count];
  739. int pos = 0;
  740. for (int i = 0; i < len; i++)
  741. {
  742. ParameterInfo param = parameters[i];
  743. if (FlowsOut(param))
  744. {
  745. result[pos++] = param;
  746. }
  747. }
  748. return result;
  749. }
  750. static internal bool HasOutputParameters(MethodInfo method, bool asyncPattern)
  751. {
  752. ParameterInfo[] parameters = method.GetParameters();
  753. // length of parameters we care about (-1 for async)
  754. int len = parameters.Length;
  755. if (asyncPattern)
  756. {
  757. len -= 1;
  758. }
  759. // count the outs
  760. for (int i = 0; i < len; i++)
  761. {
  762. if (FlowsOut(parameters[i]))
  763. {
  764. return true;
  765. }
  766. }
  767. return false;
  768. }
  769. static MethodInfo GetEndMethodInternal(MethodInfo beginMethod)
  770. {
  771. string logicalName = GetLogicalName(beginMethod);
  772. string endMethodName = EndMethodNamePrefix + logicalName;
  773. MemberInfo[] endMethods = beginMethod.DeclaringType.GetMember(endMethodName, ServiceModelBindingFlags);
  774. if (endMethods.Length == 0)
  775. {
  776. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName)));
  777. }
  778. if (endMethods.Length > 1)
  779. {
  780. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MoreThanOneEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName)));
  781. }
  782. return (MethodInfo)endMethods[0];
  783. }
  784. static internal MethodInfo GetEndMethod(MethodInfo beginMethod)
  785. {
  786. MethodInfo endMethod = GetEndMethodInternal(beginMethod);
  787. if (!HasEndMethodShape(endMethod))
  788. {
  789. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidAsyncEndMethodSignatureForMethod2, endMethod.Name, endMethod.DeclaringType.FullName)));
  790. }
  791. return endMethod;
  792. }
  793. static internal XmlName GetOperationName(MethodInfo method)
  794. {
  795. OperationContractAttribute operationAttribute = GetOperationContractAttribute(method);
  796. return NamingHelper.GetOperationName(GetLogicalName(method), operationAttribute.Name);
  797. }
  798. static internal bool HasBeginMethodShape(MethodInfo method)
  799. {
  800. ParameterInfo[] parameters = method.GetParameters();
  801. if (!method.Name.StartsWith(BeginMethodNamePrefix, StringComparison.Ordinal) ||
  802. parameters.Length < 2 ||
  803. parameters[parameters.Length - 2].ParameterType != asyncCallbackType ||
  804. parameters[parameters.Length - 1].ParameterType != objectType ||
  805. method.ReturnType != asyncResultType)
  806. {
  807. return false;
  808. }
  809. return true;
  810. }
  811. static internal bool IsBegin(OperationContractAttribute opSettings, MethodInfo method)
  812. {
  813. if (opSettings.AsyncPattern)
  814. {
  815. if (!HasBeginMethodShape(method))
  816. {
  817. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidAsyncBeginMethodSignatureForMethod2, method.Name, method.DeclaringType.FullName)));
  818. }
  819. return true;
  820. }
  821. return false;
  822. }
  823. static internal bool IsTask(MethodInfo method)
  824. {
  825. if (method.ReturnType == taskType)
  826. {
  827. return true;
  828. }
  829. if (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == taskTResultType)
  830. {
  831. return true;
  832. }
  833. return false;
  834. }
  835. static internal bool IsTask(MethodInfo method, out Type taskTResult)
  836. {
  837. taskTResult = null;
  838. Type methodReturnType = method.ReturnType;
  839. if (methodReturnType == taskType)
  840. {
  841. taskTResult = VoidType;
  842. return true;
  843. }
  844. if (methodReturnType.IsGenericType && methodReturnType.GetGenericTypeDefinition() == taskTResultType)
  845. {
  846. taskTResult = methodReturnType.GetGenericArguments()[0];
  847. return true;
  848. }
  849. return false;
  850. }
  851. static internal bool HasEndMethodShape(MethodInfo method)
  852. {
  853. ParameterInfo[] parameters = method.GetParameters();
  854. if (!method.Name.StartsWith(EndMethodNamePrefix, StringComparison.Ordinal) ||
  855. parameters.Length < 1 ||
  856. parameters[parameters.Length - 1].ParameterType != asyncResultType)
  857. {
  858. return false;
  859. }
  860. return true;
  861. }
  862. internal static OperationContractAttribute GetOperationContractAttribute(MethodInfo method)
  863. {
  864. OperationContractAttribute operationContractAttribute = GetSingleAttribute<OperationContractAttribute>(method);
  865. if (operationContractAttribute != null)
  866. {
  867. return operationContractAttribute;
  868. }
  869. IOperationContractAttributeProvider operationContractProvider = GetFirstAttribute<IOperationContractAttributeProvider>(method);
  870. if (operationContractProvider != null)
  871. {
  872. return operationContractProvider.GetOperationContractAttribute();
  873. }
  874. return null;
  875. }
  876. static internal bool IsBegin(MethodInfo method)
  877. {
  878. OperationContractAttribute opSettings = GetOperationContractAttribute(method);
  879. if (opSettings == null)
  880. return false;
  881. return IsBegin(opSettings, method);
  882. }
  883. static internal string GetLogicalName(MethodInfo method)
  884. {
  885. bool isAsync = IsBegin(method);
  886. bool isTask = isAsync ? false : IsTask(method);
  887. return GetLogicalName(method, isAsync, isTask);
  888. }
  889. static internal string GetLogicalName(MethodInfo method, bool isAsync, bool isTask)
  890. {
  891. if (isAsync)
  892. {
  893. return method.Name.Substring(BeginMethodNamePrefix.Length);
  894. }
  895. else if (isTask && method.Name.EndsWith(AsyncMethodNameSuffix, StringComparison.Ordinal))
  896. {
  897. return method.Name.Substring(0, method.Name.Length - AsyncMethodNameSuffix.Length);
  898. }
  899. else
  900. {
  901. return method.Name;
  902. }
  903. }
  904. static internal bool HasNoDisposableParameters(MethodInfo methodInfo)
  905. {
  906. foreach (ParameterInfo inputInfo in methodInfo.GetParameters())
  907. {
  908. if (IsParameterDisposable(inputInfo.ParameterType))
  909. {
  910. return false;
  911. }
  912. }
  913. if (methodInfo.ReturnParameter != null)
  914. {
  915. return (!IsParameterDisposable(methodInfo.ReturnParameter.ParameterType));
  916. }
  917. return true;
  918. }
  919. static internal bool IsParameterDisposable(Type type)
  920. {
  921. return ((!type.IsSealed) || typeof(IDisposable).IsAssignableFrom(type));
  922. }
  923. }
  924. }