Example #1
0
        public ActionResult Update(int id)
        {
            User user = _dbContext.Users.FirstOrDefault(x => x.Id == id);

            if (user != null)
            {
                UpdateUserDTO data = new UpdateUserDTO();
                data.Id               = user.Id;
                data.Ad               = user.Ad;
                data.Soyad            = user.Soyad;
                data.Tckn             = user.Tckn;
                data.Email            = user.Email;
                data.Telefon          = user.Telefon;
                data.Görev            = user.Görev;
                data.Unvan            = user.Unvan;
                data.Kullanıcı_Rolü   = user.Kullanıcı_Rolü;
                data.İse_Giris_Tarihi = user.İse_Giris_Tarihi;
                data.Parola           = user.Parola;
                return(View(data));
            }
            else
            {
                return(RedirectToAction("List"));
            }
        }
Example #2
0
        public ActionResult Update(UpdateUserDTO data)
        {
            if (ModelState.IsValid)
            {
                User user = _dbContext.Users.FirstOrDefault(x => x.Id == data.Id);

                user.Ad               = data.Ad;
                user.Soyad            = data.Soyad;
                user.Tckn             = data.Tckn;
                user.Email            = data.Email;
                user.Telefon          = data.Telefon;
                user.Görev            = data.Görev;
                user.Unvan            = data.Unvan;
                user.Kullanıcı_Rolü   = data.Kullanıcı_Rolü;
                user.İse_Giris_Tarihi = data.İse_Giris_Tarihi;
                user.Parola           = data.Parola;
                user.UpdateDate       = DateTime.Now;
                user.Status           = Status.Modified;

                _dbContext.SaveChanges();
                return(RedirectToAction("List"));
            }
            else
            {
                return(View(data));
            }
        }
        public async Task KeepSameSecondName()
        {
            var options = Utils.GetOptions(nameof(KeepSameSecondName));

            var userStore   = new Mock <IUserStore <User> >();
            var userManager = new Mock <UserManager <User> >(userStore.Object, null, null, null,
                                                             null, null, null, null, null).Object;
            var contextAccessor      = new Mock <IHttpContextAccessor>().Object;
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <User> >().Object;
            var signManager          = new Mock <SignInManager <User> >(userManager, contextAccessor, userPrincipalFactory, null, null, null, null).Object;
            var updateDTO            = new UpdateUserDTO()
            {
                FirstName = "John"
            };

            using (var arrContext = new PhotoContestContext(options))
            {
                await arrContext.Ranks.AddRangeAsync(Utils.SeedRanks());

                await arrContext.Users.AddRangeAsync(Utils.SeedUsers());

                await arrContext.SaveChangesAsync();
            }
            using (var actContext = new PhotoContestContext(options))
            {
                var sut          = new UserService(actContext, userManager, signManager);
                var userToUpdate = actContext.Users.Last();
                var result       = await sut.UpdateAsync(updateDTO, userToUpdate.UserName);

                var lastNameChecker = userToUpdate.LastName;
                Assert.AreEqual(updateDTO.FirstName, result.FirstName);
                Assert.AreEqual(lastNameChecker, result.LastName);
            }
        }
Example #4
0
        public IActionResult Put([FromBody] UpdateUserDTO dto)
        {
            var userId = AuthMiddleware.GetUserId(User);

            _service.Update(dto, userId);
            return(Ok("Successfully updated!"));
        }
        public IActionResult Put([FromBody] UpdateUserDTO dto)
        {
            var id = GetTokenId.getId(User);

            _userService.Update(dto, id);
            return(Ok("succesufully updated"));
        }
Example #6
0
        public ServiceResult <UserDTO> UpdatePassword(UpdateUserDTO model)
        {
            string errorMessage = string.Empty;
            EnumServiceResultType serviceResultType = EnumServiceResultType.Unspecified;
            UserDTO result = null;

            try
            {
                var existingUser = _userRepository.Entities.Where(p => p.Username == model.Username).SingleOrDefault();

                if (existingUser == null)
                {
                    throw new Exception("Kullanıcı bulunamadı.");
                }

                existingUser.Password = model.Password;


                _unitOfWork.SaveChanges();

                result            = GetUser(existingUser.Id);
                serviceResultType = EnumServiceResultType.Success;
            }
            catch (Exception ex)
            {
                errorMessage      = ex.Message;
                serviceResultType = EnumServiceResultType.Error;
            }
            return(new ServiceResult <UserDTO> {
                ErrorMessage = errorMessage, Result = result, ServiceResultType = serviceResultType
            });
        }
Example #7
0
        public ActionResult <UserDTO> UpdateUserRole(int id, UpdateUserDTO updateUserDTO)
        {
            if (_authService.IsAuthenticated(HttpContext.User))
            {
                if (_authService.IsAdmin(HttpContext.User))
                {
                    var role = _roleService.GetRoleById(updateUserDTO.RoleId);
                    var user = _userService.GetUserById(id);

                    if (user == null)
                    {
                        return(NotFound());
                    }

                    if (role == null)
                    {
                        return(BadRequest());
                    }

                    user.RoleId = updateUserDTO.RoleId;

                    _userService.UpdateUser(user);

                    _userService.SaveChanges();

                    return(Ok(_mapper.Map <UserDTO>(user)));
                }

                return(Forbid());
            }

            return(Unauthorized());
        }
Example #8
0
        public async Task <bool> UpdateUserAsync(UpdateUserDTO data)
        {
            var user = _userManager.FindByIdAsync(data.UserId).Result;

            if (user == null)
            {
                return(false);
            }

            user.FirstName = data.FirstName;
            user.LastName  = data.FirstName;
            user.Surname   = data.Surname;
            user.State     = data.State;

            user.Address     = data.Address;
            user.PhoneNumber = data.PhoneNumber;

            try
            {
                using (var context = _context)
                {
                    context.Users.Attach(user);

                    await _context.SaveChangesAsync();
                }

                return(true);
            }
            catch (Exception ex)
            {
            }

            return(false);
        }
Example #9
0
        public async Task UpdateUser(string id, UpdateUserDTO updateUserDto)
        {
            var userInDb = await GetApplicationUserById(id);

            _mapper.Map(updateUserDto, userInDb);
            await _dbContext.SaveChangesAsync();
        }
Example #10
0
        public async Task updateUser(string apiToken, UpdateUserDTO model, string userId)
        {
            try
            {
                var userCurrent = await this.getcurrentUserDetails(apiToken);

                var url = _configuration.GetSection("ZoomEndpoints:Endpoints:4:url").Value;
                using (var httpClient = new HttpClient())
                {
                    var         payload = JsonConvert.SerializeObject(model);
                    HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
                    var queryString = new QueryString(string.Empty).ToString();
                    queryString = userId;
                    url         = url + "/" + queryString;
                    var response = await httpClient.PutAsync(url, content);

                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        var resError = JsonConvert.DeserializeObject <ApiResponseDTO>(apiResponse);
                        throw new Exception(resError.message.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <Response <string> > UpdateUser(User user, UpdateUserDTO model)
        {
            Response <string> response = new Response <string>();

            if (user == null)
            {
                response.Message = "Sorry! You cannot perform this operation";
                return(response);
            }
            user.FirstName          = model.FirstName ?? user.FirstName;
            user.LastName           = model.LastName ?? user.LastName;
            user.UserName           = model.UserName ?? user.UserName;
            user.Gender             = model.Gender ?? user.Gender;
            user.Squad              = model.Squad ?? user.Squad;
            user.PhoneNumber        = model.PhoneNumber ?? user.PhoneNumber;
            user.IsProfileCompleted = true;

            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                response.Message = "Update Successful";
                response.Success = true;
            }
            else
            {
                response.Message = "Could not update user";
            }

            return(response);
        }
Example #12
0
        //[Authorize(Roles = "UpdateUser")]
        public IActionResult UpdateUser(int id, [FromBody] UpdateUserDTO updateUserDTO)
        {
            updateUserDTO.Name = updateUserDTO.Name.Trim();
            if (string.IsNullOrWhiteSpace(updateUserDTO.Name))
            {
                var message = Messages.EmptyName;
                message.ActionName     = "Update User";
                message.ControllerName = "User";
                return(BadRequest(message));
            }
            var simelar = _userRepositroy.Get(c => c.Name == updateUserDTO.Name && c.Id != id).FirstOrDefault();

            if (simelar != null)
            {
                var message = Messages.Exist;
                message.ActionName     = "Update User";
                message.ControllerName = "User";
                return(Conflict(message));
            }
            var user = _userRepositroy.Find(id);

            if (user == null)
            {
                var message = Messages.NotFound;
                message.ActionName     = "Update User";
                message.ControllerName = "User";
                message.Message        = "المستخدم غير موجود";
                return(NotFound(message));
            }
            user = _mapper.Map(updateUserDTO, user);
            _userRepositroy.Update(user, UserName());
            _userRepositroy.Save();
            return(Ok());
        }
Example #13
0
        public User UpdateUser(UpdateUserDTO updatedUser)
        {
            using (var context = new TwitterContext())
            {
                try
                {
                    var user = context.Users
                               .Include("MyTweets")
                               .Include("FavoritedTweets")
                               .Include("FollowingUsers")
                               .Include("FollowedBy")
                               .Include("Comments")
                               .FirstOrDefault(x => x.Id == updatedUser.Id);
                    if (user == null)
                    {
                        throw new NullReferenceException("Error when getting the required user!");
                    }

                    user.Username = updatedUser.Username;
                    user.Password = updatedUser.Password;
                    user.Name     = updatedUser.Name;
                    user.Lastname = updatedUser.Lastname;
                    user.Email    = updatedUser.Email;

                    context.SaveChanges();
                    return(user);
                }
                catch (Exception e)
                {
                    throw new Exception("Required user not found. Exception: " + e.Message);
                }
            }
        }
Example #14
0
        public void Update(UpdateUserDTO entity, int id)
        {
            var user = _unitOfWork.User.Get(id);

            if (!String.IsNullOrEmpty(entity.FirstName))
            {
                user.FirstName = entity.FirstName;
            }
            if (!String.IsNullOrEmpty(entity.LastName))
            {
                user.LastName = entity.LastName;
            }
            if (!String.IsNullOrEmpty(entity.Password))
            {
                user.Password = Compute256Hash.ComputeSha256Hash(entity.Password);
            }
            if (!String.IsNullOrEmpty(entity.Email))
            {
                user.Email = entity.Email;
            }
            if (entity.IsDeleted == 0 || entity.IsDeleted == 1)
            {
                user.IsDeleted = entity.IsDeleted;
            }
            if (entity.RoleId == 1 || entity.RoleId == 2)
            {
                user.RoleId = entity.RoleId;
            }
            user.ModifiedAt = DateTime.Now;
            _unitOfWork.Save();
        }
Example #15
0
        public ResultDTO UpdateUser(long UserId, UpdateUserDTO UserEntity)
        {
            var result = new ResultDTO {
                IsSuccess = false
            };

            if (UserEntity != null)
            {
                using (var scope = new TransactionScope())
                {
                    var user = _unitOfWork.UserRepository.GetByID(UserId);
                    if (UserEntity != null)
                    {
                        user.UserId     = UserEntity.UserId;
                        user.Username   = UserEntity.Username;
                        user.FirstName  = UserEntity.FirstName;
                        user.LastName   = UserEntity.LastName;
                        user.EmailId    = UserEntity.EmailId;
                        user.RoleId     = UserEntity.RoleId;
                        user.ModifiedBy = UserEntity.ModifiedBy;
                        user.ModifiedOn = DateTime.Now;
                        _unitOfWork.UserRepository.Update(user);
                        _unitOfWork.Save();
                        scope.Complete();

                        result.IsSuccess = true;
                        result.Message   = "Updated Successfully";
                    }
                }
            }
            return(result);
        }
Example #16
0
        public async Task UpdateAsync(UpdateUserDTO dto)
        {
            using (UserContext ctx = new UserContext())
            {
                BaseService <UserEntity> userBs = new BaseService <UserEntity>(ctx);
                var emailEntity = await userBs.GetAll().SingleOrDefaultAsync(e => e.Email == dto.Email || e.NickName == dto.NickName);

                if (emailEntity != null)
                {
                    if (emailEntity.Id != dto.Id)
                    {
                        throw new Exception("用户邮箱或者昵称已存在");
                    }
                }
                var user = await userBs.GetAll().SingleOrDefaultAsync(e => e.Id == dto.Id);

                if (user == null)
                {
                    return;
                }
                user.Autograph = dto.Autograph;
                user.City      = dto.City;
                user.Email     = dto.Email;
                user.Gender    = dto.Gender;
                if (user.Email != dto.Email)
                {
                    user.IsActive = false;
                }
                user.NickName = dto.NickName;
                await ctx.SaveChangesAsync();
            }
        }
Example #17
0
        public async Task <ServiceResponse <GetUserDTO> > UpdateUser(UpdateUserDTO updatedUser)
        {
            var serviceResponse = new ServiceResponse <GetUserDTO>();

            try
            {
                User user = await _repository.GetByIdAsync(updatedUser.Id);

                if (user == null)
                {
                    return(serviceResponse);
                }

                // TODO: Check permission
                user.Birthday    = updatedUser.Birthday == null ? user.Birthday : updatedUser.Birthday;
                user.Description = updatedUser.Description == null ? user.Description : updatedUser.Description;
                user.Gender      = updatedUser.Gender == null ? user.Gender : updatedUser.Gender.Value;
                user.Name        = updatedUser.Name == null ? user.Name : updatedUser.Name;
                user.Picture     = updatedUser.Picture == null ? user.Picture : updatedUser.Picture;

                await _repository.Update(user);

                serviceResponse.Data = _mapper.Map <GetUserDTO>(await _repository.GetByIdAsync(user.Id));
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
            }

            return(serviceResponse);
        }
Example #18
0
        public async Task <IActionResult> UpdateSource(int id, [FromBody] UpdateUserDTO source)
        {
            try
            {
                if (source == null)
                {
                    return(BadRequest());
                }
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid model object"));
                }
                var sourceEntity = await _repositoryWrapper.UserRepo.GetDataByIdAsync(id);

                if (sourceEntity == null)
                {
                    return(NotFound());
                }
                _mapper.Map(source, sourceEntity);
                _repositoryWrapper.UserRepo.UpdateData(sourceEntity);
                await _repositoryWrapper.SaveAsync();

                return(Ok("Update successfully!"));
            }
            catch (Exception ex)
            {
                //_logger.LogError($"Something went wrong inside CreateSources action: {ex.Message}");
                if (ex.InnerException != null)
                {
                    return(BadRequest(ex.Message + "," + ex.InnerException.Message));
                }
                return(BadRequest(ex.Message));
            }
        }
        public async Task <ServiceResponse <GetUserDTO> > UpdateUser(UpdateUserDTO updatedUser)
        {
            ServiceResponse <GetUserDTO> serviceResponse = new ServiceResponse <GetUserDTO>();

            try {
                // Grab the specific User from the database asynchronously.
                User user = await _context.Users.FirstOrDefaultAsync(f => f.Id == updatedUser.Id);

                user.Email         = updatedUser.Email;
                user.FirstName     = updatedUser.FirstName;
                user.LastName      = updatedUser.LastName;
                user.Organization  = updatedUser.Organization;
                user.Points        = updatedUser.Points;
                user.Certificates  = updatedUser.Certificates;
                user.Registrations = updatedUser.Registrations;

                // Update the particular User in the database
                _context.Users.Update(user);
                // Save the changes in the database
                await _context.SaveChangesAsync();

                serviceResponse.Message = "User update successful.";
                serviceResponse.Data    = _mapper.Map <GetUserDTO>(user);
            } catch (Exception ex) {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
            }

            return(serviceResponse);
        }
        public void UpdateUser_WithCorrectData_ShouldUpdateUserProperly()
        {
            string errorMessagePrefix = "UserService UpdateUser() method does not work properly.";

            var repo            = new Mock <IRepository <ApplicationUser> >();
            var mockUserManager = new Mock <UserManager <ApplicationUser> >(
                new Mock <IUserStore <ApplicationUser> >().Object,
                new Mock <IOptions <IdentityOptions> >().Object,
                new Mock <IPasswordHasher <ApplicationUser> >().Object,
                new IUserValidator <ApplicationUser> [0],
                new IPasswordValidator <ApplicationUser> [0],
                new Mock <ILookupNormalizer>().Object,
                new Mock <IdentityErrorDescriber>().Object,
                new Mock <IServiceProvider>().Object,
                new Mock <ILogger <UserManager <ApplicationUser> > >().Object);

            repo.Setup(r => r.All()).Returns(GetTestData().AsQueryable);

            this._userService = new UserService(repo.Object, mockUserManager.Object);

            var updateUserDto = new UpdateUserDTO
            {
                Role = "Editor"
            };

            var isCompleted = this._userService.UpdateUser("1", updateUserDto, true).IsCompletedSuccessfully;

            Assert.True(isCompleted, errorMessagePrefix);
        }
Example #21
0
        public async Task UpdateUser(string id, UpdateUserDTO userDTO, bool skipMethodForTest = false)
        {
            var user = this._userRepository
                       .All()
                       .Single(x => x.Id == id);

            var roles = new [] { "Admin", "User", "Editor" };

            if (!roles.Contains(userDTO.Role))
            {
                throw new InvalidOperationException("Role doesn't exist.");
            }

            var userRole = "";

            if (!skipMethodForTest)
            {
                userRole = this.GetUserRole(id);
            }

            await this._userManager.RemoveFromRoleAsync(user, userRole);

            await this._userManager.AddToRoleAsync(user, userDTO.Role);

            await this._userRepository.SaveChangesAsync();
        }
Example #22
0
        public void UpdateUser(string id, UpdateUserDTO updatedUserDTO)
        {
            User user = _uow.Users.Find(id);

            if (updatedUserDTO.UserName != null)
            {
                user.UserName = updatedUserDTO.UserName;
            }
            if (updatedUserDTO.FirstName != null)
            {
                user.FirstName = updatedUserDTO.FirstName;
            }
            if (updatedUserDTO.LastName != null)
            {
                user.LastName = updatedUserDTO.LastName;
            }
            if (updatedUserDTO.PhoneNumber != null)
            {
                user.PhoneNumber = updatedUserDTO.PhoneNumber;
            }
            if (updatedUserDTO.Password != null)
            {
                user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, updatedUserDTO.Password);
            }
            _uow.Users.Update(user);
            _uow.SaveChanges();
        }
Example #23
0
        public void UpdateUser(UpdateUserDTO userDto)
        {
            try
            {
                _logger.Info("Start updatin user with id " + userDto.Id);

                var user = _userRepository.GetById(userDto.Id);
                if (user == null)
                {
                    throw new ServiceException("No user with this id");
                }

                Mapper.Initialize(
                    cfg => cfg.CreateMap <UpdateUserDTO, User>( ));
                //user = Mapper.Map<UpdateUserDTO, User> (userDto);
                user.LastUpdate  = DateTime.Now;
                user.UserName    = userDto.UserName;
                user.Email       = userDto.Email;
                user.PhoneNumber = userDto.PhoneNumber;
                user.DateBirth   = userDto.DateBirth;
                user.Information = userDto.Information;
                user.Name        = userDto.Name;
                user.Surname     = userDto.Surname;
                _userRepository.Update(user);
                _logger.Info("Update user with id " + user.Id);
            }
            catch (RepositoryException re)
            {
                throw new ServiceException("Repositiry ex: " + re.Message);
            }
            catch (Exception ex)
            {
                throw new ServiceException(ex.Message);
            }
        }
Example #24
0
        public async Task <ServiceResponse <GetUserDTO> > UpdateUser(UpdateUserDTO updatedUser)
        {
            ServiceResponse <GetUserDTO> serviceResponse = new ServiceResponse <GetUserDTO>();

            try
            {
                var user = await _context.Users.FindAsync(updatedUser.Id);

                if (user == null)
                {
                    serviceResponse.Success = false;
                    serviceResponse.Message = $"Could not found user with id '{updatedUser.Id}'";
                }
                else
                {
                    user.Firstname = updatedUser.Firstname;
                    user.Lastname  = updatedUser.Lastname;
                    user.Phone     = updatedUser.Phone;

                    _context.Users.Update(user);
                    await _context.SaveChangesAsync();

                    serviceResponse.Data = _mapper.Map <GetUserDTO>(user);
                }
            }
            catch (Exception ex)
            {
                serviceResponse.Success   = false;
                serviceResponse.Exception = ex.Message;
            }
            return(serviceResponse);
        }
Example #25
0
        public void Update(int userId, UpdateUserDTO updateUser)
        {
            var user = _userRepository.GetById(userId);

            user.Update(new Username(updateUser.Username), new Password(updateUser.Password));
            _userRepository.Update(user);
        }
 public User Update([FromBody] UpdateUserDTO UpdateUserData)
 {
     if (!UpdateUserData.Validate())
     {
         throw new HttpResponseException(new HttpResponseMessage()
         {
             StatusCode   = System.Net.HttpStatusCode.InternalServerError,
             ReasonPhrase = "Trying to update invalid User",
             Content      = new StringContent("The User is not valid and can't be updated")
         });
     }
     try
     {
         var User = new User()
         {
             Id        = UpdateUserData.Id,
             Name      = UpdateUserData.Name,
             Birthdate = UpdateUserData.Birthdate,
         };
         return(UserService.Update(User));
     }
     catch (HttpResponseException Ex) //catches an exception from a deeper layer
     {
         throw Ex;
     }
 }
Example #27
0
        public void Update(UpdateUserDTO dto, int id)
        {
            var user = _unitOfWork.User.Get(id);

            if (!String.IsNullOrEmpty(dto.Email) && dto.Email.Contains("@"))
            {
                user.Email = dto.Email;
            }
            if (!String.IsNullOrEmpty(dto.FirstName))
            {
                user.FirstName = dto.FirstName;
            }
            if (!String.IsNullOrEmpty(dto.LastName))
            {
                user.LastName = dto.LastName;
            }
            if (!String.IsNullOrEmpty(dto.Password))
            {
                user.Password = AuthMiddleware.ComputeSha256Hash(dto.Password);
            }
            if (dto.IsDeleted == 0 || dto.IsDeleted == 1)
            {
                user.IsDeleted = dto.IsDeleted;
            }
            user.ModifiedAt = DateTime.Now;
            _unitOfWork.Save();
        }
Example #28
0
        public IActionResult Put([FromQuery] int Id, [FromBody] UpdateUserDTO user)
        {
            try
            {
                var existingUser = _userService.GetUser(Id);

                if (existingUser is null)
                {
                    return(NotFound("User does not exists."));
                }

                if (_user.Email == existingUser.Email || _user.Role == UserRolesEnum.Negotiator.ToString())
                {
                    _userService.Update(Id, user);
                    return(Ok("Updated"));
                }
                else
                {
                    return(Unauthorized("You can not update this user."));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Example #29
0
 public bool Put([FromBody] UpdateUserDTO user)
 {
     if (user != null && User.Identity.IsAuthenticated)
     {
         return(service.UpdateUser(user, User.Identity.Name));
     }
     return(false);
 }
Example #30
0
        public async Task <JsonResult> UpdateUser([FromBody] UpdateUserDTO userDetails)
        {
            if (userDetails == null)
            {
                return(null);
            }

            return(Json(await _user.UpdateUserAsync(userDetails)));
        }