PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/TechEdWebApiDemo/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs

https://github.com/garchibald/TechEdWebApiDemo
C# | 373 lines | 267 code | 30 blank | 76 comment | 38 complexity | 5f7dcf31b684e421aedba8d70c9a9b10 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.Http;
  10. using System.Net.Http.Formatting;
  11. using System.Net.Http.Headers;
  12. using System.Web.Http.Description;
  13. using System.Xml.Linq;
  14. using Newtonsoft.Json;
  15. namespace TechEdWebApiDemo.Areas.HelpPage
  16. {
  17. /// <summary>
  18. /// This class will generate the samples for the help page.
  19. /// </summary>
  20. public class HelpPageSampleGenerator
  21. {
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
  24. /// </summary>
  25. public HelpPageSampleGenerator()
  26. {
  27. ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
  28. ActionSamples = new Dictionary<HelpPageSampleKey, object>();
  29. SampleObjects = new Dictionary<Type, object>();
  30. }
  31. /// <summary>
  32. /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
  33. /// </summary>
  34. public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
  35. /// <summary>
  36. /// Gets the objects that are used directly as samples for certain actions.
  37. /// </summary>
  38. public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
  39. /// <summary>
  40. /// Gets the objects that are serialized as samples by the supported formatters.
  41. /// </summary>
  42. public IDictionary<Type, object> SampleObjects { get; internal set; }
  43. /// <summary>
  44. /// Gets the request body samples for a given <see cref="ApiDescription"/>.
  45. /// </summary>
  46. /// <param name="api">The <see cref="ApiDescription"/>.</param>
  47. /// <returns>The samples keyed by media type.</returns>
  48. public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
  49. {
  50. return GetSample(api, SampleDirection.Request);
  51. }
  52. /// <summary>
  53. /// Gets the response body samples for a given <see cref="ApiDescription"/>.
  54. /// </summary>
  55. /// <param name="api">The <see cref="ApiDescription"/>.</param>
  56. /// <returns>The samples keyed by media type.</returns>
  57. public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
  58. {
  59. return GetSample(api, SampleDirection.Response);
  60. }
  61. /// <summary>
  62. /// Gets the request or response body samples.
  63. /// </summary>
  64. /// <param name="api">The <see cref="ApiDescription"/>.</param>
  65. /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
  66. /// <returns>The samples keyed by media type.</returns>
  67. public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
  68. {
  69. if (api == null)
  70. {
  71. throw new ArgumentNullException("api");
  72. }
  73. string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
  74. string actionName = api.ActionDescriptor.ActionName;
  75. IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
  76. Collection<MediaTypeFormatter> formatters;
  77. Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
  78. var samples = new Dictionary<MediaTypeHeaderValue, object>();
  79. // Use the samples provided directly for actions
  80. var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
  81. foreach (var actionSample in actionSamples)
  82. {
  83. samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
  84. }
  85. // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
  86. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
  87. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
  88. {
  89. object sampleObject = GetSampleObject(type);
  90. foreach (var formatter in formatters)
  91. {
  92. foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
  93. {
  94. if (!samples.ContainsKey(mediaType))
  95. {
  96. object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
  97. // If no sample found, try generate sample using formatter and sample object
  98. if (sample == null && sampleObject != null)
  99. {
  100. sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
  101. }
  102. samples.Add(mediaType, WrapSampleIfString(sample));
  103. }
  104. }
  105. }
  106. }
  107. return samples;
  108. }
  109. /// <summary>
  110. /// Search for samples that are provided directly through <see cref="ActionSamples"/>.
  111. /// </summary>
  112. /// <param name="controllerName">Name of the controller.</param>
  113. /// <param name="actionName">Name of the action.</param>
  114. /// <param name="parameterNames">The parameter names.</param>
  115. /// <param name="type">The CLR type.</param>
  116. /// <param name="formatter">The formatter.</param>
  117. /// <param name="mediaType">The media type.</param>
  118. /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
  119. /// <returns>The sample that matches the parameters.</returns>
  120. public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
  121. {
  122. object sample;
  123. // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
  124. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
  125. // If still not found, try get the sample provided for a specific type and mediaType
  126. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
  127. ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
  128. ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
  129. {
  130. return sample;
  131. }
  132. return null;
  133. }
  134. /// <summary>
  135. /// Gets the sample object that will be serialized by the formatters.
  136. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
  137. /// </summary>
  138. /// <param name="type">The type.</param>
  139. /// <returns>The sample object.</returns>
  140. public virtual object GetSampleObject(Type type)
  141. {
  142. object sampleObject;
  143. if (!SampleObjects.TryGetValue(type, out sampleObject))
  144. {
  145. // Try create a default sample object
  146. ObjectGenerator objectGenerator = new ObjectGenerator();
  147. sampleObject = objectGenerator.GenerateObject(type);
  148. }
  149. return sampleObject;
  150. }
  151. /// <summary>
  152. /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
  153. /// </summary>
  154. /// <param name="api">The <see cref="ApiDescription"/>.</param>
  155. /// <param name="controllerName">Name of the controller.</param>
  156. /// <param name="actionName">Name of the action.</param>
  157. /// <param name="parameterNames">The parameter names.</param>
  158. /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
  159. /// <param name="formatters">The formatters.</param>
  160. [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
  161. public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
  162. {
  163. if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
  164. {
  165. throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
  166. }
  167. if (api == null)
  168. {
  169. throw new ArgumentNullException("api");
  170. }
  171. Type type;
  172. if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
  173. ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
  174. {
  175. // Re-compute the supported formatters based on type
  176. Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
  177. foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
  178. {
  179. if (IsFormatSupported(sampleDirection, formatter, type))
  180. {
  181. newFormatters.Add(formatter);
  182. }
  183. }
  184. formatters = newFormatters;
  185. }
  186. else
  187. {
  188. switch (sampleDirection)
  189. {
  190. case SampleDirection.Request:
  191. ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
  192. type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
  193. formatters = api.SupportedRequestBodyFormatters;
  194. break;
  195. case SampleDirection.Response:
  196. default:
  197. type = api.ActionDescriptor.ReturnType;
  198. formatters = api.SupportedResponseFormatters;
  199. break;
  200. }
  201. }
  202. return type;
  203. }
  204. /// <summary>
  205. /// Writes the sample object using formatter.
  206. /// </summary>
  207. /// <param name="formatter">The formatter.</param>
  208. /// <param name="value">The value.</param>
  209. /// <param name="type">The type.</param>
  210. /// <param name="mediaType">Type of the media.</param>
  211. /// <returns></returns>
  212. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
  213. [SuppressMessage("Microsoft.WebAPI", "CR4001:DoNotCallProblematicMethodsOnTask", Justification = "The sample generation is done synchronously.")]
  214. public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
  215. {
  216. if (formatter == null)
  217. {
  218. throw new ArgumentNullException("formatter");
  219. }
  220. if (mediaType == null)
  221. {
  222. throw new ArgumentNullException("mediaType");
  223. }
  224. object sample = String.Empty;
  225. MemoryStream ms = null;
  226. HttpContent content = null;
  227. try
  228. {
  229. if (formatter.CanWriteType(type))
  230. {
  231. ms = new MemoryStream();
  232. content = new ObjectContent(type, value, formatter, mediaType);
  233. formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
  234. ms.Position = 0;
  235. StreamReader reader = new StreamReader(ms);
  236. string serializedSampleString = reader.ReadToEnd();
  237. if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
  238. {
  239. serializedSampleString = TryFormatXml(serializedSampleString);
  240. }
  241. else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
  242. {
  243. serializedSampleString = TryFormatJson(serializedSampleString);
  244. }
  245. sample = new TextSample(serializedSampleString);
  246. }
  247. else
  248. {
  249. sample = new InvalidSample(String.Format(
  250. CultureInfo.CurrentCulture,
  251. "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
  252. mediaType,
  253. formatter.GetType().Name,
  254. type.Name));
  255. }
  256. }
  257. catch (Exception e)
  258. {
  259. sample = new InvalidSample(String.Format(
  260. CultureInfo.CurrentCulture,
  261. "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
  262. formatter.GetType().Name,
  263. mediaType.MediaType,
  264. e.Message));
  265. }
  266. finally
  267. {
  268. if (ms != null)
  269. {
  270. ms.Dispose();
  271. }
  272. if (content != null)
  273. {
  274. content.Dispose();
  275. }
  276. }
  277. return sample;
  278. }
  279. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
  280. private static string TryFormatJson(string str)
  281. {
  282. try
  283. {
  284. object parsedJson = JsonConvert.DeserializeObject(str);
  285. return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
  286. }
  287. catch
  288. {
  289. // can't parse JSON, return the original string
  290. return str;
  291. }
  292. }
  293. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
  294. private static string TryFormatXml(string str)
  295. {
  296. try
  297. {
  298. XDocument xml = XDocument.Parse(str);
  299. return xml.ToString();
  300. }
  301. catch
  302. {
  303. // can't parse XML, return the original string
  304. return str;
  305. }
  306. }
  307. private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
  308. {
  309. switch (sampleDirection)
  310. {
  311. case SampleDirection.Request:
  312. return formatter.CanReadType(type);
  313. case SampleDirection.Response:
  314. return formatter.CanWriteType(type);
  315. }
  316. return false;
  317. }
  318. private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
  319. {
  320. HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
  321. foreach (var sample in ActionSamples)
  322. {
  323. HelpPageSampleKey sampleKey = sample.Key;
  324. if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
  325. String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
  326. (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
  327. sampleDirection == sampleKey.SampleDirection)
  328. {
  329. yield return sample;
  330. }
  331. }
  332. }
  333. private static object WrapSampleIfString(object sample)
  334. {
  335. string stringSample = sample as string;
  336. if (stringSample != null)
  337. {
  338. return new TextSample(stringSample);
  339. }
  340. return sample;
  341. }
  342. }
  343. }