Пример #1
0
        public void GetUser_RunServerAddUserList_GetUser()
        {
            DoIntegrationTest(async(client, dbContextOptions) =>
            {
                //Arrange
                MiniAutoFixture miniAutoFixture = new MiniAutoFixture();
                miniAutoFixture.Initialize();
                List <User> userList  = DbSetTools.AddExampleUsersToDatabase(dbContextOptions, miniAutoFixture);
                User userExample      = userList[0];
                UserModify userModify = DomainTools.CreateUserModify(miniAutoFixture);
                var request           = new HttpRequestMessage(new HttpMethod("GET"), string.Format("/api/user/{0}", userExample.Id));

                //Action
                var response = await client.SendAsync(request);

                //Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                var content       = await response.Content.ReadAsStringAsync();
                UserView userView = JsonConvert.DeserializeObject <UserView>(content);

                Assert.Equal(userExample.Id, userView.Id);
                Assert.Equal(userExample.Name, userView.Name);
                Assert.Equal(userExample.Surname, userView.Surname);
                Assert.Equal(userExample.Deleted, userView.Deleted);
            });
        }
Пример #2
0
        public void SaveUserModify_WhenSetUserModify_ChangeUserWithoutChangeAnythingElse()
        {
            MiniAutoFixture miniAutoFixture = new MiniAutoFixture();

            miniAutoFixture.Initialize();

            int  id      = miniAutoFixture.CreateInt();
            bool deleted = miniAutoFixture.CreateBoolean();
            User user    = new User {
                Id      = id,
                Deleted = deleted,
            };

            UserModify userModify = new UserModify {
                Name    = miniAutoFixture.CreateString(),
                Surname = miniAutoFixture.CreateString()
            };

            // action
            ExtensionMethods.SaveUserModify(user, userModify);

            // assert
            Assert.Equal(id, user.Id);
            Assert.Equal(userModify.Name, user.Name);
            Assert.Equal(userModify.Surname, user.Surname);
            Assert.Equal(deleted, user.Deleted);
        }
Пример #3
0
        public UserView UpdateUser(int id, UserModify userModify)
        {
            User user = _organizerContext.User.Where(a => a.Id == id).Single();

            _organizerContext.Attach(user);
            user.SaveUserModify(userModify);
            _organizerContext.SaveChanges();
            return(_organizerContext.User.Where(a => a.Id == user.Id).Select(a => a.MapUserToView()).Single());
        }
Пример #4
0
        public void InsertUser_MockDbSetUser_AndGetInsertUser()
        {
            //assign
            int             newIdUser       = 11;
            MiniAutoFixture miniAutoFixture = new MiniAutoFixture();

            miniAutoFixture.Initialize();
            List <User>       usersCollection = DbSetTools.CreateUserList(1, 10, miniAutoFixture);
            IQueryable <User> users           = usersCollection.AsQueryable();
            var mockDbSet = new Mock <DbSet <User> >();

            mockDbSet.As <IQueryable <User> >().Setup(m => m.Provider).Returns(users.Provider);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.Expression).Returns(users.Expression);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(users.ElementType);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());
            mockDbSet.Setup(m => m.Add(It.IsAny <User>()))
            .Callback <User>(a =>
            {
                a.Id = newIdUser;
                usersCollection.Add(a);
            });

            var mockContext = new Mock <OrganizerContext>();

            mockContext.Setup(c => c.User).Returns(mockDbSet.Object);
            var logger = new Mock <ILogger <ModifyRepository> >();
            ModifyRepository modifyRepository = new ModifyRepository(mockContext.Object, logger.Object);
            UserModify       userModify       = DomainTools.CreateUserModify(miniAutoFixture);

            //action
            UserView userView = modifyRepository.InsertUser(userModify);

            //assert
            mockDbSet.Verify
            (
                a => a.Add
                (
                    It.Is <User>
                    (

                        user => user.Name == userModify.Name &&
                        user.Surname == userModify.Surname &&
                        !user.Deleted &&
                        user.Id == newIdUser
                    )
                ),
                Times.Once
            );
            mockContext.Verify(a => a.SaveChanges(), Times.Once);


            Assert.Equal(userModify.Name, userView.Name);
            Assert.Equal(userModify.Surname, userView.Surname);
            Assert.Equal(false, userView.Deleted);
            Assert.Equal(newIdUser, userView.Id);
        }
Пример #5
0
 public UserEntity UserModifyToUserEntity(UserModify user)
 {
     return(new UserEntity()
     {
         Login = user.Login,
         Password = user.Password,
         Email = user.Email,
         IsActive = true
     });
 }
Пример #6
0
        public UserView InsertUser(UserModify userModify)
        {
            User user = new User {
                Deleted = false
            };

            user.SaveUserModify(userModify);
            _organizerContext.User.Add(user);
            _organizerContext.SaveChanges();
            return(_organizerContext.User.Where(a => a.Id == user.Id).Select(a => a.MapUserToView()).Single());
        }
Пример #7
0
 public UserEntity UpdateUserEntityByUserModify(UserModify user, UserEntity userEntity)
 {
     if (user.Password != null)
     {
         userEntity.Password = CommonUtils.CheckPasswordsSame(user.Password, userEntity.Password)
         ? userEntity.Password
         : user.Password;
     }
     userEntity.Login = user.Login == userEntity.Login ? userEntity.Login : user.Login;
     userEntity.Email = user.Email == userEntity.Email ? userEntity.Email : user.Email;
     return(userEntity);
 }
Пример #8
0
        public void Put_MockUserRepository_AndUpdateUser()
        {
            //assign
            MiniAutoFixture miniAutoFixture = new MiniAutoFixture();

            miniAutoFixture.Initialize();
            int idUser = miniAutoFixture.CreateInt();

            miniAutoFixture.Initialize();
            UserModify userModify = DomainTools.CreateUserModify(miniAutoFixture);
            UserView   userView   = new UserView
            {
                Id      = idUser,
                Name    = userModify.Name,
                Surname = userModify.Surname,
                Deleted = miniAutoFixture.CreateBoolean()
            };
            var viewRepository   = new Mock <IViewRepository>();
            var modifyRepository = new Mock <IModifyRepository>();
            var logger           = new Mock <ILogger <UserController> >();

            modifyRepository.Setup(a => a.UpdateUser(It.IsAny <int>(), It.IsAny <UserModify>())).Returns <int, UserModify>((a, b) => userView);
            UserController userController = new UserController(viewRepository.Object, modifyRepository.Object, logger.Object);


            //action
            IActionResult actionResult = userController.Put(idUser, userModify);

            //assert
            modifyRepository.Verify
            (
                a =>
                a.UpdateUser
                (
                    It.Is <int>(val => val == idUser),
                    It.Is <UserModify>
                        (val => val.Name == userModify.Name && val.Surname == userModify.Surname)
                )
                , Times.Once
            );

            var okResult   = Assert.IsType <OkObjectResult>(actionResult);
            var returnUser = Assert.IsType <UserView>(okResult.Value);

            Assert.NotNull(returnUser);
            Assert.Equal(userModify.Name, returnUser.Name);
            Assert.Equal(userModify.Surname, returnUser.Surname);
            Assert.Equal(idUser, returnUser.Id);
            Assert.Equal(userView.Deleted, returnUser.Deleted);
        }
Пример #9
0
 public IActionResult Put(int id, [FromBody] UserModify value)
 {
     try {
         if (ModelState.IsValid)
         {
             return(Ok(_modifyRepository.UpdateUser(id, value)));
         }
         else
         {
             _logger.LogError("Error in put", ModelState);
             return(BadRequest(""));
         }
     } catch (Exception ex)
     {
         _logger.LogError("Error in put", ex);
         return(BadRequest());
     }
 }
Пример #10
0
 public IActionResult Post([FromBody] UserModify value)
 {
     try {
         if (ModelState.IsValid)
         {
             return(Ok(_modifyRepository.InsertUser(value)));
         }
         else
         {
             _logger.LogError("Error in post", ModelState);
             return(BadRequest());
         }
     } catch (Exception ex)
     {
         _logger.LogError("Error in post", ex);
         return(BadRequest());
     }
 }
Пример #11
0
        public void ModifytUser_MockDbSetUser_AndGetUpdateUser()
        {
            //assign
            int             idUserUpdate    = 1;
            MiniAutoFixture miniAutoFixture = new MiniAutoFixture();

            miniAutoFixture.Initialize();
            List <User>       usersCollection = DbSetTools.CreateUserList(1, 10, miniAutoFixture);
            IQueryable <User> users           = usersCollection.AsQueryable();
            UserModify        userModify      = DomainTools.CreateUserModify(miniAutoFixture);

            var mockDbSet = new Mock <DbSet <User> >();

            mockDbSet.As <IQueryable <User> >().Setup(m => m.Provider).Returns(users.Provider);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.Expression).Returns(users.Expression);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(users.ElementType);
            mockDbSet.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());


            var mockContext = new Mock <OrganizerContext>();

            mockContext.Setup(c => c.User).Returns(mockDbSet.Object);
            var logger = new Mock <ILogger <ModifyRepository> >();
            ModifyRepository modifyRepository = new ModifyRepository(mockContext.Object, logger.Object);


            //action
            UserView userView = modifyRepository.UpdateUser(idUserUpdate, userModify);

            //assert
            User userModified = usersCollection.Where(a => a.Id == idUserUpdate).Single();

            mockContext.Verify(a => a.Attach(It.Is <User>(user => userModified == user)), Times.Once);
            mockContext.Verify(a => a.SaveChanges(), Times.Once);
            Assert.Equal(userModify.Name, userView.Name);
            Assert.Equal(userModify.Surname, userView.Surname);
            Assert.Equal(userModified.Deleted, userView.Deleted);
            Assert.Equal(idUserUpdate, userView.Id);
        }
Пример #12
0
        public DataTable UserModify([FromBody] UserModify user)
        {
            DataTable dt = null;

            try
            {
                OperationData op = new OperationData();
                dt = op.UserModify(user);
            }
            catch (Exception ex)
            {
                dt = new DataTable();
                dt.Columns.Add("IsSuccess", typeof(string));
                dt.Columns.Add("Error", typeof(string));
                DataRow dr = dt.NewRow();
                dr["IsSuccess"] = "false";
                dr["Error"]     = ex.Message;
                dt.Rows.Add(dr);
                Log.WriteError(ex, "修改用户信息(UserModify)");
            }
            return(dt);
        }
Пример #13
0
        public void PostUser_RunServerAddUserList_GetAddUser()
        {
            DoIntegrationTest(async(client, dbContextOptions) =>
            {
                //Arrange
                MiniAutoFixture miniAutoFixture = new MiniAutoFixture();
                miniAutoFixture.Initialize();
                List <User> userList  = DbSetTools.AddExampleUsersToDatabase(dbContextOptions, miniAutoFixture);
                UserModify userModify = DomainTools.CreateUserModify(miniAutoFixture);

                //Action
                var response = await client.PostAsJsonAsync("/api/user", userModify);


                //Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                var content       = await response.Content.ReadAsStringAsync();
                UserView userView = JsonConvert.DeserializeObject <UserView>(content);
                Assert.Equal(userModify.Name, userView.Name);
                Assert.Equal(userModify.Surname, userView.Surname);
                Assert.Equal(false, userView.Deleted);
                Assert.Equal(true, userView.Id > 0);
            });
        }
Пример #14
0
        public static void SetMainControl(ERMTControl view)
        {
            ERMTUserControl currentUserControl = new ERMTUserControl {
                Name = "new"
            };

            switch (view)
            {
            case ERMTControl.About:
            {
                About about = new About();
                about.ShowDialog();
                break;
            }

            case ERMTControl.EditRegion:
            {
                EditRegion editRegion = new EditRegion();
                currentUserControl = editRegion;
                SetMainControl(editRegion);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.ElectoralCycle:
            {
                IndexUserControl indexUserControl = new IndexUserControl
                {
                    IndexContentType = IndexContentType.ElectoralCycle
                };
                currentUserControl = indexUserControl;
                SetMainControl(indexUserControl);
                ApplicationPrincipalForm.LoadLeftButtons("electoralcycle");
                indexUserControl.ShowHtml();
                break;
            }

            case ERMTControl.ElectoralCycleModifyPhase:
            {
                ElectoralCycleModifyPhase electoralCycleModifyPhase = new ElectoralCycleModifyPhase();
                currentUserControl = electoralCycleModifyPhase;
                SetMainControl(electoralCycleModifyPhase);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.FactorModify:
            {
                FactorModify modifyFactor = new FactorModify();
                currentUserControl = modifyFactor;
                SetMainControl(modifyFactor);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.FactorNew:
            {
                FactorNew newFactor = new FactorNew();
                currentUserControl = newFactor;
                SetMainControl(newFactor);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.FactorReorder:
            {
                FactorsReorder reorderFactors = new FactorsReorder();
                currentUserControl = reorderFactors;
                SetMainControl(reorderFactors);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.KnowledgeResources:
            {
                IndexUserControl indexUserControl = new IndexUserControl
                {
                    IndexContentType = IndexContentType.KnowledgeResources
                };
                currentUserControl = indexUserControl;
                SetMainControl(indexUserControl);
                ApplicationPrincipalForm.LoadLeftButtons("KnowledgeResources");
                indexUserControl.ShowHtml();
                break;
            }

            case ERMTControl.Login:
            {
                LoginUserControl loginUserControl = new LoginUserControl();
                currentUserControl = loginUserControl;
                SetMainControl(loginUserControl);
                break;
            }

            case ERMTControl.MarkerTypeCRUD:
            {
                MarkerTypeCRUD markerTypeControl = new MarkerTypeCRUD();
                currentUserControl = markerTypeControl;
                SetMainControl(markerTypeControl);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.ModelEdit:
            {
                ModelEdit modelEdit = new ModelEdit();
                currentUserControl = modelEdit;
                SetMainControl(modelEdit);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.ModelNew:
            {
                ModelNew modelNew = new ModelNew();
                currentUserControl = modelNew;
                SetMainControl(modelNew);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.ModelReorderFactors:
            {
                ModelReorderFactors modelReorderFactors = new ModelReorderFactors();
                currentUserControl = modelReorderFactors;
                SetMainControl(modelReorderFactors);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.RiskActionRegister:
            {
                RiskAndActionRegister riskActionRegister = new RiskAndActionRegister(true);
                currentUserControl = riskActionRegister;
                SetMainControl(riskActionRegister);
                ApplicationPrincipalForm.LoadLeftButtons("riskandaction");
                break;
            }

            case ERMTControl.RiskMapping:
            {
                //RiskMapping riskMapping = new RiskMapping();
                //currentUserControl = riskMapping;
                //SetMainControl(riskMapping);
                currentUserControl = ControlCache.RiskMappingInstance;
                SetMainControl(ControlCache.RiskMappingInstance);
                ApplicationPrincipalForm.LoadLeftButtons("map");
                break;
            }

            case ERMTControl.Start:
            {
                SetMainControl(ControlCache.StartInstance);
                currentUserControl = ControlCache.StartInstance;
                ApplicationPrincipalForm.LoadLeftButtons("Start");
                break;
            }

            case ERMTControl.TestUserControl:
            {
                TestUserControl testUserControl = new TestUserControl();
                SetMainControl(testUserControl);
                break;
            }

            case ERMTControl.UserModify:
            {
                UserModify userModify = new UserModify();
                currentUserControl = userModify;
                SetMainControl(userModify);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.UserNew:
            {
                UserNew userNew = new UserNew();
                currentUserControl = userNew;
                SetMainControl(userNew);
                ApplicationPrincipalForm.LoadLeftButtons();
                break;
            }

            case ERMTControl.UserResetPassword:
            {
                UserChangePassword ucp = new UserChangePassword();
                ucp.ShowDialog();

                break;
            }
            }
            if (currentUserControl.Name != "new")
            {
                currentUserControl.ShowTitle();
            }
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public DataTable UserModify(UserModify user)
        {
            DataTable     dt       = null;
            StringBuilder sb       = new StringBuilder();
            StringBuilder sbwhere  = new StringBuilder();
            StringBuilder sql      = new StringBuilder();
            string        phone    = string.Empty;
            string        idnumber = string.Empty;
            string        id       = string.Empty;

            try
            {
                if (user != null)
                {
                    foreach (var item in user.GetType().GetProperties())
                    {
                        string name  = item.Name;
                        string value = item.GetValue(user) == null ? string.Empty : item.GetValue(user).ToString();
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            if (name == "phone")
                            {
                                phone = value;
                            }
                            if (name == "idnumber")
                            {
                                idnumber = value;
                            }
                            if (name == "id")
                            {
                                id = value;
                                sbwhere.AppendFormat(" WHERE {0}={1}", name, value);
                            }
                            else
                            {
                                if (sb != null && !string.IsNullOrWhiteSpace(sb.ToString()))
                                {
                                    sb.AppendFormat(" ,{0}='{1}'", name, value);
                                }
                                else
                                {
                                    sb.AppendFormat("{0}='{1}'", name, value);
                                }
                            }
                        }
                    }
                }
                if (sb != null && !string.IsNullOrWhiteSpace(sb.ToString()))
                {
                    sql.Append("DECLARE @isexist INT =0;");
                    sql.Append("DECLARE @errmsg VARCHAR(500);");
                    if (!string.IsNullOrWhiteSpace(phone))       //手机不为空时 检查手机是否有重复
                    {
                        sql.AppendFormat(@"
                        IF EXISTS (SELECT 1 FROM EP_User WHERE Phone ='{0}' AND ID != {1} )
                        BEGIN
                            SET @isexist =1;
	                        SET @errmsg ='手机 ';
                        END", phone, id);
                    }
                    if (!string.IsNullOrWhiteSpace(idnumber))  //身份证不为空时 检查身份证是否有重复
                    {
                        sql.AppendFormat(@"
                        IF EXISTS (SELECT 1 FROM EP_User WHERE IDNumber ='{0}' AND ID != {1} )
                        BEGIN
                            SET @isexist =1;
	                        SET @errmsg = @errmsg + '身份证 ';
                        END", idnumber, id);
                    }
                    sql.AppendFormat(@"
                    IF (@isexist =1)
                    BEGIN
                        SELECT 'false' AS IsSuccess, @errmsg + '已存在' AS Error; 
                    END
                    ELSE
                    BEGIN
                        UPDATE EP_User SET {0} {1} ; 
	                    SELECT 'true' AS IsSuccess ,'' AS Error,* FROM EP_User {2};
                    END", sb.ToString(), sbwhere.ToString(), sbwhere.ToString());
                    EPData ep = new EPData();
                    dt = ep.GetData(sql.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(dt);
        }