Beispiel #1
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            timer.Stop();

            var browser = filterContext.HttpContext.Request.Browser;

            using (var monitorDb = new MonitorDbContext())
            {
                var diagnostic = new Diagnostic
                {
                    DiagnosticID     = Guid.NewGuid(),
                    ApplicationName  = "QA Forum",
                    WebServer        = HttpContext.Current.Request.ServerVariables["SERVER_NAME"],
                    Browser          = browser.Browser + "-" + browser.Version,
                    TargetController = filterContext.RouteData.Values["controller"].ToString(),
                    TargetAction     = filterContext.RouteData.Values["action"].ToString(),
                    DiagnosticTime   = DateTime.Now,
                    ExecutionTime    = timer.ElapsedMilliseconds
                };

                monitorDb.Diagnostics.Add(diagnostic);
                monitorDb.SaveChanges();
            }

            base.OnActionExecuted(filterContext);
        }
Beispiel #2
0
        // 返回类型可以更改为 IEnumerable,但是为了支持
        // 分页和排序,必须添加以下参数:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable <IMS.Models.DepartmentMonitor> lvDepartmentMonitor_GetData([Control] Int64?dlType, [Control] Int64?dlName, [Control] Int64?dlItem, [Control] string txtDate)
        {
            IQueryable <IMS.Models.DepartmentMonitor> query = null;
            MonitorDbContext context = new MonitorDbContext();

            query = context.DepartmentMonitors.Include(i => i.Department).Include(i => i.DepartmentType).Include(i => i.MonitorItem)
                    .OrderBy(o => o.Department.DepartmentName);
            if (txtDate != null)
            {
                var time = DateTime.Parse(txtDate);
                if (time != null)
                {
                    query = query.Where(q => q.Time.Year == time.Year && q.Time.Month == time.Month);
                }
            }

            if (dlType != null && dlType != -1)
            {
                query = query.Where(q => q.DepartmentTypeID == dlType);
            }
            if (dlName != null && dlName != -1)
            {
                query = query.Where(q => q.DepartmentID == dlName);
            }

            if (dlItem != null && dlItem != -1)
            {
                query = query.Where(q => q.MonitorItemID == dlItem);
            }

            return(query);
        }
Beispiel #3
0
        /// <summary>
        /// Checks the login.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="tenant"></param>
        /// <returns></returns>
        public async Task <LoginResponse> CheckLogin(string userName, string password, string tenant)
        {
            // check user's information
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(tenant))
            {
                return(await Task.FromResult(new LoginResponse { LoginResult = LoginResult.NotAllowd }));
            }

            // get the tenant info
            var tenantToVerify = await this.tenantRepository.GetSingleAsync(s => s.TanentName == tenant);

            if (tenantToVerify == null)
            {
                return(await Task.FromResult(new LoginResponse { LoginResult = LoginResult.NotAllowd }));
            }

            using (var context = new MonitorDbContext(MonitorDbContextHelper.ChangeDatabaseNameInConnectionString(this.connectionOptions.Value.DefaultConnection, tenantToVerify.DatabaseName).Options))
            {
                var userHandler = new UserManager <AppIdentityUser>(new AppUserStore(context), Options.Create <IdentityOptions>(this.signInManager.Options),
                                                                    this.userManager.PasswordHasher, this.userManager.UserValidators, this.userManager.PasswordValidators,
                                                                    this.userManager.KeyNormalizer, this.userManager.ErrorDescriber, null, this.userManager.Logger as ILogger <UserManager <AppIdentityUser> >);

                //get the user to verify
                var userToVerify = await userHandler.FindByNameAsync(userName);

                if (userToVerify == null || !userToVerify.IsActive)
                {
                    return(await Task.FromResult(new LoginResponse { LoginResult = LoginResult.NotAllowd }));
                }

                var singinHandler = new SignInManager <AppIdentityUser>(userHandler, this.httpContentAccessor, this.signInManager.ClaimsFactory,
                                                                        Options.Create <IdentityOptions>(this.signInManager.Options), this.signInManager.Logger as ILogger <SignInManager <AppIdentityUser> >, null);

                // check the credentials
                var pwToVerity = await singinHandler.CheckPasswordSignInAsync(userToVerify, password, false);

                if (!pwToVerity.Succeeded)
                {
                    return(await Task.FromResult(new LoginResponse { LoginResult = LoginResult.NotAllowd }));
                }

                // get roles claims
                var roles = from ur in context.UserRoles
                            where ur.UserId == userToVerify.Id
                            join r in context.Roles on ur.RoleId equals r.Id
                            select r;

                IEnumerable <Claim> claims = from role in roles
                                             join rc in context.RoleClaims
                                             on role.Id equals rc.RoleId
                                             select new StationeryClaim(rc.ClaimType, rc.ClaimValue, role.IsAdmin);
                bool isAdmin = roles.Any(s => s.IsAdmin == true);
                return(new LoginResponse {
                    ImageSource = userToVerify.ImageSource, UserName = userName, IsAdmin = isAdmin, DBName = tenantToVerify.DatabaseName, Claims = claims.ToList(), LoginResult = LoginResult.Allowed
                });
            }
        }
Beispiel #4
0
        public UnitOfWork(MonitorDbContext dbContext)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            this.dbContext = dbContext;

            // Create generic repository.
            this.Repository = new Repository(this.dbContext);
        }
Beispiel #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
                              MonitorDbContext dbContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));

            app.UseStaticFiles();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
                DbInitializer.Initialize(dbContext);

                app.UseSwagger();
                app.UseSwaggerUI(option =>
                {
                    option.SwaggerEndpoint("/swagger/v1/swagger.json", "Monitor API V1");
                });

                app.MapWhen(c => !c.Request.Path.Value.StartsWith("/swagger"), builder =>
                {
                    builder.UseMvc(routes =>
                    {
                        routes.MapSpaFallbackRoute(
                            name: "spa-fasllback",
                            defaults: new { Controller = "Home", Action = "Index" });
                    });
                });
            }
            else
            {
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");

                    routes.MapSpaFallbackRoute(
                        name: "spa-fallback",
                        defaults: new { Controller = "Home", Action = "Index" });
                });
                app.UseExceptionHandler("/Home/Error");
            }
        }
Beispiel #6
0
        // id 参数名应该与控件上设置的 DataKeyNames 值匹配
        public void lvDepartmentMonitor_UpdateItem(Int64 id)
        {
            TextBox txtEditValue = new TextBox();

            txtEditValue = (TextBox)lvDepartmentMonitor.EditItem.FindControl("txtValue");
            var value = txtEditValue?.Text;

            if (String.IsNullOrEmpty(value))
            {
                return;
            }
            using (MonitorDbContext context = new MonitorDbContext())
            {
                IMS.Models.DepartmentMonitor item = null;
                // 在此加载该项,例如 item = MyDataLayer.Find(id);
                item = context.DepartmentMonitors.Find(id);
                if (item == null)
                {
                    // 未找到该项
                    ModelState.AddModelError("", String.Format("未找到 id 为 {0} 的项", id));
                    return;
                }
                TryUpdateModel(item);
                if (ModelState.IsValid)
                {
                    // 在此保存更改,例如 MyDataLayer.SaveChanges();
                    item.Value = value;
                    //database win
                    bool saveFailed;
                    do
                    {
                        saveFailed = false;
                        try
                        {
                            context.SaveChanges();
                        }
                        catch (DbUpdateConcurrencyException ex)
                        {
                            saveFailed = true;
                            // Update the values of the entity that failed to save from the store
                            ex.Entries.Single().Reload();
                        }
                    } while (saveFailed);
                }
            }
        }
        public static void UpdateServersList(this MonitorDbContext dbContext,
                                             IEnumerable <SecurityServerData> serversList)
        {
            using (var transaction = dbContext.Database.BeginTransaction())
            {
                var localCache = dbContext.Servers.ToList();
                var forRemove  = localCache.Where(server => !serversList.Any(server.SameAs)).ToList();
                dbContext.Servers.RemoveRange(forRemove);

                var forAdd = serversList.Where(incomingServer => !localCache.Any(incomingServer.SameAs))
                             .ToList().ConvertAll(it => it.AsEntity());

                dbContext.Servers.AddRange(forAdd);
                dbContext.SaveChanges();
                transaction.Commit();
            }
        }
Beispiel #8
0
        /// <summary>
        /// Registers the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public async Task <RegisterModelResponse> CreateNewUser(RegisterModel model)
        {
            var user = new AppIdentityUser
            {
                UserName    = model.UserName,
                Email       = model.Email,
                CreatedDate = DateTime.Now,
                LastModify  = DateTime.Now,
                IsActive    = model.IsActive,
                ImageSource = model.ImageSource,
                PhoneNumber = model.PhoneNo
            };

            using (var context = new MonitorDbContext(MonitorDbContextHelper.ChangeDatabaseNameInConnectionString(this.connectionOptions.Value.DefaultConnection, model.DatabaseName).Options))
            {
                var userHandler = new UserManager <AppIdentityUser>(new AppUserStore(context), Options.Create <IdentityOptions>(this.signInManager.Options),
                                                                    this.userManager.PasswordHasher, this.userManager.UserValidators, this.userManager.PasswordValidators,
                                                                    this.userManager.KeyNormalizer, this.userManager.ErrorDescriber, null, this.userManager.Logger as ILogger <UserManager <AppIdentityUser> >);

                var result = await userHandler.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    result = await userHandler.AddToRolesAsync(user, model.Roles);

                    return(await Task.FromResult(new RegisterModelResponse()
                    {
                        AddedResult = LoginResult.Allowed
                    }));
                }

                return(await Task.FromResult(new RegisterModelResponse()
                {
                    AddedResult = LoginResult.NotAllowd, Error = result.Errors.ElementAt(0).Description
                }));
            }
        }
Beispiel #9
0
        // id 参数名应该与控件上设置的 DataKeyNames 值匹配
        public void lvDepartmentMonitor_DeleteItem(Int64 id)
        {
            using (MonitorDbContext context = new MonitorDbContext())
            {
                IMS.Models.DepartmentMonitor item = null;
                item = context.DepartmentMonitors.Find(id);
                if (item == null)
                {
                    // 未找到该项
                    ModelState.AddModelError("", String.Format("未找到 id 为 {0} 的项", id));
                    return;
                }

                TryUpdateModel(item);
                if (ModelState.IsValid)
                {
                    // 在此保存更改,例如 MyDataLayer.SaveChanges();
                    context.DepartmentMonitors.Remove(item);
                    //database win
                    bool saveFailed;
                    do
                    {
                        saveFailed = false;
                        try
                        {
                            context.SaveChanges();
                        }
                        catch (DbUpdateConcurrencyException ex)
                        {
                            saveFailed = true;
                            // Update the values of the entity that failed to save from the store
                            ex.Entries.Single().Reload();
                        }
                    } while (saveFailed);
                }
            }
        }
 public MonitorContextInitialiser(MonitorDbContext ctx)
 {
     _ctx = ctx;
 }
Beispiel #11
0
 public PanelsController(MonitorDbContext context)
 {
     this._context = context;
 }
Beispiel #12
0
 public GroupsController(MonitorDbContext context)
 {
     this._context = context;
 }
 public static void Initialize(MonitorDbContext dbContext)
 {
     dbContext.Database.EnsureCreated();
 }