Exemplo n.º 1
0
        internal static string DoRequest(Uri uri)
        {
            var req = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = HttpMethod.Get
            };

            VersionedApiRequest.SetUserAgent(ref req);

            using (Configuration.Instance.ApiLogger.BeginScope("ApiRequest.DoRequest {0}", uri.GetHashCode()))
            {
                Configuration.Instance.ApiLogger.LogDebug($"GET {uri}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();
                var readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();
                string json;
                using (var sr = new StreamReader(readTask.Result))
                {
                    json = sr.ReadToEnd();
                }
                Configuration.Instance.ApiLogger.LogDebug(json);
                return(json);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Send a request to the Nexmo API.
        /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter.
        /// </summary>
        /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param>
        /// <param name="uri">The URI to communicate with</param>
        /// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public static NexmoResponse DoRequest(string method, Uri uri, Dictionary <string, string> parameters, Credentials creds = null)
        {
            var sb = new StringBuilder();

            // if parameters is null, assume that key and secret have been taken care of
            if (null != parameters)
            {
                sb = BuildQueryString(parameters, creds);
            }

            var req = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = new HttpMethod(method)
            };

            VersionedApiRequest.SetUserAgent(ref req, creds);

            var data = Encoding.ASCII.GetBytes(sb.ToString());

            req.Content = new ByteArrayContent(data);
            req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
            {
                Logger.Debug($"{method} {uri} {sb}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

                    if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
                                       "true", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        sendTask.Result.EnsureSuccessStatusCode();
                    }

                    return(new NexmoResponse
                    {
                        Status = sendTask.Result.StatusCode
                    });
                }

                string json;
                var    readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();
                using (var sr = new StreamReader(readTask.Result))
                {
                    json = sr.ReadToEnd();
                }
                Logger.Debug(json);
                return(new NexmoResponse
                {
                    Status = sendTask.Result.StatusCode,
                    JsonResponse = json
                });
            }
        }
Exemplo n.º 3
0
        internal static HttpResponseMessage DoRequestJwt(Uri uri, Credentials creds)
        {
            var appId      = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
            var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"];

            var req = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = HttpMethod.Get
            };

            VersionedApiRequest.SetUserAgent(ref req, creds);

            req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",
                                                                                              Jwt.CreateToken(appId, appKeyPath));

            using (LogProvider.OpenMappedContext("ApiRequest.DoRequestJwt", uri.GetHashCode()))
            {
                Logger.Debug($"GET {uri}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

                    if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
                                       "true", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        sendTask.Result.EnsureSuccessStatusCode();
                    }
                }
                return(sendTask.Result);
            }
        }
Exemplo n.º 4
0
        public static NexmoResponse DoRequest(string method, Uri uri, object requestBody, Credentials creds = null)
        {
            var sb         = new StringBuilder();
            var parameters = new Dictionary <string, string>();

            sb = BuildQueryString(parameters, creds);

            var requestContent = JsonConvert.SerializeObject(requestBody);

            var req = new HttpRequestMessage
            {
                RequestUri = new Uri((uri.OriginalString + $"?{sb}").ToLower()),
                Method     = new HttpMethod(method),
                Content    = new StringContent(requestContent, Encoding.UTF8, "application/json"),
            };

            VersionedApiRequest.SetUserAgent(ref req, creds);

            using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
            {
                Logger.Debug($"{method} {uri} {sb}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

                    if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
                                       "true", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        sendTask.Result.EnsureSuccessStatusCode();
                    }

                    return(new NexmoResponse
                    {
                        Status = sendTask.Result.StatusCode
                    });
                }

                string jsonResult;
                var    readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();
                using (var sr = new StreamReader(readTask.Result))
                {
                    jsonResult = sr.ReadToEnd();
                }
                Logger.Debug(jsonResult);
                return(new NexmoResponse
                {
                    Status = sendTask.Result.StatusCode,
                    JsonResponse = jsonResult
                });
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Send a request to the Nexmo API.
        /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter.
        /// </summary>
        /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param>
        /// <param name="uri">The URI to communicate with</param>
        /// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public static NexmoResponse DoRequest(string method, Uri uri, Dictionary <string, string> parameters, Credentials creds = null)
        {
            var sb = new StringBuilder();

            // if parameters is null, assume that key and secret have been taken care of
            if (null != parameters)
            {
                sb = BuildQueryString(parameters, creds);
            }

            var req = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = new HttpMethod(method),
            };

            VersionedApiRequest.SetUserAgent(ref req);

            var data = Encoding.ASCII.GetBytes(sb.ToString());

            req.Content = new ByteArrayContent(data);
            req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using (Configuration.Instance.ApiLogger.BeginScope("ApiRequest.DoRequest {0}", uri.GetHashCode()))
            {
                Configuration.Instance.ApiLogger.LogDebug($"{method} {uri} {sb}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Configuration.Instance.ApiLogger.LogError($"FAIL: {sendTask.Result.StatusCode}");
                    throw NexmoApiExceptionFactory.CreateForResponse(sendTask.Result.StatusCode);
                    // return new NexmoResponse
                    // {
                    //     Status = sendTask.Result.StatusCode
                    // };
                }

                string json;
                var    readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();
                using (var sr = new StreamReader(readTask.Result))
                {
                    json = sr.ReadToEnd();
                }
                Configuration.Instance.ApiLogger.LogDebug(json);
                return(new NexmoResponse
                {
                    Status = sendTask.Result.StatusCode,
                    JsonResponse = json
                });
            }
        }
Exemplo n.º 6
0
        internal static string DoRequest(Uri uri, Credentials creds)
        {
            var apiKey    = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
            var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
            var req       = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = HttpMethod.Get
            };

            VersionedApiRequest.SetUserAgent(ref req, creds);

            // do we need to use basic auth?
            // TODO / HACK: this is a newer auth method that needs to be incorporated better in the future
            if (uri.AbsolutePath.StartsWith("/accounts/") || uri.AbsolutePath.StartsWith("/v2/applications"))
            {
                var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret);
                req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
                                                                                                  Convert.ToBase64String(authBytes));
            }

            using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
            {
                Logger.Debug($"GET {uri}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

                    if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
                                       "true", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        sendTask.Result.EnsureSuccessStatusCode();
                    }
                }

                var readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();

                string json;
                using (var sr = new StreamReader(readTask.Result))
                {
                    json = sr.ReadToEnd();
                }
                Logger.Debug(json);
                return(json);
            }
        }
Exemplo n.º 7
0
        internal static string DoRequest(Uri uri, Credentials creds)
        {
            var req = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = HttpMethod.Get
            };

            VersionedApiRequest.SetUserAgent(ref req, creds);

            using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
            {
                Logger.Debug($"GET {uri}");
                var sendTask = Configuration.Instance.Client.SendAsync(req);
                sendTask.Wait();

                if (!sendTask.Result.IsSuccessStatusCode)
                {
                    Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

                    if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
                                       "true", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        sendTask.Result.EnsureSuccessStatusCode();
                    }
                }

                var readTask = sendTask.Result.Content.ReadAsStreamAsync();
                readTask.Wait();

                string json;
                using (var sr = new StreamReader(readTask.Result))
                {
                    json = sr.ReadToEnd();
                }
                Logger.Debug(json);
                return(json);
            }
        }