コード例 #1
0
        /// <summary>
        /// Запись информации в LOG-файл
        /// </summary>
        /// <param name="ResponseData">Объект, содержащий результаты вызова метода удаленного сервиса/param>
        public void WriteLog(ResponseData ResponseData)
        {
            double previousTime = 0D;
            string timingFormat = "\t{0,10:0.0000}";

            string message = String.Format("\r\n\r\n______________________________________\r\n\r\n{0:dd.MM.yyyy} {0:HH:mm:ss.fff}   -   {1}", ResponseData.StartTime, ResponseData.ActionURL);



            if (ResponseData.Request != null)
            {
                message += String.Format("\r\nRequestType: {0}", ResponseData.Request.GetType().FullName);
            }

            if (ResponseData.Response != null)
            {
                message += String.Format("\r\nResponseType: {0}", ResponseData.Response.GetType().FullName);
            }


            if (!String.IsNullOrEmpty(ResponseData.JsonRequest))
            {
                message += String.Format("\r\n\r\n--- JsonRequest: ---\r\n{0}", ResponseData.JsonRequest);
            }

            if (!String.IsNullOrEmpty(ResponseData.JsonResponse))
            {
                message += String.Format("\r\n\r\n--- JsonResponse: ---\r\n{0}", ResponseData.JsonResponse);
            }


            if (!String.IsNullOrEmpty(ResponseData.ResponseURL))
            {
                message += String.Format("\r\n\r\nResponseURL: {0}", ResponseData.ResponseURL);
                message += String.Format("\r\nStatusCode: {0} [ {1} - {2} ]\r\n", ResponseData.StatusCode, (int)ResponseData.StatusCode, ResponseData.StatusName);
            }


            if (ResponseData.IsError)
            {
                message += "\r\n";

                if (!String.IsNullOrEmpty(ResponseData.ErrorMessage))
                {
                    message += String.Format("\r\n\r\nErrorMessage:\r\n{0}", ResponseData.ErrorMessage);
                }

                if (!String.IsNullOrEmpty(ResponseData.ExceptionTypeName))
                {
                    message += String.Format("\r\n\r\nExceptionTypeName:\r\n{0}", ResponseData.ExceptionTypeName.ToString());
                }

                if (!String.IsNullOrEmpty(ResponseData.ExceptionMessage))
                {
                    message += String.Format("\r\n\r\nExceptionMessage:\r\n{0}", ResponseData.ExceptionMessage);
                }
            }


            if (ResponseData.JsonSerializeTime > 0D)
            {
                message     += String.Format("\r\nJsonSerializeTime:" + timingFormat, ResponseData.JsonSerializeTime - previousTime);
                previousTime = ResponseData.JsonSerializeTime;
            }

            if (ResponseData.RequestStreamWriteTime > 0D)
            {
                message     += String.Format("\r\nRequestStreamWriteTime:" + timingFormat, ResponseData.RequestStreamWriteTime - previousTime);
                previousTime = ResponseData.RequestStreamWriteTime;
            }

            if (ResponseData.GetResponseTime > 0D)
            {
                message     += String.Format("\r\nGetResponseTime:" + timingFormat, ResponseData.GetResponseTime - previousTime);
                previousTime = ResponseData.GetResponseTime;
            }

            if (ResponseData.ResponseStreamReadTime > 0D)
            {
                message     += String.Format("\r\nResponseStreamReadTime:" + timingFormat, ResponseData.ResponseStreamReadTime - previousTime);
                previousTime = ResponseData.ResponseStreamReadTime;
            }

            if (ResponseData.JsonDeserializeTime > 0D)
            {
                message     += String.Format("\r\nJsonDeserializeTime:" + timingFormat, ResponseData.JsonDeserializeTime - previousTime);
                previousTime = ResponseData.JsonDeserializeTime;
            }

            if (ResponseData.WebExceptionBeginTime > 0D)
            {
                message     += String.Format("\r\nWebExceptionBeginTime: " + timingFormat, ResponseData.WebExceptionBeginTime - previousTime);
                previousTime = ResponseData.WebExceptionBeginTime;
            }

            if (ResponseData.WebExceptionEndTime > 0D)
            {
                message     += String.Format("\r\nWebExceptionEndTime:" + timingFormat, ResponseData.WebExceptionEndTime - previousTime);
                previousTime = ResponseData.WebExceptionEndTime;
            }

            if (ResponseData.EndTime > 0D)
            {
                message += String.Format("\r\n\r\nFullTime:\t" + timingFormat, ResponseData.EndTime);
            }


            try
            {
                System.IO.File.AppendAllText
                (
                    String.Format(@"{0}\{1}_{2:yyyy-MM-dd}.log", LogFileDir, LogFileName, DateTime.Now.Date), message
                );
            }
            catch { }
        }
コード例 #2
0
ファイル: Adapter.cs プロジェクト: Sllayar/RestApiAdapter
        /// <summary>
        /// Вызов метода удаленного сервиса
        /// </summary>
        /// <typeparam name="TRequest">Тип контракта (.NET) входного параметра (Если нет - можно указать любой, обязательно - Nullable)</typeparam>
        /// <typeparam name="TResponse">Тип контракта (.NET) ожидаемого по результатам выполнения метода</typeparam>
        /// <param name="HttpWebRequest">Экземпляр HttpWebRequest созданный в вызывающем сервисе</param>
        /// <param name="Request">Контракт (.NET) входного параметра, если не используется - NULL</param>
        /// <returns>Объект ResponseData</returns>
        public ResponseData RunREST <TRequest, TResponse>(HttpWebRequest HttpWebRequest, TRequest Request)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();


            ResponseData result = new ResponseData()
            {
                HttpWebRequest = HttpWebRequest,
                Request        = Request
            };


            try
            {
                if (Request != null)
                {
                    //Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
                    //{
                    //	NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                    //};

                    result.JsonRequest       = Newtonsoft.Json.JsonConvert.SerializeObject(Request);
                    result.JsonSerializeTime = stopwatch.Elapsed.TotalMilliseconds;


                    using (Stream requestStream = HttpWebRequest.GetRequestStream())
                    {
                        requestStream.Write(_enc.GetBytes(result.JsonRequest), 0, _enc.GetByteCount(result.JsonRequest));
                        result.RequestStreamWriteTime = stopwatch.Elapsed.TotalMilliseconds;
                    }
                }


                using (HttpWebResponse response = (HttpWebResponse)HttpWebRequest.GetResponse())
                {
                    result.HttpWebResponse = response;

                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result.GetResponseTime        = stopwatch.Elapsed.TotalMilliseconds;
                        result.JsonResponse           = reader.ReadToEnd();
                        result.ResponseStreamReadTime = stopwatch.Elapsed.TotalMilliseconds;


                        if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
                        {
                            result.ErrorMessage = result.JsonResponse;
                        }
                        else
                        {
                            // При возникновении исключения NewtonSoft не выдает поле в котором происходит ошибка во время
                            // десериализации, поэтому реализован костыль, который бросает дополнительное сообщение,
                            // содержащее название такого поля. Результат хранится в ExceptionHelpMessage.

                            Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer();
                            jsonSerializer.Error += AddToError;

                            result.Response = jsonSerializer.Deserialize <TResponse>(
                                new Newtonsoft.Json.JsonTextReader(new StringReader(result.JsonResponse)));

                            //result.Response = (Newtonsoft.Json.JsonConvert.DeserializeObject<TResponse>(result.JsonResponse));
                            result.JsonDeserializeTime = stopwatch.Elapsed.TotalMilliseconds;
                        }
                    }

                    response.Close();
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    result.WebExceptionBeginTime = stopwatch.Elapsed.TotalMilliseconds;
                    HttpWebResponse response = (HttpWebResponse)ex.Response;

                    result.HttpWebResponse = response;

                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result.ErrorMessage = reader.ReadToEnd();
                    }
                }

                result.ResponseException = ex;

                result.WebExceptionEndTime = stopwatch.Elapsed.TotalMilliseconds;
            }
            catch (Exception ex)
            {
                result.ResponseException = ex;
            }

            result.EndTime = stopwatch.Elapsed.TotalMilliseconds;

            TryPrcessException(result);

            TryWriteLog(result);

            return(result);
        }
コード例 #3
0
 public Logger(ResponseData result, string logFileDir, string logFileName)
 {
     Result      = result;
     LogFileDir  = logFileDir;
     LogFileName = logFileName;
 }