示例#1
0
        public void Logger_LogServiceResult_DoesNotSaveOKIfLoggingLevel2()
        {
            // Arrange
            var mockEfDbContext = new Mock<EFDbContext>();
            mockEfDbContext.Setup(x => x.DBResults.Add(It.IsAny<DBResult>())).Returns(new DBResult());
            mockEfDbContext.Setup(x => x.SaveChanges()).Verifiable();

            var result = new DBResult
            {
                StatusCode = HttpStatusCode.OK,
                ServiceName = "dummyService",
                ActionName = "dummyAction",
                ControllerName = "dummyController",
                UserName = "******",
                StatusDescription = "test descr"
            };
            var logger = new DBLogger(2, 0, mockEfDbContext.Object);

            //Act
            logger.LogResult(result);

            // Assert
            mockEfDbContext.Verify(m => m.DBResults.Add(It.IsAny<DBResult>()), Times.Exactly(1));
            mockEfDbContext.Verify(x => x.SaveChanges(), Times.Exactly(1));
        }
示例#2
0
        //Constructors---------------------------------------------------------------------------------------------------------//

        //Methods--------------------------------------------------------------------------------------------------------------//

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                string errorsFromModelState = "";
                foreach (ModelState state in filterContext.Controller.ViewData.ModelState.Values)
                {
                    foreach (ModelError error in state.Errors)
                    {
                        errorsFromModelState = String.IsNullOrEmpty(errorsFromModelState) ? errorsFromModelState : errorsFromModelState + "\n";
                        errorsFromModelState += error.ErrorMessage;
                    }
                }

                var filterResult = new DBResult
                {
                    ActionName = filterContext.RouteData.Values["action"].ToString(),
                    ControllerName = filterContext.RouteData.Values["controller"].ToString(),
                    ServiceName = "DBSrvValidateAttribute",
                    UserName = filterContext.HttpContext.User.Identity.Name,
                    UserHostAddress = filterContext.HttpContext.Request.UserHostAddress,
                    StatusCode = HttpStatusCode.BadRequest,
                    StatusDescription = "Error(s) in submitted values:\n" + errorsFromModelState,
                };
                Logger.LogResult(filterResult);
                filterContext.HttpContext.Response.StatusCode = (int)filterResult.StatusCode;
                filterContext.Result = new JsonResult()
                {
                    Data = new { Success = "False", responseText = filterResult.StatusDescription },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
        }
示例#3
0
        //Constructors---------------------------------------------------------------------------------------------------------//

        //Methods--------------------------------------------------------------------------------------------------------------//

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterResult = new DBResult
            {
                DtStart = DateTime.Now,
                ActionName = filterContext.RouteData.Values["action"].ToString(),
                ControllerName = filterContext.RouteData.Values["controller"].ToString(),
                UserName = filterContext.HttpContext.User.Identity.Name,
                UserHostAddress = filterContext.HttpContext.Request.UserHostAddress
            };
            timer = Stopwatch.StartNew();
        }
示例#4
0
        //Methods--------------------------------------------------------------------------------------------------------------//

        public void OnAuthentication(AuthenticationContext context)
        {
            var filterResult = new DBResult
            {
                ActionName = context.RouteData.Values["action"].ToString(),
                ControllerName = context.RouteData.Values["controller"].ToString(),
                ServiceName = "DBSrvAuthAttribute",
                UserName = context.Principal.Identity.Name,
                UserHostAddress = context.HttpContext.Request.UserHostAddress
            };

            var dbRolesArray = dbRoles.Split(','); var isInRole = false;
            foreach (var dbRole in dbRolesArray)
            {
                if (context.Principal.IsInRole(dbRole)) 
                { 
                    isInRole = true; 
                    break;
                }
            }


            if (!context.HttpContext.Request.IsAuthenticated || (dbRoles != "" && !isInRole))
            {
                filterResult.StatusCode = HttpStatusCode.Conflict;
                filterResult.StatusDescription = 
                    "You are not logged in or request not authorized.\n" + 
                    "Try to log in again or contact SDDB administrator to obtain appropriate privileges.";
                Logger.LogResult(filterResult);
                context.HttpContext.Response.StatusCode = (int)filterResult.StatusCode;
                context.Result = new JsonResult()
                {
                    Data = new { Success = "False", responseText = filterResult.StatusDescription },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }

            if (ajaxRequired && !context.HttpContext.Request.IsAjaxRequest())
            {
                filterResult.StatusCode = HttpStatusCode.Gone;
                filterResult.StatusDescription = "Error 0101: AJAX request allowed only.";
                Logger.LogResult(filterResult);
                context.HttpContext.Response.StatusCode = (int)filterResult.StatusCode;
                context.Result = new JsonResult()
                {
                    Data = new { Success = "False", responseText = filterResult.StatusDescription },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
        }
示例#5
0
        //Constructors---------------------------------------------------------------------------------------------------------//

        //Methods--------------------------------------------------------------------------------------------------------------//

        public void OnException(ExceptionContext exceptionContext)
        {
            if (exceptionContext.ExceptionHandled) { return; }
                        
            var filterResult = new DBResult
            {
                ActionName = exceptionContext.RouteData.Values["action"].ToString(),
                ControllerName = exceptionContext.RouteData.Values["controller"].ToString(),
                ServiceName = exceptionContext.Controller.ViewBag.ServiceName,
                UserName = exceptionContext.HttpContext.User.Identity.Name,
                UserHostAddress = exceptionContext.HttpContext.Request.UserHostAddress,
                StatusCode = getStatusCodeHelper(exceptionContext),
                StatusDescription = "Exception thrown: " + exceptionContext.Exception.ToString()
            };
            Logger.LogResult(filterResult);

            setResponseResultHelper(exceptionContext);
                        
            exceptionContext.ExceptionHandled = true;
        }
示例#6
0
文件: _DBLogger.cs 项目: naishan/SDDB
        //Methods--------------------------------------------------------------------------------------------------------------//

        public void LogResult(DBResult result)
        {
            result.Id = Guid.NewGuid().ToString();
            result.UserName = (String.IsNullOrEmpty(result.UserName)) ? "_unknown_" : result.UserName;
            result.UserHostAddress = (String.IsNullOrEmpty(result.UserHostAddress)) ? "_unknown_" : result.UserHostAddress;
            result.ServiceName = (String.IsNullOrEmpty(result.ServiceName)) ? "_unknown_" : result.ServiceName;

            result.DtStart = (result.DtStart <= DateTime.Parse("1900-01-01")) ? DateTime.Now : result.DtStart;
            result.DtEnd = (result.DtEnd <= DateTime.Parse("1900-01-01")) ? result.DtStart : result.DtEnd;
            var procTime = result.DtEnd - result.DtStart;

            if (procTooLongmSec > 0 && procTime.TotalMilliseconds > procTooLongmSec)
            {
                result.StatusCode = HttpStatusCode.InternalServerError;
                result.StatusDescription += String.Format(" Process ran {0:F3} seconds.", procTime.TotalSeconds);
            }

            var saveToDB = false;
            switch (dbLoggingLevel)
            {
                case 0:
                    return;
                case 1:
                    if (result.StatusCode != HttpStatusCode.OK) saveToDB = true;
                    break;
                default:
                    saveToDB = true;
                    break;
            }
            if (saveToDB)
            {
                using (var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    dbContext.DBResults.Add(result);
                    dbContext.SaveChanges();
                    trans.Complete();
                }
            }
        }
示例#7
0
        public void Logger_LogServiceResult_DoesNotSaveIfResultOk()
        {
            // Arrange
            var mockEfDbContext = new Mock<EFDbContext>();

            var result = new DBResult
            {
                StatusCode = HttpStatusCode.OK,
                ServiceName = "dummyService",
                ActionName = "dummyAction",
                ControllerName = "dummyController",
                UserName = "******",
                StatusDescription = "test descr"
            };
            var logger = new DBLogger(1, 0, mockEfDbContext.Object);

            //Act
            logger.LogResult(result);

            // Assert
            mockEfDbContext.Verify(m => m.DBResults.Add(It.IsAny<DBResult>()), Times.Never());
        }
示例#8
0
        public void Logger_LogServiceResult_SavesIfProcTooLong()
        {
            // Arrange
            var mockEfDbContext = new Mock<EFDbContext>();
            mockEfDbContext.Setup(x => x.DBResults.Add(It.IsAny<DBResult>())).Returns(new DBResult());
            mockEfDbContext.Setup(x => x.SaveChanges()).Verifiable();

            var result = new DBResult
            {
                StatusCode = HttpStatusCode.BadRequest,
                ServiceName = "dummyService",
                ActionName = "dummyAction",
                ControllerName = "dummyController",
                StatusDescription = "test descr",
                DtStart = DateTime.Parse("2015-05-05 00:00:00"),
                DtEnd = DateTime.Parse("2015-05-05 00:00:01")
            };

            var logger = new DBLogger(1, 500, mockEfDbContext.Object);

            //Act
            logger.LogResult(result);

            // Assert
            Assert.IsTrue(result.StatusCode == HttpStatusCode.InternalServerError);
            Assert.IsTrue(result.StatusDescription.Contains("Process ran 1.000 seconds."));
        }
示例#9
0
        public void Logger_LogServiceResult_AddsDTStartDTEndUserNameHostAddresAndGuid()
        {
            // Arrange
            var mockEfDbContext = new Mock<EFDbContext>();
            mockEfDbContext.Setup(x => x.DBResults.Add(It.IsAny<DBResult>())).Returns(new DBResult());
            mockEfDbContext.Setup(x => x.SaveChanges()).Verifiable();

            var result = new DBResult
            {
                StatusCode = HttpStatusCode.BadRequest,
                ServiceName = "dummyService",
                ActionName = "dummyAction",
                ControllerName = "dummyController",
                StatusDescription = "test descr"
            };
            var logger = new DBLogger(1, 0, mockEfDbContext.Object);

            //Act
            logger.LogResult(result);

            // Assert
            Assert.IsTrue(result.UserName.Contains("_unknown_"));
            Assert.IsTrue(result.UserHostAddress.Contains("_unknown_"));
            var regex = new Regex(@"\w*-\w*-\w*-\w*-\w*"); Assert.IsTrue(regex.IsMatch(result.Id));
            Assert.IsTrue(result.DtStart > DateTime.Now.AddSeconds(-1));
            Assert.IsTrue(result.DtEnd > DateTime.Now.AddSeconds(-1));
        }