示例#1
0
        public static string PushMetrics(string ns, List <MetricDatum> metrics)
        {
            var request = new PutMetricDataRequest
            {
                Namespace  = ns,
                MetricData = metrics
            };

            //
            Amazon.Runtime.AWSCredentials credentials = null;
            if (Configuration.IsLinux())
            {
                string AccessKey = "xxx";
                string SecretKey = "xxx";
                credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, SecretKey);
            }
            else
            {
                credentials = new Amazon.Runtime.StoredProfileAWSCredentials("cloudwatch");
            }
            //
            var client = new AmazonCloudWatchClient(credentials, Amazon.RegionEndpoint.APSoutheast1);

            System.Threading.Tasks.Task <PutMetricDataResponse> task = client.PutMetricDataAsync(request);
            PutMetricDataResponse response = task.Result;

            //
            System.Net.HttpStatusCode statusCode = response.HttpStatusCode;
            Console.WriteLine(DateTime.Now.ToString("HH:mm ") + statusCode.ToString());
            return(statusCode.ToString());
        }
示例#2
0
        public async Task <T> GetAsync <T>(string endpoint, params KeyValuePair <string, string>[] headers)
        {
            System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.OK;
            try
            {
                _logger.LogInformation("GET: {endpoint}", endpoint);

                foreach (var header in headers)
                {
                    _client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }

                var result = await _client.GetAsync(endpoint);

                statusCode = result.StatusCode;

                result.EnsureSuccessStatusCode();
                var stringResult = await result.Content.ReadAsStringAsync();

                var accessModelResponse = JsonConvert.DeserializeObject <T>(stringResult);

                return(accessModelResponse);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "GET Exception: {ex} {@statusCode}", ex, statusCode);
                throw new ApiException(ex, (int)statusCode, new List <string> {
                    ex.Message, statusCode.ToString()
                });
            }
        }
        public static void LogAPICallToDB(int intOrderAdressID, string strHost, string strFullRoute, System.Net.HttpStatusCode objHttpResponseCode, TimeSpan objTimeSpan)
        {
            try
            {
                DateTime dteNow = DateTime.Now;

                APICallLogItem objAPICallLogItem = new APICallLogItem();
                objAPICallLogItem.OrderAddressID       = intOrderAdressID;
                objAPICallLogItem.Host                 = strHost;
                objAPICallLogItem.FullUrl              = strFullRoute;
                objAPICallLogItem.ResponseCode         = objHttpResponseCode.ToString();
                objAPICallLogItem.RunTimeHumanReadable = Model.StopwatchUtil.GetHumanReadableTimeElapsedString(objTimeSpan);
                objAPICallLogItem.RunTimeInTicksString = objTimeSpan.Ticks.ToString();
                objAPICallLogItem.DateUpdated          = dteNow;
                objAPICallLogItem.DateCreated          = dteNow;

                string strLastError = String.Empty;
                if (objAPICallLogItem.Insert(out strLastError) == false)
                {
                    throw new Exception(String.Format("The API Call Log Item failed to insert, as the identity/PK value returned was not valid.  OrderAddressID = [{0}], Host = [{1}], Route = [{2}], Http Status Code = [{3}], Error Message = [{4}]", intOrderAdressID, strHost, strFullRoute, objHttpResponseCode.ToString(), strLastError));
                }
            }
            catch (Exception ex)
            {
                // Don't abort processing since this is a post-action log... just log the error
                _objLogger.Error(String.Format("There was an error while trying to insert the API Call Log Item to the DB.  This error will be eaten, so that processing can continue. Error Message = [{0}]", ex.Message));
            }
        }
示例#4
0
 public UnexpectedResponseTypeCodeException(System.Net.HttpStatusCode expectedStatusCode, System.Net.HttpStatusCode receivedStatusCode)
     : base(string.Format("Unexpected status code response recived. Expected {0:S}, received {1:S}.",
                          expectedStatusCode.ToString(), receivedStatusCode.ToString()), null)
 {
     this.ExpectedStatusCode = expectedStatusCode;
     this.ReceivedStatusCode = receivedStatusCode;
 }
 public void ThenIShouldSeeTheResponseStatusCodeAs(string _statuscode)
 {
     //Reading the http status code
     System.Net.HttpStatusCode statusCode = restResponse.StatusCode;
     //Validating the status code
     Assert.AreEqual(_statuscode, statusCode.ToString());
 }
示例#6
0
        public async Task <IActionResult> Index(string ProductName, string UserId)
        {
            ShoppingCartItem newItem = new ShoppingCartItem();

            newItem.ProductName = ProductName;
            newItem.UserId      = UserId;
            var allItems = await userClient.GetShoppingCartItems();

            int temp = 0;

            foreach (ShoppingCartItem s in allItems)
            {
                if (s.ID > temp)
                {
                    temp = s.ID;
                }
            }
            newItem.ID = temp + 1;

            System.Net.HttpStatusCode res = userClient.AddShoppingCartItem(newItem);
            _logger.LogInformation("User {username} added {ProductName} to cart at {time}", UserClient.username, ProductName, DateTime.Now);
            Console.WriteLine("this is " + res);
            if (res == System.Net.HttpStatusCode.Created)
            {
                var products = await userClient.GetProducts();

                return(View(products));
            }
            return(Content(res.ToString()));
        }
示例#7
0
        public void GenerateExceptionTypeTest(System.Net.HttpStatusCode HttpStatusCode, Type ExceptionExcepted)
        {
            HttpResponseMessage m = new HttpResponseMessage(HttpStatusCode);

            m.Content = new StringContent(HttpStatusCode.ToString());

            if (HttpStatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                APIBadRequestResult BadRequestResult = new APIBadRequestResult();
                BadRequestResult.Add("Name", new List <string> {
                    "The Name field is required.", "The Name ..."
                });

                m.Content = new StringContent(JsonConvert.SerializeObject(BadRequestResult));
            }

            APIResponse <string> response = new APIResponse <string>(m);

            try
            {
                response.GenerateException();

                Assert.True(false, "Une exception aurait dû être générée");
            }
            catch (Exception ex)
            {
                Assert.IsType(ExceptionExcepted, ex);
            }
        }
        private string GetStatusCodeMessage(System.Net.HttpStatusCode statusCode, string reasonPhrase)
        {
            var intCode   = (int)statusCode;
            var resultMsg = statusCode.ToString();

            return($"{intCode} - {resultMsg} - {reasonPhrase}");
        }
        private void ThrowIfStatusNotOk(System.Net.HttpStatusCode statusCode, string responseResult)
        {
            ThrowIfStatusNotOk(statusCode);

            if (string.IsNullOrEmpty(responseResult))
            {
                throw new Exception("response exception : " + statusCode.ToString());
                //throw new HttpResponseException(statusCode);
            }

            var errormsg = JsonConvert.DeserializeObject <JObject>(responseResult);

            var exmsg = errormsg["exceptionMessage"];

            if (exmsg != null)
            {
                JToken outtt;
                if (errormsg.TryGetValue("innerException", out outtt))
                {
                    var inererror = outtt["exceptionMessage"];
                    if (inererror != null)
                    {
                        throw new Exception(inererror + " :");
                    }
                }

                throw new Exception(exmsg + " :");
            }

            throw new Exception(errormsg["message"] + " :");
        }
示例#10
0
 public TFSRestClientException(System.Net.HttpStatusCode httpStatusCode, string p, string content)
     : base(httpStatusCode.ToString() + " - " + p + "\r\n" + content)
 {
     // TODO: Complete member initialization
     this.StatusCode        = httpStatusCode;
     this.StatusDescription = p;
     this.Content           = content;
 }
示例#11
0
 public static RepositoryResponce StatusCodeResponce(System.Net.HttpStatusCode statusCode)
 {
     return(new RepositoryResponce()
     {
         StatusCode = (int)statusCode,
         Message = statusCode.ToString(),
         Succeed = ((int)statusCode >= 200) && ((int)statusCode <= 299)
     });
 }
示例#12
0
        public string Translate(string src, ref bool isError)
        {
            if (!isInit)
            {
                isError = true;

                if (lastError == System.Net.HttpStatusCode.NotFound)
                {
                    return("잘못된 시트 또는 없는 주소입니다.");
                }
                else if (lastError != System.Net.HttpStatusCode.OK)
                {
                    return("에러 : " + lastError.ToString());
                }
                return("초기화 실패 - 현재 사용할 수 없습니다.");
            }
            // 요청 파라미터 정의

            try
            {
                string range = Upload(src);

                Console.WriteLine("src= " + src);
                SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
                Console.WriteLine("Make Request");
                // 결과물 출력
                ValueRange response = request.Execute();
                Console.WriteLine("Execute");

                foreach (var obj in response.Values)
                {
                    if (obj != null)
                    {
                        for (int i = 0; i < obj.Count; i++)
                        {
                            Console.WriteLine("google result = " + obj[i]);
                        }
                    }
                }
                string output = string.Format("{0}", response.Values[0][0]);

                if (output == "#VALUE!")
                {
                    isError = true;
                    return(string.Empty);
                }
                else
                {
                    return(output);
                }
            }
            catch (Exception e)
            {
                isError = true;
                return("처리하는 도중 오류가 발생했습니다" + System.Environment.NewLine + e.Message);
            }
        }
示例#13
0
        private void TestEnumTypes()
        {
            string method_name = "ProcessEnumTypes";

            System.Reflection.MethodInfo method_info = sample_class_type.GetMethod(method_name);
            System.Net.HttpStatusCode    status_code = System.Net.HttpStatusCode.BadGateway;
            method_info.Invoke(sample_class_instance, new System.Object[] { status_code });
            Assert.IsTrue(Logger.CallLogger.LastLog.Contains(sample_class_name + "::" + method_name));
            Assert.IsTrue(Logger.CallLogger.LastLog.Contains(status_code.ToString()));
        }
示例#14
0
        /// <summary>
        /// Generic handling of status responses
        /// See: https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        /// </summary>
        /// <param name="httpStatusCode"></param>
        private void HandleResponse(IRestResponse response)
        {
            System.Net.HttpStatusCode httpStatusCode = response.StatusCode;
            if (httpStatusCode == System.Net.HttpStatusCode.OK ||        //200
                httpStatusCode == System.Net.HttpStatusCode.Created ||   //201
                httpStatusCode == System.Net.HttpStatusCode.NoContent)   //204
            {
                return;
            }
            else
            {
                Console.WriteLine("HttpError:" + httpStatusCode.ToString());
                IList <ApiError> errors;
                try
                {
                    var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer()
                    {
                        RootElement = "errors"
                    };
                    errors = xmlDeserializer.Deserialize <List <ApiError> >(new RestResponse {
                        Content = response.Content
                    });
                }
                catch (Exception) // If there's an issue deserializing the error we still want to raise a fitbit exception
                {
                    errors = new List <ApiError>();
                }

                FitbitException exception = new FitbitException("Http Error:" + httpStatusCode.ToString(), httpStatusCode, errors);

                var retryAfterHeader = response.Headers.FirstOrDefault(h => h.Name == "Retry-After");
                if (retryAfterHeader != null)
                {
                    int retryAfter;
                    if (int.TryParse(retryAfterHeader.Value.ToString(), out retryAfter))
                    {
                        exception.RetryAfter = retryAfter;
                    }
                }
                throw exception;
            }
        }
示例#15
0
        public override string ToString()
        {
            StringBuilder list = new StringBuilder(base.ToString());

            if (_statusCode > 0)
            {
                list.Append("; statusCode=").Append(_statusCode.ToString());
            }
            if (_responseBody != null && _responseBody.Any())
            {
                list.Append("; responseBody='").Append(_responseBody).Append("'");
            }
            return(list.ToString());
        }
示例#16
0
        public static HttpResponseMessage GenerateResponse(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode)
        {
            HttpResponseMessage response = null;

            if (!IsSuccessful(statusCode))
            {
                response = request.GenerateErrorResponse(statusCode, statusCode.ToString());
            }
            else
            {
                response = request.GenerateResponseInternal(statusCode);
            }

            return(response);
        }
示例#17
0
        /// <summary>Writes the response part of the request into a stream (including the status, headers and everything)</summary>
        /// <param name="stream">The stream to write the response into.</param>
        public void WriteResponse(Stream stream)
        {
            System.Net.HttpStatusCode responseStatusCode = (System.Net.HttpStatusCode) this.ResponseStatusCode;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("HTTP/1.1 " + this.ResponseStatusCode.ToString() + " " + responseStatusCode.ToString());
            InMemoryWebRequest.WriteHeadersToStringBuilder(sb, this.ResponseHeaders);
            sb.AppendLine();

            InMemoryWebRequest.WriteStringToStream(stream, sb.ToString());
            if (this.responseStream != null)
            {
                TestUtil.CopyStream(this.GetResponseStream(), stream);
            }
        }
示例#18
0
        public async Task <T> GetAsync <T>(string endpoint, string id, string gettingType)
        {
            System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.OK;
            try
            {
                _logger.LogInformation("GET {@gettingType}: request {@id}", gettingType, id);
                // _logger.LogDebug("GET {@gettingType}: config {@config}", gettingType, _config);
                _logger.LogInformation("GET {@gettingType}: request url {@apiEndpoint}", gettingType, endpoint);

                var result = await _client.GetAsync(endpoint);

                _logger.LogInformation("GET {@gettingType}: Sent request", gettingType);

                if ((int)result.StatusCode < 400)
                {
                    _logger.LogInformation("GET {@gettingType}: status code {@statusCode}", gettingType, result.StatusCode);
                }
                else
                {
                    _logger.LogError("GET {@gettingType}: status code {@statusCode}", gettingType, result.StatusCode);
                }

                statusCode = result.StatusCode;

                result.EnsureSuccessStatusCode();
                var stringResult = await result.Content.ReadAsStringAsync();

                _logger.LogInformation("GET {@gettingType}: result {@result}", gettingType, result);

                var accessModelResponse = JsonConvert.DeserializeObject <T>(stringResult);

                return(accessModelResponse);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "GET {@gettingType}: FAILED - Unable to GET.", gettingType);
                _logger.LogCritical(ex, "GET Exception: {ex}", ex);
                throw new ApiException(ex, (int)statusCode, new List <string> {
                    ex.Message, statusCode.ToString()
                });
            }
        }
示例#19
0
        public async Task <HttpStatusCode?> GetAsync(System.Net.HttpStatusCode httpStatusCode)
        {
            byte[]? data = await IDistributedCache.GetAsync($"{ParameterName}{httpStatusCode.ToString()}");

            if (data is object)
            {
                return(JsonSerializer.Deserialize <HttpStatusCode>(data));
            }
            else
            {
                HttpStatusCode?HttpStatusCode = await IHttpStatusCodeRepository.GetByCode(httpStatusCode);

                if (HttpStatusCode is object)
                {
                    await this.SetAsync(HttpStatusCode);

                    return(HttpStatusCode);
                }
                return(null);
            }
        }
        public void WebSiteAPIPostDataBackendService()
        {
            // assigning categories for reports
            extentReportsTest.AssignCategory("Regression", "WebSiteAPI");

            // test case variables
            string apiUrl = "https://httpbin.org/post/1";
            var    client = new RestClient(apiUrl);

            // logging step for get command
            extentReportsTest.Log(LogStatus.Info, "MRN-304: API Post", "API POST to obtain Status");

            // executed an API get to the specified URL can getting status code
            IRestResponse response = client.Post(new RestRequest());

            System.Net.HttpStatusCode statusCode = response.StatusCode;

            // logging step for get command
            extentReportsTest.Log(LogStatus.Info, "MRN-304: API Status Code", "API Status Recieved");

            // verifying status code is 200 (OK = the request was received )
            StringAssert.AreEqualIgnoringCase("OK", statusCode.ToString());
        }
示例#21
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                System.Net.HttpStatusCode defaultStatus = System.Net.HttpStatusCode.InternalServerError;
                WebApiResponse            response      = new WebApiResponse();
                System.Net.HttpStatusCode status        = defaultStatus;

                if (context.Exception is WebApiException webApiException)
                {
                    status   = (System.Net.HttpStatusCode)webApiException.Status;
                    response = response.Fail((System.Net.HttpStatusCode)webApiException.Status);
                }
                else if (context.Exception is System.UnauthorizedAccessException unauthorizedException)
                {
                    status = System.Net.HttpStatusCode.Unauthorized;
                }

                string message = "";

                if (System.String.IsNullOrEmpty(message))
                {
                    message = (System.String.IsNullOrEmpty(context.Exception.Message)) ? status.ToString() : context.Exception.Message;
                }

                response = new WebApiResponse().Fail(status).SetMessage(message);

                context.Result = new ObjectResult(response)
                {
                    StatusCode = (int)status
                };

                _logger.LogError(context.Exception, "Exception capturada en filtro");

                context.ExceptionHandled = true;
            }
        }
示例#22
0
 public ErrorResponse(Error error, INancyEnvironment env,
                      HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
     : base(error, new JsonNetSerializer(new CustomJsonSerializer()), env)
 {
     // TODO: this might fail if the status code enums are not identical
     StatusCode = (Nancy.HttpStatusCode)Enum.Parse(typeof(Nancy.HttpStatusCode), statusCode.ToString());
 }
示例#23
0
        } // End Task Invoke

        // https://stackoverflow.com/questions/35599050/correct-way-to-notify-http-client-of-error-after-partial-response-has-been-sent
        private static System.Threading.Tasks.Task HandleUnsuccessfullStatusAsync(Microsoft.AspNetCore.Http.HttpContext context)
        {
            int code = context.Response.StatusCode;

            System.Net.HttpStatusCode hc = (System.Net.HttpStatusCode)code;

            // if (exception is MyNotFoundException) code = System.Net.HttpStatusCode.NotFound;
            // else if (exception is MyUnauthorizedException) code = System.Net.HttpStatusCode.Unauthorized;
            // else if (exception is MyException) code = System.Net.HttpStatusCode.BadRequest;

            string result = Newtonsoft.Json.JsonConvert.SerializeObject(new { error = hc.ToString() });

            context.Response.Headers.Clear();
            context.Response.Clear();

            context.Response.StatusCode  = (int)code;
            context.Response.ContentType = "application/json";

            return(context.Response.WriteAsync(result));
        } // End Task HandleUnsuccessfullStatusAsync
示例#24
0
 public async Task <HttpStatusCode?> GetByCode(System.Net.HttpStatusCode httpStatusCode)
 {
     return(await DbSet.SingleOrDefaultAsync(x => x.Code == httpStatusCode.ToString()));
 }
示例#25
0
 public RequestException(System.Net.HttpStatusCode response, string message)
     : base("Response came back as " + response.ToString())
 {
     this.ResponseCode       = response;
     this.ServerErrorMessage = message;
 }
示例#26
0
 private string FormatHTTPStatusCodeAsString(System.Net.HttpStatusCode HttpStatusCode)
 {
     return($"{((int)HttpStatusCode).ToString()} {HttpStatusCode.ToString()}");
 }
示例#27
0
 /// <summary>
 /// Client端本地版本对比服务端js版本,来决定是否清缓
 /// </summary>
 public bool UpdateJSVersion(string xmlPath)
 {
     #region 清理IE缓存,失败如果,retry 3次
     bool updateXML = false;
     try
     {
         string requestServerUrl = AppSettings.GetJSVersionService.Replace("{JavaHost}", AppSettings.JavaHost);
         string httpResponseJson = string.Empty;
         System.Net.HttpStatusCode httpStatusCode = HttpHelper.HttpPostRequest(requestServerUrl, string.Empty, ref httpResponseJson);
         if (httpStatusCode.Equals(System.Net.HttpStatusCode.OK))
         {
             JObject obj = JObject.Parse(httpResponseJson);
             if (obj.GetValue("status").ToString().ToUpperInvariant().Equals("000"))
             {
                 string  data    = obj.GetValue("data").ToString().Replace("[", "").Replace("]", "");
                 JObject objdata = JObject.Parse(data);
                 httpResponseJson = objdata.GetValue("jsVersion").ToString();
                 if (!httpResponseJson.Equals(AppSettings.UserConfiguration.JSInformation.JSVersion))
                 {
                     ClearIECache();
                     AppSettings.UserConfiguration.JSInformation.JSVersion = httpResponseJson;
                     updateXML = true;
                 }
             }
         }
         else
         {
             LogHelper.WriteErrorLog(string.Format("Post HttpResponseCode:{0},Url:{1},Response:{2}", httpStatusCode.ToString(), requestServerUrl, httpResponseJson));
             ClearIECache();
         }
         return(updateXML);
     }
     catch (Exception ex)
     {
         LogHelper.WriteErrorInfoLog(" 清理IE缓存异常", ex);
         return(updateXML);
     }
     finally
     {
         LogHelper.WriteMethodLog(false);
     }
     #endregion
 }
示例#28
0
 public UnsuccessfulRequestException(System.Net.HttpStatusCode statusCode)
     : base($"Is not a success status code. Code: {statusCode.ToString()}.")
 {
 }
示例#29
0
 public async Task RemoveAsync(System.Net.HttpStatusCode httpStatusCode)
 {
     await IDistributedCache.RemoveAsync($"{ParameterName}{httpStatusCode.ToString()}");
 }
示例#30
0
        public static ResponseModel Error(int httpStatusCode, string message = null)
        {
            System.Net.HttpStatusCode s = (System.Net.HttpStatusCode)httpStatusCode;
            switch (s)
            {
            case System.Net.HttpStatusCode.OK:
            case System.Net.HttpStatusCode.Created:
            case System.Net.HttpStatusCode.NoContent: return(new ResponseModel(ResponseCode.Ok, message));

            case System.Net.HttpStatusCode.Conflict: return(new ResponseModel(ResponseCode.Duplicate, message));

            default: return(new ResponseModel(ResponseCode.Provider_Error, $"status: {s.ToString()} -> {message}"));
            }
        }