Exemplo n.º 1
0
        /// <summary>
        /// Modified to send OUTER Source & Type.
        /// </summary>
        /// <param name="error"></param>
        /// <param name="severity"></param>
        public static void LogCustom(this Elmah.Error error, LogSeverity severity = LogSeverity.Error)
        {
            // fix application name
            error.ApplicationName = CommonSettings.Application;

            var message = new Message(error.Message)
            {
                Application = error.ApplicationName,
                Cookies     = error.Cookies.AllKeys.Select(key => new Item {
                    Key = key, Value = error.Cookies[key]
                }).ToList(),
                DateTime = error.Time,
                Detail   = error.Detail,
                Form     = error.Form.AllKeys.Select(key => new Item {
                    Key = key, Value = error.Form[key]
                }).ToList(),
                Hostname    = error.HostName,
                QueryString = error.QueryString.AllKeys.Select(key => new Item {
                    Key = key, Value = error.QueryString[key]
                }).ToList(),
                ServerVariables = error.ServerVariables.AllKeys.Select(key => new Item {
                    Key = key, Value = error.ServerVariables[key]
                }).ToList(),
                Title = error.Message,
                //Source = error.Source,
                Source     = error.Exception.Source,
                StatusCode = error.StatusCode,
                //Type = error.Type,
                Type = error.Exception.GetType().ToString(),
                User = error.User,
                Data = error.Exception.ToDataList(),
            };

            LogMessage(message);
        }
        private ErrorLogModel GetErrorLogModel(Exception ex, HttpContext httpContext)
        {
            var error = new Elmah.Error(ex, httpContext);
            var log   = Elmah.ErrorLog.GetDefault(httpContext);

            error.ApplicationName = log.ApplicationName;
            var          id     = log.Log(error);
            var          entry  = new Elmah.ErrorLogEntry(log, id, error);
            StringWriter writer = new StringWriter(new StringBuilder());

            Elmah.ErrorJson.Encode(entry.Error, writer);
            var str = writer.ToString();

            return(new ErrorLogModel
            {
                AllXml = str,
                Application = entry.Error.ApplicationName,
                ErrorId = Guid.NewGuid(),
                Host = entry.Error.HostName,
                IsWeb = true,
                Message = entry.Error.Message,
                Source = entry.Error.Source,
                StatusCode = entry.Error.StatusCode,
                TimeUtc = entry.Error.Time,
                Type = entry.Error.Type,
                User = entry.Error.User,
                StoreId = SessionHelper.CurrentSession.Id
            });
        }
Exemplo n.º 3
0
 public jGrowlMessage(string title, string message, jGrowlMessageType type, Elmah.Error error = null, long messageDisplayTime = 20000)
 {
     this.title              = title;
     this.message            = message.Replace("\\", "/");
     this.type               = type;
     this.messageDisplayTime = messageDisplayTime;
     this.error              = error;
 }
Exemplo n.º 4
0
 public static void AddException(Exception e)
 {
     Notifications.Add(new Notification(NotificationType.Error, e.Message, e));
     Elmah.Error er = new Elmah.Error(e);
     using (var db = new Models.ApplicationDbContext())
     {
         //db.ElmahErr.Add(er);
         //db.SaveChangesAsync();
     }
 }
Exemplo n.º 5
0
        public void TestDeSerializeAndRun()
        {
            var config  = CustomErrorHandlerConfiguration.ReadFromString(CommonCode.GetStringFromEmbeddedResource("ElmahExtensions.SampleConfiguration01.xml"));
            var handler = new CustomErrorHandler()
            {
                Configuration = config
            };
            var error = new Elmah.Error(new NullReferenceException());

            handler.HandleError(error);
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Category(string id = "")
        {
            var cateListTemp = RedisManager.GetItem <List <Category> >("categories");

            if (cateListTemp == null)
            {
                cateListTemp = await _categoryRepository.GetAll();

                if (cateListTemp != null && cateListTemp.Any())
                {
                    RedisManager.SetItem("categories", cateListTemp, new TimeSpan(0, Settings.Config.CacheExpired, 0));
                }
            }
            if (id != "" && id != "other" && !cateListTemp.Select(t => t.Alias).Contains(id))
            {
                var error = new Elmah.Error(new Exception("分类alias:" + id + " 不存在!"), System.Web.HttpContext.Current)
                {
                    StatusCode = 404
                };
                Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error);
                return(View("Error404"));
            }
            var cateList = new List <CategoryBar>();

            cateList.Add(new CategoryBar
            {
                Alias    = string.Empty,
                CateName = "全部分类",
                Img      = "/Content/Img/all.svg"
                           //PostCount = await _postRepository.GetPostCountByCate(string.Empty)
            });
            foreach (var category in cateListTemp)
            {
                cateList.Add(new CategoryBar
                {
                    Alias    = category.Alias,
                    CateName = category.CateName,
                    Img      = category.Img,
                    Link     = category.Link
                               //PostCount = await _postRepository.GetPostCountByCate(category.UniqueId)
                });
            }
            cateList.Add(new CategoryBar
            {
                Alias    = "other",
                CateName = "未分类",
                Img      = "/Content/Img/unall.svg"
                           //PostCount = await _postRepository.GetPostCountByCate("other")
            });
            ViewBag.CateList  = cateList;
            ViewBag.CateAlias = id;
            return(View("Category"));
        }
Exemplo n.º 7
0
        public async Task <ViewResult> Item(string id)
        {
            if (id.Equals("about", StringComparison.CurrentCultureIgnoreCase))
            {
                var configSettings = new ConfigSettings();
                var config         = new AboutConfig(configSettings, "About", Server.MapPath("~/Settings"));
                config.Load();
                return(View("About", config));
            }
            if (id.Equals("guestbook", StringComparison.CurrentCultureIgnoreCase))
            {
                return(View("Guestbook"));
            }
            var cacheKey = "post_" + id;
            var post     = RedisManager.GetItem <Post>(cacheKey);

            if (post == null)
            {
                post = await _postRepository.GetPostByAlias(id);

                if (post != null)
                {
                    RedisManager.SetItem(cacheKey, post, new TimeSpan(0, Settings.Config.CacheExpired, 0));
                }
            }
            if (post != null)
            {
                var item = new PostItem
                {
                    UniqueId      = post.UniqueId,
                    Title         = post.Title,
                    CategoryAlias = post.CategoryAlias,
                    CateName      = await _categoryRepository.GetNameByAlias(post.CategoryAlias),
                    CreateTimeStr = post.CreateTime.ToString("yy-MM-dd HH:mm"),
                    ViewCount     = post.ViewCount,
                    LabelList     = JsonConvert.DeserializeObject <List <LabelShow> >(post.Labels).Select(t => t.Text).ToList(),
                    Summary       = post.Summary,
                    Content       = post.Content
                };
                return(View(item));
            }
            else
            {
                var error = new Elmah.Error(new Exception("文章id:" + id + " 不存在!"), System.Web.HttpContext.Current)
                {
                    StatusCode = 404
                };
                Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error);
                return(View("Error404"));
            }
        }
Exemplo n.º 8
0
        public void Log(Exception exception)
        {
            var frame  = new StackFrame(1);
            var method = frame.GetMethod();

            var error = new Elmah.Error(exception, _currentHttpContext)
            {
                Source = $"{(method.DeclaringType != null ? method.DeclaringType.FullName : "?")}.{method.Name}",
            };

            Elmah.ErrorLog.GetDefault(_currentHttpContext).Log(error);

            throw exception;
        }
Exemplo n.º 9
0
        private bool LogExceptionInternal(HttpContextBase context, Exception ex, string info = "", string memberName = "", string sourceFilePath = "", int sourceLineNumber = 0)
        {
            var err = new Elmah.Error(ex);

            err.Detail = $"memberName: {memberName}\nsourceFilePath: {sourceFilePath}\nsourceLineNumber: {sourceLineNumber}\ninfo: {info}";

            if (context.ApplicationInstance != null)
            {
                Elmah.ErrorLog.GetDefault(context.ApplicationInstance.Context).Log(err);

                return(true);
            }

            return(false);
        }
Exemplo n.º 10
0
 public async Task<ActionResult> Category(string id = "")
 {
     var cateListTemp = RedisManager.GetItem<List<Category>>("categories");
     if (cateListTemp == null)
     {
         cateListTemp = await _categoryRepository.GetAll();
         if (cateListTemp != null && cateListTemp.Any())
         {
             RedisManager.SetItem("categories", cateListTemp, new TimeSpan(0, Settings.Config.CacheExpired, 0));
         }
     }
     if (id != "" && id != "other" && !cateListTemp.Select(t => t.Alias).Contains(id))
     {
         var error = new Elmah.Error(new Exception("分类alias:" + id + " 不存在!"), System.Web.HttpContext.Current) { StatusCode = 404 };
         Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error);
         return View("Error404");
     }
     var cateList = new List<CategoryBar>();
     cateList.Add(new CategoryBar
     {
         Alias = string.Empty,
         CateName = "全部分类",
         Img = "/Content/Img/全部分类.svg"
         //PostCount = await _postRepository.GetPostCountByCate(string.Empty)
     });
     foreach (var category in cateListTemp)
     {
         cateList.Add(new CategoryBar
         {
             Alias = category.Alias,
             CateName = category.CateName,
             Img = category.Img,
             Link = category.Link
             //PostCount = await _postRepository.GetPostCountByCate(category.UniqueId)
         });
     }
     cateList.Add(new CategoryBar
     {
         Alias = "other",
         CateName = "未分类",
         Img = "/Content/Img/未分类.svg"
         //PostCount = await _postRepository.GetPostCountByCate("other")
     });
     ViewBag.CateList = cateList;
     ViewBag.CateAlias = id;
     return View("Category");
 }
Exemplo n.º 11
0
        public ActionResult NotFound()
        {
            try
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;

                // log the 404 so we can keep an eye on them
                var Exception = new HttpException((int)HttpStatusCode.NotFound, "Destination not found: " + Request.RawUrl);
                var Error     = new Elmah.Error(Exception);
                var Logger    = Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current);

                Logger.Log(Error);
            }
            catch { }

            return(View());
        }
Exemplo n.º 12
0
        // in .net 4.0, when you return a 401 (unauthorized), it automatically redirects to the login page. The login page has logic to redirect BACK here if the user is logged in, with
        // status code 200 (ok) to allow this page to be displayed properly. So this gets hit twice, once it logs the error and returns 401, once it returns 200 and displays the page
        public ActionResult NotAllowed(HttpStatusCode statusCode = HttpStatusCode.Unauthorized)
        {
            try
            {
                Response.StatusCode = (int)statusCode;
                if (statusCode == HttpStatusCode.Unauthorized)
                {
                    // log the 401 so we can keep an eye on them
                    var Exception = new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized action at: " + Request.RawUrl);
                    var Error     = new Elmah.Error(Exception);
                    var Logger    = Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current);

                    Logger.Log(Error);
                }
            }
            catch { }

            return(View());
        }
        /// <summary>
        /// Returns a page of errors from the databse in descending order 
        /// of logged time.
        /// </summary>
        /// 

        public override int GetErrors(int pageIndex, int pageSize, System.Collections.IList errorEntryList)
        {
            if (pageIndex < 0)
                throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);

            if (pageSize < 0)
                throw new ArgumentOutOfRangeException("pageSize", pageSize, null);

            const string sql = @"
                SELECT
                    [ErrorId],
                    [Application],
                    [Host],
                    [Type],
                    [Source],
                    [Message],
                    [User],
                    [StatusCode],
                    [TimeUtc]
                FROM
                    [ELMAH_Error]
                WHERE
                    [Application] = @Application
                ORDER BY
                    [TimeUtc] DESC, 
                    [Sequence] DESC
                OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY;
                ";

                const string getCount = @"
                SELECT COUNT(*) FROM [ELMAH_Error]";

            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            {
                connection.Open();

                using (SqlCeCommand command = new SqlCeCommand(sql, connection))
                {
                    SqlCeParameterCollection parameters = command.Parameters;

                    parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
                    parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName;


                    using (SqlCeDataReader reader = command.ExecuteReader())
                    {
                        if (errorEntryList != null)
                        {
                            while (reader.Read())
                            {
                                string id = reader["ErrorId"].ToString();

                                Elmah.Error error = new Elmah.Error();
                                error.ApplicationName = reader["Application"].ToString();
                                error.HostName = reader["Host"].ToString();
                                error.Type = reader["Type"].ToString();
                                error.Source = reader["Source"].ToString();
                                error.Message = reader["Message"].ToString();
                                error.User = reader["User"].ToString();
                                error.StatusCode = Convert.ToInt32(reader["StatusCode"]);
                                error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime();
                                errorEntryList.Add(new ErrorLogEntry(this, id, error));
                            }
                        }
                    }
                }

                using (SqlCeCommand command = new SqlCeCommand(getCount, connection))
                {
                    return (int)command.ExecuteScalar();
                }
            }
        }
Exemplo n.º 14
0
 public void DisplayErrorMessage(string message, Elmah.Error error = null)
 {
     DisplayjGrowlMessage(new jGrowlMessage("Error", message, jGrowlMessage.jGrowlMessageType.Error, error));
 }
Exemplo n.º 15
0
 public Return(object rawData, Elmah.Error error)
 {
     this.rawData = rawData;
     this.error   = error;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Returns a page of errors from the databse in descending order
        /// of logged time.
        /// </summary>
        ///

        public override int GetErrors(int pageIndex, int pageSize, System.Collections.IList errorEntryList)
        {
            if (pageIndex < 0)
            {
                throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
            }

            if (pageSize < 0)
            {
                throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
            }

            const string sql = @"
                SELECT
                    [ErrorId],
                    [Application],
                    [Host],
                    [Type],
                    [Source],
                    [Message],
                    [User],
                    [StatusCode],
                    [TimeUtc]
                FROM
                    [ELMAH_Error]
                ORDER BY
                    [TimeUtc] DESC, 
                    [Sequence] DESC
                OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY;
                ";

            const string getCount = @"
                SELECT COUNT(*) FROM [ELMAH_Error]";

            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            {
                connection.Open();

                using (SqlCeCommand command = new SqlCeCommand(sql, connection))
                {
                    SqlCeParameterCollection parameters = command.Parameters;

                    parameters.Add("@PageIndex", SqlDbType.Int).Value            = pageIndex;
                    parameters.Add("@PageSize", SqlDbType.Int).Value             = pageSize;
                    parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName;


                    using (SqlCeDataReader reader = command.ExecuteReader())
                    {
                        if (errorEntryList != null)
                        {
                            while (reader.Read())
                            {
                                string id = reader["ErrorId"].ToString();

                                Elmah.Error error = new Elmah.Error();
                                error.ApplicationName = reader["Application"].ToString();
                                error.HostName        = reader["Host"].ToString();
                                error.Type            = reader["Type"].ToString();
                                error.Source          = reader["Source"].ToString();
                                error.Message         = reader["Message"].ToString();
                                error.User            = reader["User"].ToString();
                                error.StatusCode      = Convert.ToInt32(reader["StatusCode"]);
                                error.Time            = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime();
                                errorEntryList.Add(new ErrorLogEntry(this, id, error));
                            }
                        }
                    }
                }

                using (SqlCeCommand command = new SqlCeCommand(getCount, connection))
                {
                    return((int)command.ExecuteScalar());
                }
            }
        }
Exemplo n.º 17
0
 public async Task<ViewResult> Item(string id)
 {
     if (id.Equals("about", StringComparison.CurrentCultureIgnoreCase))
     {
         var configSettings = new ConfigSettings();
         var config = new AboutConfig(configSettings, "About", Server.MapPath("~/Settings"));
         config.Load();
         return View("About", config);
     }
     if (id.Equals("guestbook", StringComparison.CurrentCultureIgnoreCase))
     {
         return View("Guestbook");
     }
     var cacheKey = "post_" + id;
     var post = RedisManager.GetItem<Post>(cacheKey);
     if (post == null)
     {
         post = await _postRepository.GetPostByAlias(id);
         if (post != null)
         {
             RedisManager.SetItem(cacheKey, post, new TimeSpan(0, Settings.Config.CacheExpired, 0));
         }
     }
     if (post != null)
     {
         var item = new PostItem
         {
             UniqueId = post.UniqueId,
             Title = post.Title,
             CategoryAlias = post.CategoryAlias,
             CateName = await _categoryRepository.GetNameByAlias(post.CategoryAlias),
             CreateTimeStr = post.CreateTime.ToString("yy-MM-dd HH:mm"),
             ViewCount = post.ViewCount,
             LabelList = JsonConvert.DeserializeObject<List<LabelShow>>(post.Labels).Select(t => t.Text).ToList(),
             Summary = post.Summary,
             Content = post.Content
         };
         return View(item);
     }
     else
     {
         var error = new Elmah.Error(new Exception("文章id:" + id + " 不存在!"), System.Web.HttpContext.Current) { StatusCode = 404 };
         Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error);
         return View("Error404");
     }
 }
        public async Task <string> Upload(HttpPostedFileBase claimfile)
        {
            int       Added   = 0;
            int       Existed = 0;
            IWorkbook book;

            try
            {
                if (claimfile == null || claimfile.ContentLength == 0)
                {
                    return("Файл нулевого размера.");
                }
                if (Path.GetExtension(claimfile.FileName) != ".xls" && Path.GetExtension(claimfile.FileName) != ".xlsx")
                {
                    return("Неверный тип файла. Поддерживаются только файлы с расширением XLS или XLSX.");
                }
                book = WorkbookFactory.Create(claimfile.InputStream);
                var sheet = book.GetSheetAt(0);
                for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                {
                    var row = sheet.GetRow(rowNum);
                    try
                    {
                        Employee emp = new Employee();
                        //{

                        //};
                        emp.SurName = row.GetCell(0) != null?row.GetCell(0).StringCellValue : String.Empty;

                        emp.FirstName = row.GetCell(1) != null?row.GetCell(1).StringCellValue : String.Empty;

                        emp.MiddleName = row.GetCell(2) != null?row.GetCell(2).StringCellValue : String.Empty;

                        emp.Position = row.GetCell(3) != null?row.GetCell(3).StringCellValue : String.Empty;

                        emp.Gender = row.GetCell(4) != null?row.GetCell(4).StringCellValue : String.Empty;

                        emp.Serial = row.GetCell(5) != null?row.GetCell(5).StringCellValue : String.Empty;

                        emp.Code = row.GetCell(6) != null?row.GetCell(6).StringCellValue : String.Empty;

                        emp.IssueDate = row.GetCell(7) != null ? (DateTime)row.GetCell(7).DateCellValue : new DateTime(1900, 1, 1);
                        emp.WhoIssued = row.GetCell(8) != null?row.GetCell(8).StringCellValue : String.Empty;

                        emp.Registration = row.GetCell(9) != null?row.GetCell(9).StringCellValue : String.Empty;

                        emp.CitizenShip = row.GetCell(10) != null?row.GetCell(10).StringCellValue : String.Empty;

                        emp.BirthPlace = row.GetCell(11) != null?row.GetCell(11).StringCellValue : String.Empty;

                        emp.HireDate         = row.GetCell(12) != null ? (DateTime)row.GetCell(12).DateCellValue : new DateTime(1900, 1, 1);
                        emp.BirthDate        = row.GetCell(13) != null ? (DateTime)row.GetCell(13).DateCellValue : new DateTime(1900, 1, 1);
                        emp.TerritoryService = row.GetCell(14) != null?row.GetCell(14).StringCellValue : String.Empty;

                        try
                        {
                            Employee findEmp = db.Employees.Where(s => s.Serial == emp.Serial & s.Code == emp.Code).FirstOrDefault();
                            if (findEmp == null)
                            {
                                emp.AddedDate = DateTime.Now;
                                db.Employees.Add(emp);
                                Added++;
                            }
                            else
                            {
                                Existed++;
                            }
                        }
                        catch (Exception ex)
                        {
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Elmah.Error error = new Elmah.Error(ex);
                return("");
            }
            return("Успешно добавлено " + Added.ToString() + " сотрудников" + " пропущено " + Existed.ToString() + " существующих");
        }