Пример #1
0
 public SystemEventLogService(IRepository <SystemEventLog, Guid> repository,
                              IUnitOfWork unitOfWork,
                              CurrentSystemCallInfo currentSystemCallInfo)
 {
     _repository            = repository;
     _currentSystemCallInfo = currentSystemCallInfo;
     _unitOfWork            = unitOfWork;
 }
Пример #2
0
        public async Task Invoke(HttpContext context, ISystemCallService systemCallService, CurrentSystemCallInfo currentSystemCallInfo)
        {
            //code dealing with request

            //First, get the incoming request
            var requestLog = await FormatRequest(context.Request).ConfigureAwait(false);

            //Copy a pointer to the original response body stream
            var originalBodyStream = context.Response.Body;

            currentSystemCallInfo.Id = await systemCallService.Create(new SystemCall()
            {
                InputWay      = context.Request.Method + " " + context.Request.GetDisplayUrl(),
                InputData     = requestLog,
                InputMetaData = $"{{\"ClientIp\":\"{context.Connection.RemoteIpAddress}\", \"Scheme\": \"{context.Request.Scheme}\",\"Host\":\"{context.Request.Host}\",\"Headers\":\"{context.Request.Headers}\",\"Path\":\"{context.Request.Path}\",\"QueryStrings\":\"{context.Request.QueryString}\",\"Method\":\"{context.Request.Method}\"}}"
            }).ConfigureAwait(false);

            //Create a new memory stream...
            using (var responseBody = new MemoryStream())
            {
                //...and use that for the temporary response body
                context.Response.Body = responseBody;

                await _next(context).ConfigureAwait(false);

                var responseLog = await FormatResponse(context.Response).ConfigureAwait(false);

                await systemCallService.Update(currentSystemCallInfo.Id, responseLog).ConfigureAwait(false);

                //In Case If We Only want Api log
                //We should save log only if we are calling our web api class
                //var routeData = context.GetRouteData();
                //if (routeData != null)
                //{
                //    var controller = context.GetRouteData().Values["Controller"];
                //    if (!string.IsNullOrEmpty(controller.ToString()))
                //    {
                //        var controllerClass = Array.Find(
                //            Assembly.GetExecutingAssembly().GetTypes(),
                //            x => typeof(BaseApiController).IsAssignableFrom(x) && x.Name.Contains(controller.ToString()));

                //        if (controllerClass != null)
                //        {
                //            //Format the response from the server
                //            var response = await FormatResponse(context.Response).ConfigureAwait(false);
                //            //save log to database
                //            var log = requestLog + "</br>" + response;
                //        }
                //    }
                //}

                //Copy the contents of the new memory stream (which contains the response) to the original stream, which is then returned to the client.
                await responseBody.CopyToAsync(originalBodyStream).ConfigureAwait(false);
            }
        }
Пример #3
0
        /// <summary>
        /// Invoke method which runs on middle ware , when a request come out from application
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpContext, CurrentSystemCallInfo currentSystemCallInfo)
        {
            //prop initialization
            //var status = ResponseStatus.UnhandledError;
            //var message = SystemErrorResourceKeys.SystemUnhandledException;
            var responseObject = new object();

            bool hasError = true;

            try
            {
                await _next(httpContext);

                hasError = false;

                var message = "";

                //Success message of web api
                switch (httpContext.Request.Method.ToLower())
                {
                case "post":
                    message = SystemMessagesResourceKeys.PostSuccess;
                    httpContext.Response.StatusCode = StatusCodes.Status201Created;
                    break;

                case "get":
                    message = SystemMessagesResourceKeys.GetSuccess;
                    break;

                case "put":
                    message = SystemMessagesResourceKeys.PutSuccess;
                    break;

                case "delete":
                    message = SystemMessagesResourceKeys.DeleteSuccess;
                    break;

                default:
                    message = "نتیجه نامعلوم";
                    httpContext.Response.StatusCode = StatusCodes.Status200OK;
                    break;
                }


                if (httpContext.Response.Body.Length == 0)
                {
                    //httpContext.Response.Clear();
                    httpContext.Response.ContentType = "application/json";
                    string json = JsonConvert.SerializeObject(new { Message = message });
                    await httpContext.Response.WriteAsync(json).ConfigureAwait(false);
                }
            }
            catch (ValidationException ex)
            {
                httpContext.Response.Clear();
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = StatusCodes.Status400BadRequest;

                var properties = new List <string>();

                var validationMessages = ex.Errors.Select(error =>
                {
                    if (!properties.Any(c => c == error.PropertyName))
                    {
                        //In case if error message is: A non-empty request body is required.
                        if (string.IsNullOrEmpty(error.PropertyName))
                        {
                            return(new ValidationMessage
                            {
                                PropertyName = "RequestBody",
                                Messages = new List <string> {
                                    ValidationResourceKeys.RequestBodyNull
                                }
                            });
                        }

                        var validationMessage = new ValidationMessage
                        {
                            PropertyName = error.PropertyName,
                            Messages     = ex.Errors.Where(x => x.PropertyName.Equals(error.PropertyName))
                                           .Select(x => x.ErrorMessage)
                        };
                        properties.Add(error.PropertyName);
                        return(validationMessage);
                    }
                    else
                    {
                        return(null);
                    }
                }).Where(x => x != null).AsEnumerable();

                responseObject = new { Message = ValidationResourceKeys.ValidationErrorMessage, validationMessages };
            }
            catch (EntityNotFoundException ex)
            {
                httpContext.Response.Clear();
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = StatusCodes.Status404NotFound;
                responseObject = new { ex.Message };
            }
            catch (UserFriendlyException ex)
            {
                httpContext.Response.Clear();
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = StatusCodes.Status500InternalServerError;
                responseObject = new { ex.Message };
            }
            catch (Exception ex)
            {
                httpContext.Response.Clear();
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = StatusCodes.Status500InternalServerError;

                if (_env.IsDevelopment())
                {
                    responseObject = new { Message = SystemErrorResourceKeys.SystemUnhandledException, Exception = ex };
                }
                else
                {
                    var elmahError = new Error(ex);
                    elmahError.User = currentSystemCallInfo.Id.ToString();

                    //Log in elmah
                    //Log error with elmah before create response
                    if (Startup.SiteSettings.ActiveDatabase == ActiveDatabase.SqlServer)
                    {
                        ErrorLog errorLog = new SqlErrorLog(Startup.SiteSettings.GetDbConnectionString())
                        {
                            ApplicationName = "GhabzeTo"
                        };
                        await errorLog.LogAsync(elmahError).ConfigureAwait(false);
                    }
                    else if (Startup.SiteSettings.ActiveDatabase == ActiveDatabase.PostgreSQL)
                    {
                        ErrorLog errorLog = new PgsqlErrorLog(Startup.SiteSettings.GetDbConnectionString())
                        {
                            ApplicationName = "GhabzeTo"
                        };
                        await errorLog.LogAsync(elmahError).ConfigureAwait(false);
                    }

                    responseObject = new { Message = SystemErrorResourceKeys.SystemUnhandledException };
                }
            }

            if (hasError)
            {
                string json = JsonConvert.SerializeObject(responseObject);
                await httpContext.Response.WriteAsync(json).ConfigureAwait(false);
            }
        }