public override void PreProcess(RestSharp.IRestRequest request) { if (!Description.IsNullOrWhitespace()) { request.AddParameterExclusive("cd", Description.Truncate(500)); } }
public void Authenticate(RSharp.IRestClient client, RSharp.IRestRequest request) { if (!request.Parameters.Any(p => "Authorization".Equals(p.Name, StringComparison.OrdinalIgnoreCase))) { request.AddParameter("Authorization", authHeader, RSharp.ParameterType.HttpHeader); } }
public override void PreProcess(RestSharp.IRestRequest request) { if (!Path.IsNullOrWhitespace()) { request.AddParameterExclusive("dp", Path.Truncate(2048)); } }
private string GetAuthenticationHeader(RestSharp.IRestClient client, RestSharp.IRestRequest request) { string requestContentBase64String = string.Empty; //Calculate UNIX time DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); //create random nonce for each request string nonce = Guid.NewGuid().ToString("N"); // URLEncode the request URI var requestUri = HttpUtility.UrlEncode(client.BuildUri(request).AbsoluteUri.ToLower()); //Creating the raw signature string string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", _srApiKey, request.Method, requestUri, requestTimeStamp, nonce, requestContentBase64String); var secretKeyByteArray = Convert.FromBase64String(_srApiSecret); byte[] signature = Encoding.UTF8.GetBytes(signatureRawData); using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray)) { byte[] signatureBytes = hmac.ComputeHash(signature); string requestSignatureBase64String = Convert.ToBase64String(signatureBytes); //Setting the values in the Authorization header using custom scheme (amx) return("amx " + string.Format("{0}:{1}:{2}:{3}", _srApiKey, requestSignatureBase64String, nonce, requestTimeStamp)); } }
/// <summary> /// Adds the API token key to the REST request header /// </summary> public void Authenticate(RestSharp.IRestClient client, RestSharp.IRestRequest request) { if (!request.Parameters.Any(p => p.Name.Equals("X-TOKEN", StringComparison.OrdinalIgnoreCase))) { var token = string.Format("{0}", _apiToken); request.AddParameter("X-TOKEN", token, ParameterType.HttpHeader); } }
public ApiResult <T> ExecutePublicRequest <T>(RestSharp.IRestRequest request, int weight, string contentPath = null) { try { var sw = Stopwatch.StartNew(); var response = client.Execute(request); sw.Stop(); if (response.IsSuccessful) { UpdateWeight(weight); Log.DebugFormat("{0} {1} - {2}ms : {3} ({4}).", request.Method.ToString(), client.BuildUri(request), sw.ElapsedMilliseconds, response.StatusDescription, (int)response.StatusCode); #if DEBUG if (contentPath != null) { File.WriteAllText(contentPath, response.Content); } #endif var data = JsonConvert.DeserializeObject <T>(response.Content.Replace(",[]", string.Empty)); return(new ApiResult <T>(data, null, sw.ElapsedMilliseconds)); } else if (response.ResponseStatus == ResponseStatus.Completed) { if (response.StatusCode >= HttpStatusCode.InternalServerError || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.Unauthorized) { // Do not retry for public API? var error = client.Deserialize <ApiError>(response).Data; Log.WarnFormat("{0} {1} - {2}ms : {3} ({4}).", request.Method.ToString(), client.BuildUri(request), sw.ElapsedMilliseconds, response.StatusDescription, (int)response.StatusCode); return(new ApiResult <T>(default(T), error, sw.ElapsedMilliseconds)); } else { Log.WarnFormat("{0} {1} - {2}ms : {3} ({4}).", request.Method.ToString(), client.BuildUri(request), sw.ElapsedMilliseconds, response.StatusDescription, (int)response.StatusCode); return(new ApiResult <T>(default(T), new ApiError((int)response.StatusCode, response.StatusDescription), sw.ElapsedMilliseconds)); } } else { Log.ErrorFormat("{0} {1} - {2}ms : {3} ({4}).", request.Method.ToString(), client.BuildUri(request), sw.ElapsedMilliseconds, response.ErrorMessage, (int)response.ResponseStatus); return(new ApiResult <T>(default(T), new ApiError((int)response.ResponseStatus, response.ErrorMessage), sw.ElapsedMilliseconds)); } } catch (Exception ex) { Log.Error(string.Format("{0} {1} failed.", request.Method.ToString(), client.BuildUri(request)), ex); return(new ApiResult <T>(default(T), new ApiError(-1, ex.Message))); } finally { } }
/// <summary> /// Adds the authentication tokens to the request if the parameters don't include them /// </summary> /// <param name="request">The request object to be checked</param> private RestSharp.IRestRequest AddAuthTokensAsNecessary(RestSharp.IRestRequest request) { if (string.IsNullOrEmpty(loginToken) == false && request.Parameters.Count(x => string.Equals(x.Name, clientConfig.TokenCookieName) == true) == 0) { request.AddParameter(clientConfig.TokenCookieName, loginToken); } if (string.IsNullOrEmpty(sessionToken) == false && request.Parameters.Count(x => string.Equals(x.Name, clientConfig.SessionCookieName) == true) == 0) { request.AddParameter(clientConfig.SessionCookieName, sessionToken); } return(request); }
private async Task <T> RequestSignedApiAsync <T>(RestSharp.IRestRequest request, int weight, TimeSpan offset, int tries = 0) { try { //await slim.WaitAsync().ConfigureAwait(true); request.AddQueryParameter("timestamp", DateTime.UtcNow.Add(offset).ToUnixTimestamp().ToString()); var uri = client.BuildUri(request); var signature = ByteArrayToHexString(SignString(uri.Query.Replace("?", string.Empty))); request.AddQueryParameter("signature", signature); request.AddHeader("X-MBX-APIKEY", ApiKey.ToManagedString()); var response = await client.ExecuteTaskAsync <T>(request).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.OK) { UpdateWeight(PlaceOrderWeight); return(JsonConvert.DeserializeObject <T>(response.Content)); //return response.Data; } else if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) { // retry... return(await RequestSignedApiAsync <T>(request, weight, offset, tries + 1)); } else if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest) { var error = client.Deserialize <ApiError>(response).Data; if (error.Code == -1021 && tries < 5) { // retry... return(await RequestSignedApiAsync <T>(request, weight, offset, tries + 1)); } else { throw new Exception($"Error {error.Code}: {error.Msg}."); } } else { throw new Exception(response.ErrorMessage); } } finally { //slim.Release(); } }
private async Task <RestSharp.IRestResponse <T> > RequestSignedApiAsync <T>(RestSharp.IRestRequest request, TimeSpan offset) { try { //await slim.WaitAsync().ConfigureAwait(true); request.AddQueryParameter("timestamp", ToUnixTimestamp(DateTime.UtcNow.Add(offset)).ToString()); var uri = client.BuildUri(request); var signature = ByteArrayToHexString(SignString(uri.Query.Replace("?", string.Empty))); request.AddQueryParameter("signature", signature); request.AddHeader("X-MBX-APIKEY", ApiKey.ToManagedString()); var response = await client.ExecuteTaskAsync <T>(request).ConfigureAwait(false); return(response); } finally { //slim.Release(); } }
public override void PreProcess(RestSharp.IRestRequest request) { request.AddParameterExclusive("t", "event"); if (!string.IsNullOrEmpty(Category)) { request.AddParameterExclusive("ec", Category.Truncate(150)); } if (!string.IsNullOrEmpty(Action)) { request.AddParameterExclusive("ea", Action.Truncate(500)); } if (!string.IsNullOrEmpty(Label)) { request.AddParameterExclusive("el", Label.Truncate(500)); } if (Value != 0) { request.AddParameterExclusive("ev", Value); } }
public override Task <IRestResponse <T> > ExecutePostTaskAsync <T>(IRestRequest request) { return(DecoratedClient.ExecutePostTaskAsync <T>(request)); }
public override Task <IRestResponse> ExecutePostTaskAsync(IRestRequest request, CancellationToken token) { return(DecoratedClient.ExecutePostTaskAsync(request, token)); }
public override Task <IRestResponse> ExecuteGetTaskAsync(IRestRequest request) { return(DecoratedClient.ExecuteGetTaskAsync(request)); }
public override RestRequestAsyncHandle ExecuteAsyncPost <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback, string httpMethod) { return(DecoratedClient.ExecuteAsyncPost(request, callback, httpMethod)); }
public override RestRequestAsyncHandle ExecuteAsync <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback) { return(DecoratedClient.ExecuteAsync(request, callback)); }
public override IRestResponse <T> Execute <T>(IRestRequest request) { return(DecoratedClient.Execute <T>(request)); }
public override void PreProcess(RestSharp.IRestRequest request) { request.AddParameter("dp", Path); }
public override void PreProcess(RestSharp.IRestRequest request) { request.AddParameter("cd", Description); }
public override void PreProcess(RestSharp.IRestRequest request) { request.AddParameter("dt", Title); }
public override void PreProcess(RestSharp.IRestRequest request) { request.AddParameterExclusive("sc", "end"); }