Exemple #1
0
        public static Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> > GetRunnableClientSampleMethods(string area = null, string resource = null)
        {
            Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> > results = new Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> >();

            CompositionContainer container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            IEnumerable <Lazy <ClientSample> > samples = container.GetExports <ClientSample>();

            foreach (Lazy <ClientSample> cs in samples)
            {
                try
                {
                    Type csType = cs.Value.GetType();
                    ClientSampleAttribute csAttr = csType.GetCustomAttribute <ClientSampleAttribute>();

                    List <RunnableClientSampleMethod> runnableMethods = new List <RunnableClientSampleMethod>();

                    foreach (MethodInfo m in csType.GetMethods())
                    {
                        ClientSampleMethodAttribute[] attrs = (ClientSampleMethodAttribute[])m.GetCustomAttributes(typeof(ClientSampleMethodAttribute), false);
                        foreach (var ma in attrs)
                        {
                            RunnableClientSampleMethod runnableMethod = new RunnableClientSampleMethod();

                            if (string.IsNullOrEmpty(ma.Area))
                            {
                                runnableMethod.Area = csAttr.Area;
                            }
                            else
                            {
                                runnableMethod.Area = ma.Area;
                            }

                            if (string.IsNullOrEmpty(ma.Resource))
                            {
                                runnableMethod.Resource = csAttr.Resource;
                            }
                            else
                            {
                                runnableMethod.Resource = ma.Resource;
                            }

                            if (!string.IsNullOrEmpty(runnableMethod.Area) && !string.IsNullOrEmpty(runnableMethod.Resource))
                            {
                                runnableMethod.MethodBase = m;
                                runnableMethods.Add(runnableMethod);
                            }
                        }
                    }

                    if (runnableMethods.Any())
                    {
                        if (!String.IsNullOrEmpty(area))
                        {
                            runnableMethods = runnableMethods.FindAll(
                                rcsm =>
                            {
                                return(string.Equals(area, rcsm.Area, StringComparison.InvariantCultureIgnoreCase) &&
                                       (resource == null || string.Equals(resource, rcsm.Resource, StringComparison.InvariantCultureIgnoreCase)));
                            }
                                );
                        }

                        results.Add(cs.Value, runnableMethods);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }

            return(results);
        }
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);

            RunnableClientSampleMethod runnableMethod = ClientSampleContext.CurrentRunnableMethod;

            if (runnableMethod != null)
            {
                bool suppressOutput;
                if (!ClientSampleContext.CurrentContext.TryGetValue <bool>(PropertySuppressOutput, out suppressOutput))
                {
                    suppressOutput = false;
                }

                string operationName;
                if (!ClientSampleContext.CurrentContext.TryGetValue <string>(PropertyOperationName, out operationName))
                {
                    operationName = ClientSampleContext.CurrentRunnableMethod.MethodBase.Name;
                }
                else
                {
                    // TODO: add validation around the operation name
                }

                if (!suppressOutput)
                {
                    DirectoryInfo baseOutputPath;
                    if (ClientSampleContext.CurrentContext.TryGetValue <DirectoryInfo>(PropertyOutputFilePath, out baseOutputPath))
                    {
                        Dictionary <string, string> requestHeaders  = ProcessHeaders(request.Headers);
                        Dictionary <string, string> responseHeaders = ProcessHeaders(response.Headers);

                        dynamic requestBody = null;
                        try
                        {
                            string requestBodyString = await request.Content.ReadAsStringAsync();

                            if (!String.IsNullOrEmpty(requestBodyString))
                            {
                                requestBody = JValue.Parse(requestBodyString);
                            }
                        }
                        catch (Exception) { }

                        JObject responseBody = null;
                        try
                        {
                            if (IsJsonResponse(response))
                            {
                                string responseBodyString = await response.Content.ReadAsStringAsync();

                                responseBody = JObject.Parse(responseBodyString);
                            }
                        }
                        catch (Exception) { }

                        ApiResponseMetadata responseData = new ApiResponseMetadata()
                        {
                            Body    = responseBody,
                            Headers = responseHeaders
                        };

                        Dictionary <string, object> requestParameters = new Dictionary <string, object>();

                        // Add the request body (if there is one)
                        if (requestBody != null)
                        {
                            requestParameters["body"] = requestBody;
                        }

                        // Add query parameters (if any)
                        if (!String.IsNullOrEmpty(request.RequestUri.Query))
                        {
                            NameValueCollection queryParams = HttpUtility.ParseQueryString(request.RequestUri.Query);
                            foreach (string param in queryParams.Keys)
                            {
                                requestParameters[param] = queryParams[param];
                            }
                        }

                        // Add request headers
                        foreach (var rh in requestHeaders)
                        {
                            // Look for api-version
                            if (rh.Key.Equals("Accept") && rh.Value.Contains("api-version="))
                            {
                                int s = rh.Value.IndexOf("api-version=") + "api-version=".Length;
                                int e = rh.Value.IndexOf(';', s);
                                requestParameters.Add("api-version", e != -1 ? rh.Value.Substring(s, e) : rh.Value.Substring(s));
                            }
                            else
                            {
                                requestParameters.Add(rh.Key, rh.Value);
                            }
                        }

                        // Add sample account name if "account" parameter not already set
                        if (!requestParameters.ContainsKey("account"))
                        {
                            requestParameters["account"] = "fabrikam";
                        }

                        ApiRequestResponseMetdata data = new ApiRequestResponseMetdata()
                        {
                            Area       = runnableMethod.Area,
                            Resource   = runnableMethod.Resource,
                            HttpMethod = request.Method.ToString().ToUpperInvariant(),
                            RequestUrl = request.RequestUri.ToString(),
                            Parameters = requestParameters,
                            Responses  = new Dictionary <string, ApiResponseMetadata>()
                            {
                                { ((int)response.StatusCode).ToString(), responseData }
                            },
                            Generated     = true,
                            GeneratedDate = DateTime.Now
                        };

                        string outputPath     = Path.Combine(baseOutputPath.FullName, char.ToLower(data.Area[0]) + data.Area.Substring(1), char.ToLower(data.Resource[0]) + data.Resource.Substring(1));
                        string outputFileName = operationName + ".json";

                        DirectoryInfo outputDirectory = Directory.CreateDirectory(outputPath);

                        string outputFile = Path.Combine(outputDirectory.FullName, outputFileName);

                        string output = JsonConvert.SerializeObject(data, this.serializerSettings);

                        File.WriteAllText(outputFile, output);
                    }
                }
            }

            return(response);
        }