Пример #1
0
        /// <summary>
        /// Executes a request and returns a JToken for querying. Throws an exception when the response is invalid.
        /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        /// <remarks>
        /// This method will automatically dispose the <paramref name="baseClient"/> and <paramref name="content" /> when finished.
        /// </remarks>
        protected async Task<RequestResult<JToken>> ExecuteRequestAsync(RequestUri uri, HttpMethod method,
            CancellationToken cancellationToken, HttpContent content = null)
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _ExecutionPolicy.Run(baseRequestMessage, async (requestMessage) =>
                {
                    var request = _Client.SendAsync(requestMessage, cancellationToken);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        JToken jtoken = null;

                        // Don't parse the result when the request was Delete.
                        if (baseRequestMessage.Method != HttpMethod.Delete)
                        {
                            // Make sure that dates are not stripped of any timezone information if tokens are de-serialised into strings/DateTime/DateTimeZoneOffset
                            using (var reader = new JsonTextReader(new StringReader(rawResult)) { DateParseHandling = DateParseHandling.None })
                            {
                                jtoken = await JObject.LoadAsync(reader, cancellationToken);
                            }
                        }

                        return new RequestResult<JToken>(response, jtoken, rawResult, ReadLinkHeader(response));
                    }
                }, cancellationToken);

                return policyResult;
            }
        }
Пример #2
0
        /// <summary>
        /// Executes a request and returns the given type. Throws an exception when the response is invalid.
        /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        /// <remarks>
        /// This method will automatically dispose the <paramref name="baseRequestMessage" /> when finished.
        /// </remarks>
        protected async Task <T> ExecuteRequestAsync <T>(RequestUri uri, HttpMethod method, HttpContent content = null, string rootElement = null) where T : new()
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _ExecutionPolicy.Run <T>(baseRequestMessage, async (requestMessage) =>
                {
                    var request = _Client.SendAsync(requestMessage);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        // This method may fail when the method was Delete, which is intendend.
                        // Delete methods should not be parsing the response JSON and should instead
                        // be using the non-generic ExecuteRequestAsync.
                        var reader = new JsonTextReader(new StringReader(rawResult));
                        var data   = _Serializer.Deserialize <JObject>(reader).SelectToken(rootElement);
                        var result = data.ToObject <T>();

                        return(new RequestResult <T>(response, result, rawResult));
                    }
                });

                return(policyResult);
            }
        }
        private async Task <TokenInformation> GetTokenInformation()
        {
            if (this.Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.GoogleApis, Api.Auth, ApiVersion.V1, Endpoint.TokenInfo);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "access_token", this.Token.Value }
                };



                #endregion


                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl);

                return(!string.IsNullOrWhiteSpace(response) ? JsonConvert.DeserializeObject <TokenInformation>(response) : null);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
Пример #4
0
        /// <summary>
        /// Executes a request and returns a JToken for querying. Throws an exception when the response is invalid.
        /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        /// <remarks>
        /// This method will automatically dispose the <paramref name="baseClient"/> and <paramref name="content" /> when finished.
        /// </remarks>
        protected async Task <JToken> ExecuteRequestAsync(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _ExecutionPolicy.Run(baseRequestMessage, async (requestMessage) =>
                {
                    var request = _Client.SendAsync(requestMessage);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        JToken jtoken = null;

                        // Don't parse the result when the request was Delete.
                        if (baseRequestMessage.Method != HttpMethod.Delete)
                        {
                            jtoken = JToken.Parse(rawResult);
                        }

                        return(new RequestResult <JToken>(response, jtoken, rawResult));
                    }
                });

                return(policyResult);
            }
        }
        /// <summary>
        /// Revoke access token. Returns true if token revoked successfully.
        /// </summary>
        /// <returns></returns>
        public async Task <bool> RevokeToken()
        {
            if (this.Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.Accounts, Api.Outh2, Endpoint.RevokeToken);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "token", this.Token.Value },
                };

                #endregion

                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl);

                if (response == "{}")
                {
                    this.Token = null;
                    return(true);
                }


                return(false);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
        /// <summary>
        /// Get channel's videos.
        /// </summary>
        /// <param name="channelId">Youtube channel id.</param>
        /// <param name="pageToken">Next or previous page token.</param>
        /// <returns></returns>
        public async Task <GoogleApiResponse <Video <VideoIdentifier> > > GetChannelVideos(string channelId, string pageToken, DateTime publishedAfter, DateTime publishedBefore)
        {
            if (Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.GoogleApis, Api.Youtube, ApiVersion.V3, Endpoint.Search);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "order", "date" },
                    { "part", Part.Snippet.GetDescription() },
                    { "channelId", channelId },
                    { "key", this.Credentials.ApiKey },
                    { "pageToken", pageToken },
                    { "type", "video" },
                    { "publishedAfter", publishedAfter.ToString("yyyy-MM-ddTHH:mm:ssK") },
                    { "publishedBefore", publishedBefore.ToString("yyyy-MM-ddTHH:mm:ssK") }
                };

                #endregion


                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl);

                return(!string.IsNullOrWhiteSpace(response) ? JsonConvert.DeserializeObject <GoogleApiResponse <Video <VideoIdentifier> > >(response) : null);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
Пример #7
0
        /// <summary>
        /// Executes a request and returns the given type. Throws an exception when the response is invalid.
        /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        protected async Task <T> ExecuteRequestAsync <T>(RequestUri uri, HttpMethod method, HttpContent content = null, string rootElement = null) where T : new()
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _ExecutionPolicy.Run(baseRequestMessage, async requestMessage =>
                {
                    var request = _Client.SendAsync(requestMessage);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        // This method may fail when the method was Delete, which is intendend.
                        // Delete methods should not be parsing the response JSON and should instead
                        // be using the non-generic ExecuteRequestAsync.
                        try
                        {
                            var result = JsonConvert.DeserializeObject <T>(rawResult);
                            return(new RequestResult <T>(response, result, rawResult));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw;
                        }
                    }
                });

                return(policyResult);
            }
        }
        private async Task <GoogleApiResponse <Video <VideoIdentifier> > > GetChannelsLastVideo(string channelId)
        {
            if (Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.GoogleApis, Api.Youtube, ApiVersion.V3, Endpoint.Search);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "order", "date" },
                    { "part", Part.Snippet.GetDescription() },
                    { "channelId", channelId },
                    { "key", this.Credentials.ApiKey },
                    { "type", "video" },
                    { "maxResults", "1" }
                };

                #endregion


                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl);

                return(!string.IsNullOrWhiteSpace(response) ? JsonConvert.DeserializeObject <GoogleApiResponse <Video <VideoIdentifier> > >(response) : null);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
        /// <summary>
        /// Gets user google profile.
        /// </summary>
        /// <returns></returns>
        public async Task <Profile> Me()
        {
            if (this.Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.GoogleApis, Api.Plus, ApiVersion.V1, Endpoint.Me);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "client_id", this.Credentials.ClientId }
                };

                #endregion

                #region Set Headers

                var headers = new Dictionary <string, string>()
                {
                    { "Authorization", $"{this.Token.Type} {this.Token.Value}" }
                };

                #endregion

                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl, headers);

                return(!string.IsNullOrWhiteSpace(response) ? JsonConvert.DeserializeObject <Profile>(response) : null);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
Пример #10
0
        private void LoadPrefabObject(PrefabObject o)
        {
            RequestUri request = new RequestUri(o.ConfigResource);

            request.OnFinish += response =>
            {
                string    json      = ((ResponseUri)response).TextData;
                AssetInfo assetInfo = null;

                if (!LoadAssetInfo(json, ref assetInfo, o))
                {
                    return;
                }

                string mainAssembly = FindMainAssembly(assetInfo, o);

                foreach (string dllName in assetInfo.Assembly)
                {
                    if (dllName != mainAssembly)
                    {
                        LoadDll(o, dllName);
                    }
                }

                LoadDll(o, mainAssembly);

                LoadCustomAssetApi(assetInfo, o);
            };

            request.OnError += s => { Helper.ShowErrorLoadObject(o, s); };
        }
        /// <summary>
        /// Get Outh2 url for user.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetOuth2Url(Outh2RequestBody request)
        {
            if (!request.Validate())
            {
                throw new Exception("Outh2 Request Body is not valid!");
            }

            var requestUrl = RequestUri.GetRequestUrl(Base.Accounts, Api.Outh2, ApiVersion.V2, Endpoint.Auth);

            #region Set Parameters

            var parameters = new Dictionary <string, string>()
            {
                { "scope", request.Scopes.Parse() },
                { "access_type", request.AccessType.GetDescription() },
                { "include_granted_scopes", request.IncludeGrantedScopes.ToString().ToLower() },
                { "state", request.State },
                { "redirect_uri", this.Credentials.RedirectUrl },
                { "response_type", request.ResponseType.GetDescription() },
                { "client_id", this.Credentials.ClientId }
            };

            #endregion

            requestUrl = requestUrl.Append(parameters);

            return(requestUrl);
        }
Пример #12
0
        /// <summary>
        ///     Executes a request and returns a JToken for querying. Throws an exception when the response is invalid.
        ///     Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        /// <remarks>
        ///     This method will automatically dispose the
        ///     <paramref>
        ///         <name>baseClient</name>
        ///     </paramref>
        ///     and <paramref name="content" /> when finished.
        /// </remarks>
        protected async Task <JToken> ExecuteRequestAsync(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _executionPolicy.Run(baseRequestMessage, async requestMessage =>
                {
                    Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type",
                                                                         "application/json; charset=utf-8");
                    var request = Client.SendAsync(requestMessage);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        JToken jtoken = null;

                        // Don't parse the result when the request was Delete.
                        if (baseRequestMessage != null && baseRequestMessage.Method != HttpMethod.Delete)
                        {
                            jtoken = JToken.Parse(rawResult);
                        }

                        return(new RequestResult <JToken>(response, jtoken, rawResult));
                    }
                });

                return(policyResult);
            }
        }
        /// <summary>
        /// Executes a request and returns the given type. Throws an exception when the response is invalid.
        /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        protected async Task <T> ExecuteRequestAsync <T>(RequestUri uri, HttpMethod method, HttpContent content = null, string rootElement = null)
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _ExecutionPolicy.Run(baseRequestMessage, async requestMessage =>
                {
                    // update client for basic authentication
                    var byteArray = Encoding.ASCII.GetBytes($"{_userName}:{_apiKey}");
                    _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                    var request = _Client.SendAsync(requestMessage);
                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        if (!string.IsNullOrEmpty(rawResult))
                        {
                            CheckResponseExceptions(response, rawResult);
                        }
                        // This method may fail when the method was Delete, which is intendend.
                        // Delete methods should not be parsing the response JSON and should instead
                        // be using the non-generic ExecuteRequestAsync.

                        var result = JsonConvert.DeserializeObject <T>(rawResult);
                        return(new RequestResult <T>(response, result, rawResult));
                    }
                });

                return(policyResult);
            }
        }
        /// <summary>
        /// Prepares a request to the path and appends the shop's access token header if applicable.
        /// </summary>
        protected CloneableRequestMessage PrepareRequestMessage(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            var msg = new CloneableRequestMessage(uri.ToUri(), method, content);

            msg.Headers.Add("Accept", "application/json");
            return(msg);
        }
        public async Task <GoogleApiResponse <PlaylistItem> > GetPlaylistItems(string playlistId, string pageToken)
        {
            if (Token != null)
            {
                var requestUrl = RequestUri.GetRequestUrl(Base.GoogleApis, Api.Youtube, ApiVersion.V3, Endpoint.PlaylistItems);

                #region Set Parameters

                var parameters = new Dictionary <string, string>()
                {
                    { "part", $"{Part.Snippet.GetDescription()},{Part.Status.GetDescription()}" },
                    { "playlistId", playlistId },
                    { "key", this.Credentials.ApiKey },
                    { "pageToken", pageToken },
                };

                #endregion


                requestUrl = requestUrl.Append(parameters);

                var response = await HttpHelper.Instance.GetAsync(requestUrl);

                return(!string.IsNullOrWhiteSpace(response) ? JsonConvert.DeserializeObject <GoogleApiResponse <PlaylistItem> >(response) : null);
            }
            else
            {
                throw new Exception("Token not found!");
            }
        }
Пример #16
0
        /// <summary>
        /// Content agnostic way to send the request, regardless of Json or GraphQL.
        /// </summary>
        /// <param name="req">The RequestUri.</param>
        /// <param name="content">The HttpContent, be it GraphQL or Json.</param>
        /// <returns>A JToken containing the data from the request.</returns>
        private async Task <JToken> SendAsync(RequestUri req, HttpContent content, int?graphqlQueryCost, CancellationToken cancellationToken = default)
        {
            var response = await ExecuteRequestAsync(req, HttpMethod.Post, cancellationToken, content, graphqlQueryCost : graphqlQueryCost);

            CheckForErrors(response);

            return(response.Result["data"]);
        }
Пример #17
0
        /// <summary>
        /// Content agnostic way to send the request, regardless of Json or GraphQL.
        /// </summary>
        /// <param name="req">The RequestUri.</param>
        /// <param name="content">The HttpContent, be it GraphQL or Json.</param>
        /// <returns>A JToken containing the data from the request.</returns>
        private async Task <JToken> SendAsync(RequestUri req, HttpContent content)
        {
            JToken response = await ExecuteRequestAsync(req, HttpMethod.Post, content);

            await CheckForErrorsAsync(response);

            return(response["data"]);
        }
Пример #18
0
 public Context()
 {
     this.baseUri = new Lazy <Uri>(() =>
     {
         UriComponents authority = (UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port);
         return(new Uri(RequestUri.GetComponents(authority, UriFormat.SafeUnescaped)));
     });
 }
Пример #19
0
        /// <summary>
        /// Sets the proper querystring for getting or deleting a single asset.
        /// </summary>
        /// <param name="req">The request to modify.</param>
        /// <param name="key">The key value of the asset, e.g. 'templates/index.liquid' or 'assets/bg-body.gif'.</param>
        /// <param name="themeId">The id of the theme that the asset belongs to.</param>
        /// <returns>The request with the proper querystring.</returns>
        RequestUri SetAssetQuerystring(RequestUri req, string key, long themeId)
        {
            //QS should look like:
            //?asset[key]={key}&theme_id={themeId}
            req.QueryParams.Add("asset[key]", key);
            req.QueryParams.Add("theme_id", themeId);

            return(req);
        }
        /// <summary>
        /// Prepares a request to the path and appends the shop's access token header if applicable.
        /// </summary>
        protected CloneableRequestMessage PrepareRequestMessage(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            var msg = new CloneableRequestMessage(uri.ToUri(), method, content);

            msg.Headers.Add("Accept", "application/json");
            msg.Headers.Add("user-agent", "QuickbutikSharp");
            msg.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_apiKey}:{_apiKey}")));
            return(msg);
        }
        /// <summary>
        /// Add filter to request
        /// </summary>
        /// <param name="filter">Filter options</param>
        /// <returns></returns>
        public ZonkyHttpRequestMessage AddFilterOptions(FilterOptions filter = null)
        {
            if (filter != null)
            {
                RequestUri = RequestUri.AppendFilterOptions(filter);
            }

            return(this);
        }
Пример #22
0
        internal void AddUrlSegment(string key, string value)
        {
            string trueKey = "{" + key + "}";
            var    url     = RequestUri.ToString();

            url = url.Replace(trueKey, value);
            var uri = new Uri(url, UriKind.Relative);

            RequestUri = uri;
        }
        /// <summary>
        /// HttpWebRequest 객체를 생성하고 초기화한다.
        /// </summary>
        /// <returns></returns>
        private HttpWebRequest createWebRequest()
        {
            makeUriString();

            Console.WriteLine("HttpRestClient " + Method + " " + RequestUri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestUri);

            request.Method           = Method;
            request.ReadWriteTimeout = Timeout * 1000;
            request.Timeout          = Timeout * 1000;
            request.Accept           = ResponseDataFormat;
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.UserAgent = "StockItemData Client";
            //request.Referer = "";

            //request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip");
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            // 인증정보가 다른 서버로 새어나가지 않도록 API 서버 주소와 비교한다.
            string urlBase = Configure.server + "/" + Configure.apiVersion;

            if (RequestUri.StartsWith(urlBase))
            {
                // 인증헤더 추가
                string authorize = getAuthorizationString();
                if (authorize != null && authorize.Length > 0)
                {
                    // 인식하지 않음
                    // request.Credentials 을 사용할 것을 권장하는데 개발하기 번거로우니, X- 헤더로 대체함
                    //request.PreAuthenticate = true;
                    //request.Headers.Add("Authorization", authorize);
                    request.Headers.Add("X-Authorization", authorize);
                }

                // 암호화 헤더 추가
                if (UserEncryptMode)
                {
                    // 암호화헤더 추가
                    byte[] key = AESUtil.createRandomKeys(AESUtil.AES_BITS_256);
                    AESUtil.Key = key;
                    string rsaEncodedKey = "AES/256/CBC," + RSAEncrypt.Encrypt(key);
                    Console.WriteLine("X-Encrypt-Key:" + rsaEncodedKey);
                    request.Headers.Add("X-Encrypt-Key", rsaEncodedKey);
                }
            }
            else
            {
                Console.WriteLine("요청 주소는 API서버가 아님 [" + RequestUri + "]");
                // 암호화기능 disable
                UserEncryptMode = false;
            }

            return(request);
        }
Пример #24
0
        /// <summary>
        /// Prepares a request to the path and appends the shop's access token header if applicable.
        /// </summary>
        protected CloneableRequestMessage PrepareRequestMessage(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            var msg = new CloneableRequestMessage(uri.ToUri(), method, content);

            if (!string.IsNullOrEmpty(_AccessToken))
            {
                msg.Headers.Add("X-Shopify-Access-Token", _AccessToken);
            }

            return(msg);
        }
Пример #25
0
        /// <summary>
        ///     Executes a request and returns the given type. Throws an exception when the response is invalid.
        ///     Use this method when the expected response is a single line or simple object that doesn't warrant its own class.
        /// </summary>
        /// <remarks>
        ///     This method will automatically dispose the <paramref>
        ///         <name>baseRequestMessage</name>
        ///     </paramref>
        ///     when finished.
        /// </remarks>
        protected async Task <T> ExecuteRequestAsync <T>(RequestUri uri, HttpMethod method, HttpContent content = null,
                                                         string rootElement = null) where T : new()
        {
            using (var baseRequestMessage = PrepareRequestMessage(uri, method, content))
            {
                var policyResult = await _executionPolicy.Run(baseRequestMessage, async requestMessage =>
                {
                    //Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type",
                    //    "application/json; charset=utf-8");
                    var request = Client.SendAsync(requestMessage);

                    using (var response = await request)
                    {
                        var rawResult = await response.Content.ReadAsStringAsync();

                        //Check for and throw exception when necessary.
                        CheckResponseExceptions(response, rawResult);

                        // This method may fail when the method was Delete, which is intendend.
                        // Delete methods should not be parsing the response JSON and should instead
                        // be using the non-generic ExecuteRequestAsync.
                        var reader = new JsonTextReader(new StringReader(rawResult));
                        if (HttpMethod.Head.Equals(method))
                        {
                            if (response.Headers.Contains("X-Count"))
                            {
                                var data = Convert.ToInt32(response.Headers.GetValues("X-Count").First());
                                return(new RequestResult <T>(response, Parse <T>(Convert.ToInt32(data)), rawResult));
                            }
                            else
                            {
                                var data = Convert.ToInt32(response.Headers.GetValues("X-Total-Count").First());
                                return(new RequestResult <T>(response, Parse <T>(Convert.ToInt32(data)), rawResult));
                            }
                        }
                        if (rawResult.StartsWith("["))
                        {
                            var data   = Serializer.Deserialize <JArray>(reader);
                            var result = data.ToObject <T>();

                            return(new RequestResult <T>(response, result, rawResult));
                        }
                        else
                        {
                            var data   = Serializer.Deserialize <JObject>(reader);
                            var result = data.ToObject <T>();
                            return(new RequestResult <T>(response, result, rawResult));
                        }
                    }
                });

                return(policyResult);
            }
        }
Пример #26
0
        /// <summary>
        /// Prepares a request to the path and appends the shop's access token header if applicable.
        /// </summary>
        protected virtual CloneableRequestMessage PrepareRequestMessage(RequestUri uri, HttpMethod method, HttpContent content = null)
        {
            var msg = new CloneableRequestMessage(uri.ToUri(), method, content);

            if (!string.IsNullOrEmpty(_AccessToken))
            {
                msg.Headers.Add("Authorization", $@"Bearer {_AccessToken}");
            }
            msg.Headers.Add("Accept", "application/json");
            return(msg);
        }
Пример #27
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Service != null ? Service.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Route != null ? Route.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Method != null ? Method.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Payload != null ? Payload.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RequestUri != null ? RequestUri.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #28
0
        internal virtual Bucket CreateRequest()
        {
            Encoding enc = RequestEncoding;

#pragma warning disable CA2000 // Dispose objects before losing scope
            return(enc.GetBytes((Method ?? "GET") + " ").AsBucket()
                   + enc.GetBytes(RequestUri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped)).AsBucket()
                   + enc.GetBytes(" HTTP/1.1\r\n").AsBucket()
                   + CreateHeaders(RequestUri.Host));

#pragma warning restore CA2000 // Dispose objects before losing scope
        }
        /// <summary>
        /// Create a pre-sign string formed from the following items and concatenating them together
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="contentHash"></param>
        /// <param name="subaccountId"></param>
        /// <returns></returns>
        private string GetSignature(string timestamp, string url, string method, string contentHash, string subaccountId = "")
        {
            var sign   = string.Join(string.Empty, timestamp, RequestUri.ToString(), method, contentHash, subaccountId);
            var secret = Encoding.UTF8.GetBytes(_secret);

            using (HMACSHA512 hmac = new HMACSHA512(secret))
            {
                var bytes  = Encoding.UTF8.GetBytes(sign);
                var signed = hmac.ComputeHash(bytes);
                return(BitConverter.ToString(signed).ToLower().Replace("-", string.Empty));
            }
        }
        public IClientResponse Send()
        {
            _request.ContentType = _entity.ContentType.ToString();
            RaiseStatusChanged("Connecting to {0}", RequestUri.ToString());
            if (_entity.Stream != null &&
                ((_entity.Stream.CanSeek && _entity.Stream.Length > 0) ||
                 _entity.Stream != _emptyStream))
            {
                SendRequestStream();
            }

            return(new HttpWebResponseBasedResponse(this, _request));
        }
 public AzureRequestStatus CheckRequestStatus(RequestUri requestUri)
 {
     LastCheckRequestStatusRequestUri = requestUri;
     RunScript();
     return NextRequestStatus;
 }
        public AzureRequestStatus CheckRequestStatus(RequestUri requestUri)
        {
            var response = _http.Get(requestUri.ToString());
            var match = Regex.Match(response.Content, "<Status>(.*?)</Status>");
            FailFast.Unless(match.Success, "Expected regex match in response content: " + match + ".  Request URI:" + requestUri + ", Response content:" + response.Content);

            switch (match.Groups[1].Value)
            {
                case "InProgress":
                    return AzureRequestStatus.InProgress;
                case "Succeeded":
                    return AzureRequestStatus.Succeeded;
                case "Failed":
                    OurTrace.TraceError("CheckRequestStatus gave us a failure: " + response.Content);
                    var is400BadRequest = Regex.Match(response.Content, "<HttpStatusCode>400</HttpStatusCode><Error><Code>BadRequest</Code>");
                    if (is400BadRequest.Success)
                        throw new BadRequestException(requestUri, response.Content);
                    return AzureRequestStatus.Failed;
                default:
                    FailFast.WithMessage("Unexpected operation status: " + match.Groups[1].Value + ", for operation: " + requestUri);
                    // ReSharper disable HeuristicUnreachableCode
                    throw new InvalidOperationException("Shouldn't ever get here!");
                    // ReSharper restore HeuristicUnreachableCode
            }
        }
Пример #33
0
 public BadRequestException(RequestUri requestUri, string content)
     : base(string.Format("BadRequest returned for operation '{0}': response: {1}", requestUri, content))
 {
 }