Exemple #1
0
        public void LogError(ErrorLogModel errorlog, int StaffId = 0)
        {
            try
            {
                string usercode = string.Empty;
                if (errorlog != null)
                {
                    if (StaffId > 0)
                    {
                        usercode = _ctx.Staffs
                                   .Where(s => s.StaffId == StaffId)
                                   .Select(s => s.UserCode).FirstOrDefault();
                    }
                    else
                    {
                        usercode = "CommonUser";
                    }

                    _ctx.ssp_SCLogError(errorlog.ErrorMessage, errorlog.VerboseInfo, errorlog.ErrorType, usercode, DateTime.Now, errorlog.DataSetInfo);
                }
            }
            catch (Exception ex)
            {
                Exception excep = new Exception("Exception occured in ErrorLogRepository.LogError method." + ex.Message);
                throw excep;
            }
        }
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                StackTrace trace      = new StackTrace(filterContext.Exception, true);
                StackFrame stackFrame = trace.GetFrame(trace.FrameCount - 1);
                //string fileName = stackFrame.GetFileName();
                //string methodName = stackFrame.GetMethod().Name;

                ErrorLog el = new ErrorLog()
                {
                    ErrorLogId       = 0,
                    ErrorDescription = filterContext.Exception.Message,
                    ErrorReportedOn  = DateTime.Now,
                    ErrorStack       = filterContext.Exception.StackTrace.Trim(),
                    //ErrorSource = filterContext.Exception.Source,
                    //ErrorMethod = stackFrame.GetMethod().Name,
                    ErrorSource = filterContext.RouteData.Values["controller"].ToString(),
                    ErrorMethod = filterContext.RouteData.Values["action"].ToString(),
                    UserId      = HttpContext.Current.Session != null?Convert.ToInt32(HttpContext.Current.Session["UserId"]) : 0,
                };

                string version = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Status");
                //if (!version.ToLower().Equals("dev"))
                //{
                filterContext.ExceptionHandled = true;
                int error = new ErrorLogModel().Save(el);
                //}
                HttpContext ctx = HttpContext.Current;
                ctx.Response.Redirect("~/Login/ReDoLogin");
            }
        }
Exemple #3
0
        public JsonResult Detail(string id)
        {
            try
            {
                #region " [ Declaration ] "

                ErrorLogService _service = new ErrorLogService();
                //
                ViewBag.id = id;

                #endregion

                //Call to service
                ErrorLogModel model = _service.GetItemByID(new ErrorLogModel()
                {
                    ID = new Guid(id), CreateBy = UserID
                });

                return(this.Json(model, JsonRequestBehavior.AllowGet));
            }
            catch (ServiceException serviceEx)
            {
                throw serviceEx;
            }
            catch (DataAccessException accessEx)
            {
                throw accessEx;
            }
            catch (Exception ex)
            {
                throw new ControllerException(FILE_NAME, "Detail", UserID, ex);
            }
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;

            filterContext.ExceptionHandled = true;

            //var errorLog = DependencyResolver.Current.GetService<IErrorLogRepository>();
            //CommonHelper.AddErrorLog(errorLog, ex, ErrorTypeEnum.Website.ToString(), "");

            EmailHelper objEmailHelper = new EmailHelper(_dbErrorHandlingService);

            ErrorLogModel objErrorLog = new ErrorLogModel();

            objErrorLog.ErrorInnerException = ex.InnerException != null?ex.InnerException.ToString() : "";

            objErrorLog.ErrorInnerExceptionMessage = ex.InnerException != null?ex.InnerException.Message.ToString() : "";

            objErrorLog.ErrorMessage   = ex.Message.ToString();
            objErrorLog.ErrorTimeStamp = DateTime.Now;
            objErrorLog.StackTrace     = ex.StackTrace.ToString();

            EmailHelper.AddErrorLog(objErrorLog);
            TempData["error"]    = ex;
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Error" }));
        }
Exemple #5
0
        public override void OnException(ExceptionContext context)
        {
            var error = new
            {
                Success = false,
                Errors  = new [] { context.Exception.Message }
            };

            context.Result = new ObjectResult(error)
            {
                StatusCode = 500
            };
            context.Result = new ObjectResult(error)
            {
                StatusCode = 400
            };


            ErrorLogModel errorLog = new ErrorLogModel
            {
                ErrorTime        = DateTime.UtcNow,
                RequestId        = context.HttpContext.TraceIdentifier,
                StackTrace       = context.Exception.StackTrace,
                StatusCode       = context.Exception.HResult,
                ExceptionMessage = context.Exception.Message
            };

            _context.ErrorLog.Add(errorLog);
            _context.SaveChanges();

            context.ExceptionHandled = true;
        }
Exemple #6
0
        public ActionResult Index(GridCommand command, ErrorLogModel model)
        {
            if (!PermissionService.Authorize(PermissionProvider.ErrorView))
            {
                return(AccessDeniedView());
            }

            int totalRecords = 0;
            var query        = _unitOfWork.ErrorRepository.GetAsQuerable().OrderByDescending(x => x.CreatedOn);
            var errorLog     = query.ApplyGridCommandsWithPaging(command, out totalRecords);

            var errorList = errorLog.Select(error => new ErrorLogModel
            {
                Id           = error.Id,
                IpAddress    = error.IpAddress,
                PageUrl      = error.PageUrl,
                ShortMessage = error.ShortMessage,
                FullMessage  = error.FullMessage,
                CreatedOn    = error.CreatedOn
            }).ToList();

            var gridModel = new GridModel <ErrorLogModel>
            {
                Data  = errorList,
                Total = totalRecords
            };

            return(View(gridModel));
        }
        /// <summary>
        /// 插入一条错误日志
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public int InsertErrorLog(Exception e)
        {
            int result = -1;

            //构成一个错误日志对象
            ErrorLogModel log = new ErrorLogModel()
            {
                ExceptionType    = e.GetType().ToString(),
                CreateTime       = DateTime.Now,
                ExceptionContent = e.Message,
                Others           = string.Format("Exception Source : {0} \t Exception HResult : {1}", e.Source, e.HResult)
            };

            // 开始插入
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), DataBaseControlImpl.DBPath))
                {
                    result = conn.Insert(log);
                    Debug.WriteLine("写入错误日志:");
                }
            }
            catch (Exception)
            {
                // 出现异常则在控制台输出!
                Debug.WriteLine("写入错误日志失败!日志内容为:" + log.ToString());
            }
            return(result);
        }
        // GET: Error
        public ActionResult Index()
        {
            string    CurrentController    = (string)this.RouteData.Values["controller"];
            string    CurrentAction        = (string)this.RouteData.Values["action"];
            int       CurrentExceptionCode = (int)this.RouteData.Values["exceptioncode"];
            Exception ex = (Exception)this.RouteData.Values["exception"];

            TempData["exceptioncode"] = CurrentExceptionCode;
            if (CurrentExceptionCode == 404)
            {
                TempData["headermessage"] = "Page not found.";
            }
            else if (CurrentExceptionCode == 403)
            {
                TempData["headermessage"] = "Access denied.";
            }
            else
            {
                TempData["headermessage"] = "";
            }

            ErrorLogModel log = LogHelper.LogError(ex, true);

            return(View(log));
        }
        public ActionResult Errores()
        {
            ErrorLogModel model = new ErrorLogModel();

            ViewBag.Errores = ErrorLogModel.CargarErrores();
            return(View());
        }
Exemple #10
0
        public void OnException(ExceptionContext filterContext)
        {
            string _BaseURL     = ConfigurationManager.AppSettings["BaseURL"].ToString();
            string _RedirectURL = _BaseURL + "/Login/ReDoLogin";

            StackTrace trace      = new StackTrace(filterContext.Exception, true);
            StackFrame stackFrame = trace.GetFrame(trace.FrameCount - 1);
            //string fileName = stackFrame.GetFileName();
            //string methodName = stackFrame.GetMethod().Name;

            ErrorLog el = new ErrorLog()
            {
                ErrorLogId       = 0,
                ErrorDescription = filterContext.Exception.Message,
                ErrorReportedOn  = DateTime.Now,
                ErrorStack       = filterContext.Exception.StackTrace.Trim(),
                //ErrorSource = filterContext.Exception.Source,
                //ErrorMethod = stackFrame.GetMethod().Name,
                ErrorSource = filterContext.RouteData.Values["controller"].ToString(),
                ErrorMethod = filterContext.RouteData.Values["action"].ToString(),
                UserId      = HttpContext.Current.Session != null?Convert.ToInt32(HttpContext.Current.Session["UserId"]) : 0,
            };
            string version = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Status");

            filterContext.ExceptionHandled = true;
            int error = new ErrorLogModel().Save(el);

            //if (!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException)
            //{
            //    filterContext.Result = new RedirectResult("~/Jobs/Index");
            //    filterContext.ExceptionHandled = true;
            //}
            filterContext.Result           = new RedirectResult(_RedirectURL);
            filterContext.ExceptionHandled = true;
        }
Exemple #11
0
        public TResponse AddErrorLog(ErrorLogModel model)
        {
            TResponse     objResponse = new TResponse();
            ErrorLogModel adminModel  = new ErrorLogModel();

            try
            {
                using (var db = new UnitOfWork())
                {
                    ErrorLog objErrorLog = new ErrorLog();
                    objErrorLog.ClassName  = model.ClassName;
                    objErrorLog.MethodName = model.MethodName;
                    objErrorLog.Error      = model.Error;
                    objErrorLog.CreatedOn  = DateTime.Now;
                    objErrorLog            = db.ErrorLogRepository.Insert(objErrorLog);

                    objResponse.Message        = ResponseMessage.success;
                    objResponse.Status         = ResponseStaus.ok;
                    objResponse.ResponsePacket = "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //objResponse.Message = ResponseMessage.error;
                //objResponse.Status = ResponseStatus.error;
                //objResponse.ResponsePacket = model;
            }

            return(objResponse);
        }
Exemple #12
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Deletes the given log. </summary>
        ///
        /// <remarks>   Msacli, 24.04.2019. </remarks>
        ///
        /// <param name="log">  The log to save. </param>
        ///
        /// <returns>   An int. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public int Delete(ErrorLogModel log)
        {
            if (log == null)
            {
                return(CoreConstants.NullLogResponse);
            }

            if (string.IsNullOrWhiteSpace(log.Id))
            {
                return(CoreConstants.EmptyLogIdResponse);
            }

            var emptystring = Guid.Empty.ToString();

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            emptystring = emptystring.Replace('-', '\0');

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            var deleteResult = this.Collection.DeleteOne(q => q.Id == log.Id);

            return((int)deleteResult.DeletedCount);
        }
        protected void Application_Error()
        {
            HttpContext httpContext = HttpContext.Current;
            var         exception   = Server.GetLastError();

            if (httpContext != null && (exception != null))
            {
                var httpException = exception as HttpException;
                int ExceptionCode = httpException.GetHttpCode();

                if (httpContext.Request.Url.AbsoluteUri == Request.Url.GetLeftPart(UriPartial.Authority) + "/")
                {
                    ErrorLogModel log = LogHelper.LogError(exception, true);
                }
                else
                {
                    Response.Clear();
                    Server.ClearError();
                    Response.TrySkipIisCustomErrors = true;
                    var routeData = new RouteData();
                    routeData.Values["controller"]           = "Error";
                    routeData.Values["action"]               = "Index";
                    routeData.Values["exception"]            = exception;
                    routeData.Values["exceptioncode"]        = ExceptionCode;
                    HttpContext.Current.Response.ContentType = "text/html";

                    IController errorsController = new Controllers.ErrorController();
                    var         rc = new RequestContext(new HttpContextWrapper(Context), routeData);
                    errorsController.Execute(rc);
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Get item
        /// </summary>
        /// <param name="model">Error log model</param>
        /// <returns>RoleModel. Throw exception if not found or get some error</returns>
        public ErrorLogModel GetItemByID(ErrorLogModel model)
        {
            ErrorLogModel _return = new ErrorLogModel()
            {
                ID = Guid.NewGuid()
            };

            try
            {
                using (var _context = new TDHEntities())
                {
                    var _item = _context.WEB_ERROR_LOG.FirstOrDefault(m => m.id == model.ID);
                    if (_item != null)
                    {
                        _return = new ErrorLogModel()
                        {
                            ID             = _item.id,
                            FileName       = _item.file_name,
                            Message        = _item.message,
                            MethodName     = _item.method_name,
                            DateString     = _item.create_date.DateToString("dd/MM/yyyy HH:mm:ss"),
                            InnerException = _item.inner_exception,
                            StackTrace     = _item.stack_trace
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException(FILE_NAME, MethodInfo.GetCurrentMethod().Name, model.CreateBy, ex);
            }
            return(_return);
        }
Exemple #15
0
        public static ErrorLogModel LogError(Exception exception, Boolean returnLog)
        {
            try
            {
                using (var db = new ApplicationDBContext())
                {
                    ErrorLogModel log = new ErrorLogModel
                    {
                        Message    = exception.Message + "\n" + exception.GetBaseException(),
                        StackTrace = exception.StackTrace,
                        Datetime   = DateTime.UtcNow
                    };
                    db.ErrorLog.Add(log);
                    db.SaveChanges();
                    return(log);
                }
            }
            catch
            {
                try
                {
                    WriteErrorToFile(exception);
                }
                catch
                {
                    //No need
                }
            }

            return(null);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Deletes the given log. </summary>
        ///
        /// <remarks>   Mustafa SAÇLI, 26.04.2019. </remarks>
        ///
        /// <param name="log">  The log to save. </param>
        ///
        /// <returns>   An int. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public virtual int Delete(ErrorLogModel log)
        {
            if (log == null)
            {
                return(CoreConstants.NullLogResponse);
            }

            if (string.IsNullOrWhiteSpace(log.Id))
            {
                return(CoreConstants.EmptyLogIdResponse);
            }

            var emptystring = Guid.Empty.ToString();

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            emptystring = emptystring.Replace('-', '\0');

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            var result = -1;

            using (var connection = GetConnection())
            {
                try
                {
                    using (var transaction = connection.OpenAndBeginTransaction())
                    {
                        try
                        {
                            var dictionary = new Dictionary <string, object>();
                            dictionary.Add("@Id", log.Id);
                            result =
                                connection.Execute("DELETE FROM ErrorLog WHERE Id=@Id",
                                                   transaction: transaction, inputParameters: dictionary);

                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
                finally
                {
                    connection.CloseIfNot();
                }
            }

            return(result);
        }
        public void AddLog(ErrorLogModel errorLogModel)
        {
            ErrorLogs _errorLogs = new ErrorLogs();

            _errorLogs = Mapper.Map <ErrorLogModel, ErrorLogs>(errorLogModel);
            _context.ErrorLogs.Add(_errorLogs);
            _context.SaveChanges();
        }
Exemple #18
0
        public string CreateOrganization(OrganizationModel objOrg)
        {
            string status = string.Empty;

            try
            {
                var com = new DynamicParameters();

                com.Add("@OrganizationID", objOrg.OrganizationID);
                com.Add("@OrganizationName", objOrg.OrganizationName);
                com.Add("@GSTIN", objOrg.GSTIN);
                com.Add("@ESCINO", objOrg.ESCINO);
                com.Add("@EPFNO", objOrg.EPFNO);
                com.Add("@OrganizationAddr1", objOrg.OrganizationAddr1);
                com.Add("@OrganizationAddr2", objOrg.OrganizationAddr2);
                com.Add("@State", objOrg.State);
                com.Add("@City", objOrg.City);
                com.Add("@ContactNO", objOrg.ContactNO);
                com.Add("@MobileNO", objOrg.MobileNO);
                com.Add("@EmailID", objOrg.EmailID);
                com.Add("@InvoicePrefix", objOrg.InvoicePrefix);
                com.Add("@IsActive", objOrg.IsActive);
                com.Add("@CreatedBy", objOrg.CreatedBy);
                com.Add("@UpdatedBy", objOrg.UpdatedBy);


                using (sqlConnection = SqlUtility.GetConnection())
                {
                    // var result = sqlConnection.Query<int>("usp_OrganizationInsertUpdate", com, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    // status = AppUtility.getStatus(Convert.ToInt32(result));

                    var queryValues = sqlConnection.QueryMultiple("ExpenseTrakcer", commandType: CommandType.StoredProcedure);


                    ExpenseTracker           objExpesnse = queryValues.Read <ExpenseTracker>().FirstOrDefault();
                    List <ExpenseTrackModel> objExpens   = queryValues.Read <ExpenseTrackModel>().ToList();

                    //ExpenseTracker obj = new ExpenseTracker();
                    //obj.Expense.a

                    // TypeBuilder.SetParent((typeof)ExpenseTracker);
                    //TypeBuilder.DefineProperty

                    //for(var i = 0; i < objExpens.Count; i++)
                    //   {
                    //    objExpens[i].ExpenseName,

                    //}
                }
            }
            catch (Exception ex)
            {
                ErrorLogModel.ErrorLog("Organization", ex.Message.ToString());

                // return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return(status);
        }
        public void BindErrorLogModel(string action, string description, string logType)
        {
            ErrorLogModel errorLogModel = new ErrorLogModel();

            errorLogModel.actioName   = action;
            errorLogModel.description = description;
            errorLogModel.logType     = logType;
            AddLog(errorLogModel);
        }
Exemple #20
0
        protected override ErrorLogModel ThrowRequestID(HttpContext context, Exception ex)
        {
            int           siteId = 0;
            int           userId = 0;
            ErrorLogModel model  = new ErrorLogModel(ex, siteId, userId, context);

            // 存入数据库 & 发送通知
            LogAgent.Instance().SaveLog(model);

            return(model);
        }
 public async Task DoErrorLog(System.Exception e, string requestObject)
 {
     try
     {
         var errorLog = new ErrorLogModel(e);
         await _dbConnector.Execute("");
     }
     catch (System.Exception)
     {
     }
 }
Exemple #22
0
        public void WriteFunctionLog(string destinationFolder, string x, string functionName, string message, string ErrorSource)
        {
            if (Directory.Exists(destinationFolder))
            {
                string pathfile = destinationFolder + "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
                if (File.Exists(pathfile))
                {
                    StreamWriter wr = File.AppendText(pathfile);
                    wr.WriteLine(DateTime.Now.ToString("dd-MMM-yyy hh:mm") + " - " + x + " == " + functionName + " == " + message);
                    wr.Close();
                }
                else
                {
                    File.Create(pathfile).Dispose();
                    StreamWriter wr = File.AppendText(pathfile);
                    wr.WriteLine(DateTime.Now.ToString("dd-MMM-yyy hh:mm") + " - " + x + " == " + functionName + " == " + message);
                    wr.Close();
                }
            }

            else
            {
                DirectoryInfo di       = Directory.CreateDirectory(destinationFolder);
                string        pathfile = destinationFolder + "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
                if (File.Exists(pathfile))
                {
                    StreamWriter wr = File.AppendText(pathfile);
                    wr.WriteLine(DateTime.Now.ToString("dd-MMM-yyy hh:mm") + " - " + x + " == " + functionName + " == " + message);
                    wr.Close();
                }
                else
                {
                    File.Create(pathfile).Dispose();
                    StreamWriter wr = File.AppendText(pathfile);
                    wr.WriteLine(DateTime.Now.ToString("dd-MMM-yyy hh:mm") + " - " + x + " == " + functionName + " == " + message);
                    wr.Close();
                }
            }


            var data = new ErrorLogModel();

            using (IDbConnection conn = Connection)
            {
                var param = new DynamicParameters();
                param.Add("@ErrorSource", ErrorSource);
                param.Add("@ErrorMessage", message);
                param.Add("@FunctionName", functionName);


                data = conn.Query <ErrorLogModel>("sp_Tbl_Error_LogInsert", param,
                                                  commandType: CommandType.StoredProcedure).FirstOrDefault();
            }
        }
Exemple #23
0
        public void InsertErrorLog(ErrorLogModel errorLogModel)
        {
            string indexName = LogIndexType.error_log.ToString();

            if (!_client.Indices.Exists(indexName).Exists)
            {
                _client.Indices.Create(indexName);
            }

            _client.Index <ErrorLogModel>(errorLogModel, x => x.Index(indexName));
        }
Exemple #24
0
 //Error copy to Database
 private void listenClient_OnNewErrorLog(ErrorLogModel erlog)
 {
     if (ErLogBll.Add(erlog) > 0)
     {
         //add erlog
         if (_currentPageId == (int)PageIdEnum.ErrorLog && m_lastfrm != null)
         {
             ((UCErrorLog)m_lastfrm).AddNewRow(erlog);
         }
     }
 }
Exemple #25
0
        public ActionResult Index(ExportModel Expmodel, ErrorLogModel model, FormCollection frm, int?page)
        {
            int currentPageIndex = page.HasValue ? page.Value : 1;
            int defaultPageSize  = 500;


            if (model.FromDate != null)
            {
                model.FromDate = model.FromDate.Value.Date;
            }

            if (model.ToDate != null)
            {
                model.ToDate = model.ToDate.Value.Date.AddHours(23).AddMinutes(59);
            }

            model.ErrorLogList = ser.ListErrorLog(model.FromDate, model.ToDate).ToPagedList(currentPageIndex, defaultPageSize);

            //export
            bktController.GetExportTypeClicked(Expmodel, frm);
            if (Expmodel != null && (Expmodel.ExportTypeExcel != null || Expmodel.ExportTypeWord != null || Expmodel.ExportTypeCSV != null || Expmodel.ExportTypePdf != null))
            {
                try
                {
                    if (Expmodel.ExportTypeExcel != null)
                    {
                        Expmodel.ExportTypeExcel = Expmodel.ExportTypeExcel;
                    }
                    else if (Expmodel.ExportTypeWord != null)
                    {
                        Expmodel.ExportTypeWord = Expmodel.ExportTypeWord;
                    }
                    else if (Expmodel.ExportTypePdf != null)
                    {
                        Expmodel.ExportTypePdf = Expmodel.ExportTypePdf;
                    }

                    var exportData = model.ErrorLogList.Select(m => new
                    {
                        Time_Stamp = m.time_stamp,
                        Source     = m.source,
                        Message    = m.message,
                        Logger     = m.logger
                    });
                    App_Class.AppCollection.Export(Expmodel, exportData, "Error Log");
                }
                catch
                {
                }
            }

            return(View(model));
        }
 private void AddToErrorQueue(CustomExceptions.TextExtractorException exception, string queueTableName)
 {
     try
     {
         var errorLogModel = new ErrorLogModel(SqlQueryHelper, EddsDbContext, AgentId, queueTableName);
         errorLogModel.InsertRecord(exception, ExtractorSetArtifactId, WorkspaceArtifactId);
     }
     catch (Exception queueException)
     {
         TextExtractorLog.RaiseError(queueException);
     }
 }
        public void AddError(ErrorLogModel model)
        {
            var parDate    = new SqlParameter("@ErrorDateTime", model.ErrorDateTime);
            var parURL     = new SqlParameter("@URL", model.URL ?? "");
            var parSource  = new SqlParameter("@Source", model.Source ?? "");
            var parType    = new SqlParameter("@Type", model.Type ?? "");
            var parMessage = new SqlParameter("@Message", model.Message ?? "");
            var parIP      = new SqlParameter("@IPAddress", model.IPAddress ?? "");
            var parUser    = new SqlParameter("@LogUser", model.User ?? "");

            db.Database.SqlQuery <int>("udspErrorLogAdd @ErrorDateTime, @URL, @Source, @Type, @Message, @IPAddress, @LogUser",
                                       parDate, parURL, parSource, parType, parMessage, parIP, parUser).FirstOrDefault();
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Gets the logs in this collection. </summary>
        ///
        /// <remarks>   Mustafa SAÇLI, 26.04.2019. </remarks>
        ///
        /// <param name="startTimestamp">   The start timestamp. </param>
        /// <param name="endTimestamp">     The end timestamp. </param>
        ///
        /// <returns>
        /// An enumerator that allows foreach to be used to process the logs in this collection.
        /// </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public virtual IEnumerable <ErrorLogModel> GetLogs(long?startTimestamp, long?endTimestamp)
        {
            var result = new ErrorLogModel[] { }
            .AsEnumerable();

            if (!startTimestamp.HasValue && !endTimestamp.HasValue)
            {
                return(result);
            }

            var start = startTimestamp.GetValueOrDefault(0);
            var end   = endTimestamp.GetValueOrDefault(0);

            using (var connection = GetConnection())
            {
                try
                {
                    using (var transaction = connection.OpenAndBeginTransaction())
                    {
                        try
                        {
                            var dictionary = new Dictionary <string, object>();

                            dictionary.Add("@start", start);
                            dictionary.Add("@end", end);

                            var list = connection.GetDynamicResultSet(
                                "SELECT * FROM ErrorLog WHERE (LogTimeUnixTimestamp >= @start OR @start = 0) AND (LogTimeUnixTimestamp <= @end OR @end = 0)",
                                transaction: transaction, inputParameters: dictionary);

                            result = list
                                     .ConvertToList <ErrorLogModel>()
                                     .AsEnumerable();

                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
                finally
                {
                    connection.CloseIfNot();
                }
            }

            return(result);
        }
Exemple #29
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Updates the given log. </summary>
        ///
        /// <remarks>   Msacli, 24.04.2019. </remarks>
        ///
        /// <param name="log">  The log to save. </param>
        ///
        /// <returns>   An int. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public int Update(ErrorLogModel log)
        {
            if (log == null)
            {
                return(CoreConstants.NullLogResponse);
            }

            if (string.IsNullOrWhiteSpace(log.Id))
            {
                return(CoreConstants.EmptyLogIdResponse);
            }

            var emptystring = Guid.Empty.ToString();

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            emptystring = emptystring.Replace('-', '\0');

            if (log.Id == emptystring)
            {
                return(CoreConstants.EmptyGuidLogIdResponse);
            }

            var logModel = new ErrorLogModelMongo
            {
                Id                   = log.Id,
                ClassName            = log.ClassName,
                CreatedOn            = log.CreatedOn,
                CreatedOnTimestamp   = log.CreatedOnUnixTimestamp,
                ExceptionData        = log.ExceptionData,
                LogTime              = log.LogTime,
                LogTimeUnixTimestamp = log.LogTimeUnixTimestamp,
                Message              = log.Message,
                MethodName           = log.MethodName,
                RequestAddres        = log.RequestAddres,
                ResponseAddress      = log.ResponseAddress,
                ResponseMachineName  = log.ResponseMachineName,
                StackTrace           = log.StackTrace,
                UserId               = log.UserId
            };

            var filter = Builders <ErrorLogModelMongo> .Filter.Eq(s => s.Id, logModel.Id);

            var replaceOneResult = this.Collection.ReplaceOne(filter, logModel);

            return((int)replaceOneResult.ModifiedCount);
        }
Exemple #30
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Saves the given log. </summary>
        ///
        /// <remarks>   Msacli, 24.04.2019. </remarks>
        ///
        /// <param name="log">  The log to save. </param>
        ///
        /// <returns>   A string. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public string Save(ErrorLogModel log)
        {
            if (log == null)
            {
#if DEBUG
                log = new ErrorLogModel();
#else
                return("null");
#endif
            }

            var logId     = log?.Id ?? string.Empty;
            var emptyGuid = Guid.Empty.ToString();

            if (string.IsNullOrWhiteSpace(logId) ||
                logId == emptyGuid ||
                logId == emptyGuid.Replace('-', '\0'))
            {
                log.Id = Guid.NewGuid().ToString();
            }

            if (!log.LogTime.HasValue)
            {
                log.LogTime = DateTime.Now;
                log.LogTimeUnixTimestamp = log.LogTime.Value.Ticks;
            }

            log.CreatedOn = DateTime.Now;
            log.CreatedOnUnixTimestamp = log.CreatedOn.Ticks;
            var logModel = new ErrorLogModelMongo
            {
                Id                   = log.Id,
                ClassName            = log.ClassName,
                CreatedOn            = log.CreatedOn,
                CreatedOnTimestamp   = log.CreatedOnUnixTimestamp,
                ExceptionData        = log.ExceptionData,
                LogTime              = log.LogTime,
                LogTimeUnixTimestamp = log.LogTimeUnixTimestamp,
                Message              = log.Message,
                MethodName           = log.MethodName,
                RequestAddres        = log.RequestAddres,
                ResponseAddress      = log.ResponseAddress,
                ResponseMachineName  = log.ResponseMachineName,
                StackTrace           = log.StackTrace,
                UserId               = log.UserId
            };

            this.Collection.InsertOne(logModel);
            return(log.Id);
        }