/// <summary>
        /// Make a HTTP PATCH request (synchronous).
        /// </summary>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>A Task containing ApiResponse</returns>
        public ApiResponse <T> Patch <T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
        {
            var config = configuration ?? GlobalConfiguration.Instance;

            return(Exec <T>(NewRequest(HttpMethod.Patch, path, options, config), config));
        }
 public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
 {
     _serializerSettings = serializerSettings;
     _configuration      = configuration;
 }
        /// <summary>
        /// Make a HTTP DELETE request (async).
        /// </summary>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>A Task containing ApiResponse</returns>
        public Task <ApiResponse <T> > DeleteAsync <T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
        {
            var config = configuration ?? GlobalConfiguration.Instance;

            return(ExecAsync <T>(NewRequest(HttpMethod.Delete, path, options, config), config));
        }
Exemple #4
0
        /// <summary>
        /// Merge configurations.
        /// </summary>
        /// <param name="first">First configuration.</param>
        /// <param name="second">Second configuration.</param>
        /// <return>Merged configuration.</return>
        public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second)
        {
            if (second == null)
            {
                return(first ?? GlobalConfiguration.Instance);
            }

            Dictionary <string, string> apiKey         = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            Dictionary <string, string> apiKeyPrefix   = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            Dictionary <string, string> defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            foreach (var kvp in second.ApiKey)
            {
                apiKey[kvp.Key] = kvp.Value;
            }
            foreach (var kvp in second.ApiKeyPrefix)
            {
                apiKeyPrefix[kvp.Key] = kvp.Value;
            }
            foreach (var kvp in second.DefaultHeaders)
            {
                defaultHeaders[kvp.Key] = kvp.Value;
            }

            var config = new Configuration
            {
                ApiKey         = apiKey,
                ApiKeyPrefix   = apiKeyPrefix,
                DefaultHeaders = defaultHeaders,
                BasePath       = second.BasePath ?? first.BasePath,
                Timeout        = second.Timeout,
                UserAgent      = second.UserAgent ?? first.UserAgent,
                Username       = second.Username ?? first.Username,
                Password       = second.Password ?? first.Password,
                AccessToken    = second.AccessToken ?? first.AccessToken,
                TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
                DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat
            };

            return(config);
        }
 public CustomJsonCodec(IReadableConfiguration configuration)
 {
     _configuration = configuration;
 }
Exemple #6
0
 public CustomJsonCodec(IReadableConfiguration configuration)
 {
     _configuration = configuration;
     _serializer    = JsonSerializer.Create(_serializerSettings);
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="InitiationApi" /> class
 ///     using a Configuration object and client instance.
 /// </summary>
 /// <param name="client">The client interface for synchronous API access.</param>
 /// <param name="asyncClient">The client interface for asynchronous API access.</param>
 /// <param name="configuration">The configuration object.</param>
 public InitiationApi(ISynchronousClient client, IAsynchronousClient asyncClient, IReadableConfiguration configuration)
 {
     this.Client             = client ?? throw new ArgumentNullException(nameof(client));
     this.AsynchronousClient = asyncClient ?? throw new ArgumentNullException(nameof(asyncClient));
     this.Configuration      = configuration ?? throw new ArgumentNullException(nameof(configuration));
     this.ExceptionFactory   = Core.Client.Configuration.DefaultExceptionFactory;
 }
Exemple #8
0
 private ApiResponse <T> Exec <T>(HttpRequestMessage req, IReadableConfiguration configuration)
 {
     return(ExecAsync <T>(req, configuration).GetAwaiter().GetResult());
 }
Exemple #9
0
        private async Task <ApiResponse <T> > ExecAsync <T>(HttpRequestMessage req,
                                                            IReadableConfiguration configuration,
                                                            System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var deserializer = new CustomJsonCodec(SerializerSettings, configuration);

            var finalToken = cancellationToken;

            if (configuration.Timeout > 0)
            {
                var tokenSource = new CancellationTokenSource(configuration.Timeout);
                finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token;
            }

            if (configuration.Proxy != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                _httpClientHandler.Proxy = configuration.Proxy;
            }

            if (configuration.ClientCertificates != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
            }

            var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List <Cookie> : null;

            if (cookieContainer != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                foreach (var cookie in cookieContainer)
                {
                    _httpClientHandler.CookieContainer.Add(cookie);
                }
            }

            InterceptRequest(req);

            HttpResponseMessage response;

            if (RetryConfiguration.AsyncRetryPolicy != null)
            {
                var policy       = RetryConfiguration.AsyncRetryPolicy;
                var policyResult = await policy
                                   .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken))
                                   .ConfigureAwait(false);

                response = (policyResult.Outcome == OutcomeType.Successful) ?
                           policyResult.Result : new HttpResponseMessage()
                {
                    ReasonPhrase   = policyResult.FinalException.ToString(),
                    RequestMessage = req
                };
            }
            else
            {
                response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false);
            }

            if (!response.IsSuccessStatusCode)
            {
                return(await ToApiResponse <T>(response, default(T), req.RequestUri));
            }

            object responseData = await deserializer.Deserialize <T>(response);

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                responseData = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
            }
            else if (typeof(T).Name == "Stream") // for binary response
            {
                responseData = (T)(object)await response.Content.ReadAsStreamAsync();
            }

            InterceptResponse(req, response);

            return(await ToApiResponse <T>(response, responseData, req.RequestUri));
        }
        private ApiResponse <T> Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            if (configuration.ClientCertificates != null)
            {
                client.ClientCertificates = configuration.ClientCertificates;
            }

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.RetryPolicy != null)
            {
                var policy       = RetryConfiguration.RetryPolicy;
                var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = client.Execute <T>(req);
            }

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                T          instance = (T)Activator.CreateInstance(typeof(T));
                MethodInfo method   = typeof(T).GetMethod("FromJson");
                method.Invoke(instance, new object[] { response.Content });
                response.Data = instance;
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Exemple #11
0
        /// <summary>
        /// Provides all logic for constructing a new HttpRequestMessage.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the a HttpRequestMessage.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new HttpRequestMessage instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private HttpRequestMessage NewRequest(
            HttpMethod method,
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path);

            builder.AddPathParameters(options.PathParameters);

            builder.AddQueryParameters(options.QueryParameters);

            HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri());

            if (configuration.UserAgent != null)
            {
                request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent);
            }

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.Headers.Add(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        // Todo make content headers actually content headers
                        request.Headers.TryAddWithoutValidation(headerParam.Key, value);
                    }
                }
            }

            List <Tuple <HttpContent, string, string> > contentList = new List <Tuple <HttpContent, string, string> >();

            string contentType = null;

            if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type"))
            {
                var contentTypes = options.HeaderParameters["Content-Type"];
                contentType = contentTypes.FirstOrDefault();
            }

            if (contentType == "multipart/form-data")
            {
                request.Content = PrepareMultipartFormDataContent(options);
            }
            else if (contentType == "application/x-www-form-urlencoded")
            {
                request.Content = new FormUrlEncodedContent(options.FormParameters);
            }
            else
            {
                if (options.Data != null)
                {
                    if (options.Data is FileParameter fp)
                    {
                        contentType = contentType ?? "application/octet-stream";

                        var streamContent = new StreamContent(fp.Content);
                        streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                        request.Content = streamContent;
                    }
                    else
                    {
                        var serializer = new CustomJsonCodec(SerializerSettings, configuration);
                        request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(),
                                                            "application/json");
                    }
                }
            }



            // TODO provide an alternative that allows cookies per request instead of per API client
            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                request.Properties["CookieContainer"] = options.Cookies;
            }

            return(request);
        }
Exemple #12
0
        /// <summary>
        /// Provides all logic for constructing a new Url <see cref="RestRequest"/>.
        /// At this point, all information for querying the service is known.
        /// </summary>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new RestRequest instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private Url NewUrl(
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            Url url = configuration.BasePath
                      .AppendPathSegments(path);

            if (options.QueryParameters != null)
            {
                foreach (var queryParam in options.QueryParameters)
                {
                    foreach (var value in queryParam.Value)
                    {
                        url.SetQueryParam(queryParam.Key, value);
                    }
                }
            }

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    url.WithHeader(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        url.WithHeader(headerParam.Key, value);
                    }
                }
            }

            if (configuration.UserAgent != null)
            {
                url.WithHeader("User-Agent", configuration.UserAgent);
            }

            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                foreach (var cookie in options.Cookies)
                {
                    url.WithCookie(cookie.Name, cookie.Value);
                }
            }

            url.WithTimeout(configuration.Timeout);

            return(url);
        }
 /// <summary>
 /// Make a HTTP PATCH request (synchronous).
 /// </summary>
 /// <param name="path">The target path (or resource).</param>
 /// <param name="options">The additional request options.</param>
 /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
 /// GlobalConfiguration has been done before calling this method.</param>
 /// <returns>A Task containing ApiResponse</returns>
 public ApiResponse <T> Patch <T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
 {
     return(PatchAsync <T>(path, options, configuration).Result);
 }
Exemple #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PetApi"/> class
        /// using a Configuration object and client instance.
        /// </summary>
        /// <param name="client">The client interface for synchronous API access.</param>
        /// <param name="asyncClient">The client interface for asynchronous API access.</param>
        /// <param name="configuration">The configuration object.</param>
        public ComplianceApi(ISynchronousClient client, IAsynchronousClient asyncClient, IReadableConfiguration configuration)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (asyncClient == null)
            {
                throw new ArgumentNullException("asyncClient");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.Client             = client;
            this.AsynchronousClient = asyncClient;
            this.Configuration      = configuration;
            this.ExceptionFactory   = Sdcb.Mattermost.DotNetSdk.Client.Configuration.DefaultExceptionFactory;
        }
Exemple #15
0
        /// <summary>
        /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the RestSharp request.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new RestRequest instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private RestRequest newRequest(
            HttpMethod method,
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            RestRequest request = new RestRequest(Method(method))
            {
                Resource       = path,
                JsonSerializer = new CustomJsonCodec(configuration)
            };

            if (options.PathParameters != null)
            {
                foreach (var pathParam in options.PathParameters)
                {
                    request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
                }
            }

            if (options.QueryParameters != null)
            {
                foreach (var queryParam in options.QueryParameters)
                {
                    foreach (var value in queryParam.Value)
                    {
                        request.AddQueryParameter(queryParam.Key, value);
                    }
                }
            }

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.AddHeader(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        request.AddHeader(headerParam.Key, value);
                    }
                }
            }

            if (options.FormParameters != null)
            {
                foreach (var formParam in options.FormParameters)
                {
                    request.AddParameter(formParam.Key, formParam.Value);
                }
            }

            if (options.Data != null)
            {
                if (options.HeaderParameters != null)
                {
                    var contentTypes = options.HeaderParameters["Content-Type"];
                    if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
                    {
                        request.RequestFormat = DataFormat.Json;
                    }
                    else
                    {
                        // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
                    }
                }
                else
                {
                    // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
                    request.RequestFormat = DataFormat.Json;
                }

                request.AddJsonBody(options.Data);
            }

            if (options.FileParameters != null)
            {
                foreach (var fileParam in options.FileParameters)
                {
                    var bytes      = ClientUtils.ReadAsBytes(fileParam.Value);
                    var fileStream = fileParam.Value as FileStream;
                    if (fileStream != null)
                    {
                        request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
                    }
                    else
                    {
                        request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
                    }
                }
            }

            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                foreach (var cookie in options.Cookies)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
            }

            return(request);
        }
Exemple #16
0
        private async Task <ApiResponse <T> > ExecAsync <T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.Proxy != null)
            {
                client.Proxy = configuration.Proxy;
            }

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            if (configuration.ClientCertificates != null)
            {
                client.ClientCertificates = configuration.ClientCertificates;
            }

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.AsyncRetryPolicy != null)
            {
                var policy       = RetryConfiguration.AsyncRetryPolicy;
                var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false);

                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = await client.ExecuteAsync <T>(req, cancellationToken).ConfigureAwait(false);
            }

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
            }
            else if (typeof(T).Name == "Stream") // for binary response
            {
                response.Data = (T)(object)new MemoryStream(response.RawBytes);
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Exemple #17
0
        private async Task <ApiResponse <T> > Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler(existingDeserializer, "application/json", "text/json", "text/x-json", "text/javascript", "*+json");
            }
            else
            {
                var codec = new CustomJsonCodec(configuration);
                client.AddHandler(codec, "application/json", "text/json", "text/x-json", "text/javascript", "*+json");
            }

            client.AddHandler(new XmlDeserializer(), "application/xml", "text/xml", "*+xml", "*");

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            InterceptRequest(req);
            var response = await client.ExecuteTaskAsync <T>(req);

            InterceptResponse(req, response);

            var result = toApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Exemple #18
0
        /// <summary>
        /// Make a HTTP PATCH request (async).
        /// </summary>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
        /// <returns>A Task containing ApiResponse</returns>
        public Task <ApiResponse <T> > PatchAsync <T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var config = configuration ?? GlobalConfiguration.Instance;

            return(ExecAsync <T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken));
        }
Exemple #19
0
        /// <summary>
        /// Make a HTTP HEAD request (async).
        /// </summary>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>A Task containing ApiResponse</returns>
        public async Task <ApiResponse <T> > HeadAsync <T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
        {
            var config = configuration ?? GlobalConfiguration.Instance;

            return(await Exec <T>(newRequest(HttpMethod.Head, path, options, config), config));
        }
        private ApiResponse <T> Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.Proxy != null)
            {
                client.Proxy = configuration.Proxy;
            }

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            if (configuration.ClientCertificates != null)
            {
                client.ClientCertificates = configuration.ClientCertificates;
            }

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.RetryPolicy != null)
            {
                var policy       = RetryConfiguration.RetryPolicy;
                var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = client.Execute <T>(req);
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }