Exemple #1
0
        public async Task <IActionResult> Details(int?id)
        {
            IActionResult actionResult = null;

            var viewModel = new UserDetailsViewModel();

            var attendee = id.HasValue
                ? await this.DatabaseContext.Attendee
                           .FirstOrDefaultAsync(m => m.UserID == id)
                : null;

            if (attendee == null)
            {
                actionResult = this.NotFound();
            }
            else
            {
                viewModel.User = attendee;

                viewModel.PointsBalance = PointsUtils.GetPointsForUser(
                    attendee.UserID,
                    this.DatabaseContext);

                actionResult = this.View(viewModel);
            }

            return(actionResult);
        }
        //
        // GET: /Users/Details/5
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var user = await UserManager.FindByIdAsync(id);

            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);

            var detailsModel = new UserDetailsViewModel()
            {
                User = user, Lockout = new LockoutViewModel()
            };
            var isLocked = await UserManager.IsLockedOutAsync(user.Id);

            detailsModel.Lockout.Status = isLocked ? LockoutStatus.Locked : LockoutStatus.Unlocked;
            if (detailsModel.Lockout.Status == LockoutStatus.Locked)
            {
                detailsModel.Lockout.LockoutEndDate = (await UserManager.GetLockoutEndDateAsync(user.Id)).DateTime;
            }

            return(View(detailsModel));
        }
Exemple #3
0
        public Result <UserDetailsViewModel> GetDetailsViewModel(string id)
        {
            SelectSpecification <AppUserEntity, UserDetailsViewModel> userSpecification = new SelectSpecification <AppUserEntity, UserDetailsViewModel>();

            userSpecification.AddFilter(x => x.Id == id);
            userSpecification.AddSelect(x => new UserDetailsViewModel(
                                            /*id:*/ x.Id,
                                            /*userName:*/ x.UserName,
                                            /*email:*/ x.Email,
                                            /*firstName:*/ x.FirstName,
                                            /*lastName:*/ x.LastName,
                                            /*emailConfirmed:*/ x.EmailConfirmed,
                                            /*phoneNumber:*/ x.PhoneNumber,
                                            /*phoneNumberConfirmed:*/ x.PhoneNumberConfirmed,
                                            /*twoFactorEnabled:*/ x.TwoFactorEnabled,
                                            /*enabled:*/ x.Enabled,
                                            /*LockoutEnd:*/ x.LockoutEnd.HasValue ? x.LockoutEnd.Value.ToString("d.M.yyyy HH:mm:ss") : null));

            UserDetailsViewModel userDetails = _userRepository.SingleOrDefault(userSpecification);

            if (userDetails == null)
            {
                return(Result.Fail <UserDetailsViewModel>("no_user", "No user"));
            }

            userDetails.UseEmailSender = _identityUIEndpoints.UseEmailSender ?? false;

            return(Result.Ok(userDetails));
        }
        public async Task EditUserAsync(ClaimsPrincipal user, UserDetailsViewModel viewModel)
        {
            var currentUser = await this.userManager.GetUserAsync(user);

            if (currentUser == null)
            {
                this.logger.LogWarning(ErrorMessages.UnableToLoadUser);
                throw new ApplicationException(ErrorMessages.UnableToLoadUser);
            }

            try
            {
                currentUser.UserName    = viewModel.Username;
                currentUser.FirstName   = viewModel.FirstName;
                currentUser.LastName    = viewModel.LastName;
                currentUser.BirthDate   = viewModel.BirthDate;
                currentUser.Address     = viewModel.Address;
                currentUser.PhoneNumber = viewModel.PhoneNumber;

                await this.userManager.UpdateAsync(currentUser);

                logger.LogInformation(string.Format(LogMessages.UserWasUpdated, currentUser.Id));
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var user = await UserManager.FindByIdAsync(id);

            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);

            var detailsModel = new UserDetailsViewModel()
            {
                User = user, Lockout = new LockoutViewModel()
            };
            var isLocked = await UserManager.IsLockedOutAsync(user.Id);

            detailsModel.Lockout.Status = isLocked ? LockoutStatus.Locked : LockoutStatus.Unlocked;
            if (detailsModel.Lockout.Status == LockoutStatus.Locked)
            {
                detailsModel.Lockout.LockoutEndDate = (await UserManager.GetLockoutEndDateAsync(user.Id)).DateTime;
            }

            var claims = await UserManager.GetClaimsAsync(user.Id);

            detailsModel.Claims     = claims.ToList();
            detailsModel.Email      = Request["Email"];
            detailsModel.RoleId     = Request["RoleId"];
            detailsModel.SearchExec = Request["SearchExec"];
            detailsModel.Page       = Request["Page"];
            detailsModel.IsLocked   = Convert.ToInt32(Request["IsLocked"]);

            return(View(detailsModel));
        }
        public async Task <IActionResult> UserDetails(UserDetailsViewModel model)
        {
            var header = this.Request.Headers["sec-fetch-site"];

            if (header == "none")
            {
                return(RedirectToAction("Index", "Advertisement"));
            }

            if (ModelState.IsValid)
            {
                User currentUser = await signInManager.UserManager.GetUserAsync(this.User);

                currentUser = await db.Users.FirstOrDefaultAsync(u => u.Id == currentUser.Id);

                currentUser.Firstname = model.Firstname;
                currentUser.Lastname  = model.Lastname;
                currentUser.Email     = model.Email;
                currentUser.Birthdate = model.Birthdate;
                currentUser.Sex       = model.Sex;
                currentUser.Address   = model.Address;
                db.Update <User>(currentUser);
                await db.SaveChangesAsync();

                toastNotification.AddSuccessToastMessage("Personal Details Edited !", new NotyOptions
                {
                    Theme   = "metroui",
                    Timeout = 1500,
                    Layout  = "topCenter"
                });
            }
            return(PartialView("_UserDetails", model));
        }
        public ActionResult Delete(int?id)
        {
            if (id == null || AuthenticationService.LoggedUser.Id == id)
            {
                return(RedirectToAction("Index"));
            }

            UserRepository userRepo = new UserRepository();

            User user = userRepo.GetById(id.Value);

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

            UserDetailsViewModel u = new UserDetailsViewModel()
            {
                Id        = user.Id,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Username  = user.Username,
                Email     = user.Email
            };

            if (user.ImageName != null)
            {
                u.ImageName = user.ImageName;
            }

            return(View(u));
        }
Exemple #8
0
        public JsonResult InviteAFriend(string userId)
        {
            DataSet userDetailSet    = iFriendInvitationRepository.GetUserDetails(userId);
            bool    invitationStatus = false;

            if (userDetailSet.Tables.Count > 0)
            {
                UserDetailsViewModel userDetailsViewModel = userDetailSet.Tables[0].AsEnumerable().Select(result => new UserDetailsViewModel
                {
                    UserId      = result.Field <string>("UserId"),
                    UserName    = result.Field <string>("UserName"),
                    EmailId     = result.Field <string>("EmailId"),
                    CompanyId   = result.Field <int>("CompanyId"),
                    CompanyName = result.Field <string>("CompanyName")
                }).FirstOrDefault();
                var    hostName    = Resources.GetHostName(HttpContext.Request.Url.ToString());
                string mailContent = mailer.MailContentBuilder(Messages.InviteFriendToCompanyEmailBody,
                                                               new string[] { userDetailsViewModel.UserName,
                                                                              hostName, Url.Action("AcceptInvitation", "InviteFriends",
                                                                                                   new { area = "InviteFriends", userName = userDetailsViewModel.UserId, verfid = encDecryption.Encrypt(Convert.ToString(userSession.CompanyId)) }),
                                                                              User.Identity.Name });
                mailer.SetMailData(userDetailsViewModel.EmailId, string.Format("Invitation from {0}", User.Identity.Name), mailContent, true, true);
                invitationStatus = mailer.SendMail() ? iFriendInvitationRepository.LogInvitation(userId, SessionUserId, userDetailsViewModel.CompanyId.GetDefaultValueIfNull <string>()) : false;
            }

            return(Json(invitationStatus, JsonRequestBehavior.AllowGet));
        }
Exemple #9
0
        public async Task Details_ValidPersonnelUser_Success()
        {
            string USER_ID = Guid.NewGuid().ToString();

            await dbContext.Users.AddAsync(new User("TestName", "TestUserName", "*****@*****.**", DateTime.Now) { Id = USER_ID });

            await dbContext.UserRoles.AddAsync(new IdentityUserRole <string>() { UserId = USER_ID, RoleId = dbContext.Roles.First(r => r.NormalizedName == Roles.PERSONNEL.ToUpperInvariant()).Id });

            await dbContext.SaveChangesAsync();

            var service = new AdminUserService(dbContext, userManager, roleManager, signInManager, new Mock <IServerNewsService>().Object);

            UserDetailsViewModel userDetails = await service.DetailsAsync(USER_ID);

            User foundUser = await dbContext.Users.FindAsync(USER_ID);

            Assert.IsNotNull(userDetails);

            Assert.AreEqual(foundUser.BirthDate, userDetails.BirthDate);
            Assert.AreEqual(foundUser.Email, userDetails.Email);
            Assert.AreEqual(foundUser.FullName, userDetails.FullName);
            Assert.AreEqual(foundUser.PhoneNumber, userDetails.PhoneNumber);
            Assert.AreEqual(foundUser.Qualification, userDetails.Qualification);
            Assert.AreEqual(foundUser.RegisteredDate, userDetails.RegisteredDate);
            Assert.AreEqual(foundUser.UserName, userDetails.Username);


            Assert.IsTrue(userDetails.IsPersonnel);
            Assert.IsFalse(userDetails.IsAdmin);
            Assert.IsFalse(userDetails.IsDoctor);
            Assert.IsFalse(userDetails.Is2FAEnabled);
            Assert.IsFalse(userDetails.IsEmailVerified);
        }
        public void ReturnView_WithUserDetails()
        {
            // Arrange
            var userServiceMock   = new Mock <IUserService>();
            var fileConverterMock = new Mock <IFileConverter>();
            var mapperMock        = new Mock <IMapper>();

            var user = new User()
            {
                UserName  = "******",
                FirstName = "First name",
                LastName  = "Last name"
            };

            var userDetails = new UserDetailsViewModel()
            {
                FirstName = user.FirstName,
                LastName  = user.LastName
            };

            userServiceMock.Setup(us => us.GetUser(user.UserName)).Returns(user);
            mapperMock.Setup(m => m.Map <UserDetailsViewModel>(user)).Returns(userDetails);

            // Act
            var userController =
                new UserController(userServiceMock.Object, fileConverterMock.Object, mapperMock.Object);

            // Assert
            userController
            .WithCallTo(c => c.UserProfile(user.UserName))
            .ShouldRenderDefaultView()
            .WithModel <UserDetailsViewModel>(userDetails);
        }
Exemple #11
0
 // GET: Users/Details/5
 public ActionResult Details(int?id)
 {
     if (id == null || id == 0)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
     }
     try
     {
         using (var userService = new UserService())
         {
             var foundUser = userService.EagerDisconnectedService.FindByInclude(
                 x => x.Id == id.Value && x.Active, a => a.Address, p => p.PhoneNumber);
             if (!foundUser.Any())
             {
                 throw new Exception("No users found.");
             }
             var user = foundUser.First();
             var IdetailsViewModel = ModelMapper.MappFrom(user);
             var detailsViewModel  = new UserDetailsViewModel(IdetailsViewModel);
             return(View(detailsViewModel));
         }
     }
     catch (Exception e)
     {
         TempData["ResultMessage"] = e.Message;
         return(View("Error"));
     }
 }
        public ActionResult Edit(UserDetailsViewModel model)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var user        = UserManager.FindById(model.UserDetails.UserId);

            if (ModelState.IsValid || user != null)
            {
                if (model.RegisterViewModel.ResetPassword)
                {
                    UserManager.RemovePassword(user.Id);
                    UserManager.AddPassword(user.Id, "User@123");
                }

                var curRole  = db.UserRoles.Where(n => n.UserId == user.Id).FirstOrDefault();
                var rolename = roleManager.FindById(model.RoleId);


                if (curRole.RoleId != model.RoleId)
                {
                    UserManager.RemoveFromRole(user.Id, curRole.RoleId);
                }

                var userInRole = UserManager.IsInRole(user.Id, rolename.Name);
                if (!userInRole)
                {
                    UserManager.AddToRole(user.Id, rolename.Name);
                }
                model.UserDetails.NominatingBodyId = model.NominatingBodyId;
                model.UserDetails.PostalCodeId     = model.PostalCodeId;
                model.UserDetails.PFNumber         = model.RegisterViewModel.PFNumber;
                db.Entry(model.UserDetails).State  = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            UserDetails userDetails = db.UserDetails.Find(user.Id);

            if (userDetails == null)
            {
                return(HttpNotFound());
            }

            UserDetailsViewModel vm = new UserDetailsViewModel();

            vm.RoleId                     = db.UserRoles.Where(u => u.UserId == userDetails.UserId).FirstOrDefault().RoleId;
            vm.PostalCodeId               = userDetails.PostalCodeId;
            vm.NominatingBodyId           = userDetails.NominatingBodyId;
            vm.UserDetails                = userDetails;
            vm.RegisterViewModel          = new RegisterViewModel();
            vm.RegisterViewModel.UserName = user.UserName;
            vm.RegisterViewModel.Email    = user.Email;
            vm.RegisterViewModel.PFNumber = userDetails.PFNumber;

            ViewBag.RoleId           = new SelectList(db.Roles, "Id", "Name", vm.RoleId);
            ViewBag.NominatingBodyId = new SelectList(db.NominatingBodies, "Id", "Name", userDetails.NominatingBodyId);
            ViewBag.PostalCodeId     = new SelectList(db.PostalCodes, "Id", "Town", userDetails.PostalCodeId);
            return(View(vm));
        }
        // GET: UserDetails/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UserDetails userDetails = db.UserDetails.Find(id);

            if (userDetails == null)
            {
                return(HttpNotFound());
            }

            var user = db.Users.Where(u => u.Id == userDetails.UserId).FirstOrDefault();

            UserDetailsViewModel vm = new UserDetailsViewModel();

            vm.RoleId                     = db.UserRoles.Where(u => u.UserId == userDetails.UserId).FirstOrDefault().RoleId;
            vm.PostalCodeId               = userDetails.PostalCodeId;
            vm.NominatingBodyId           = userDetails.NominatingBodyId;
            vm.UserDetails                = userDetails;
            vm.RegisterViewModel          = new RegisterViewModel();
            vm.RegisterViewModel.UserName = user.UserName;
            vm.RegisterViewModel.Email    = user.Email;
            vm.RegisterViewModel.PFNumber = userDetails.PFNumber;

            ViewBag.RoleId           = new SelectList(db.Roles, "Id", "Name", vm.RoleId);
            ViewBag.NominatingBodyId = new SelectList(db.NominatingBodies, "Id", "Name", userDetails.NominatingBodyId);
            ViewBag.PostalCodeId     = new SelectList(db.PostalCodes, "Id", "Town", userDetails.PostalCodeId);
            return(View(vm));
        }
        private void UserSelectedEventFired(User userSelected)
        {
            IRegion region = this.regionManager.Regions["UserDetailsRegion"];

            if (region == null)
            {
                return;
            }
            UserDetailsView view = region.GetView("UserDetailsView") as UserDetailsView;

            if (view == null)
            {
                view = this.container.Resolve <UserDetailsView>();
                region.Add(view, "UserDetailsView");
            }
            else
            {
                region.Activate(view);
            }
            // Set the current employee property on the view model.
            UserDetailsViewModel viewModel = view.DataContext as UserDetailsViewModel;

            if (viewModel != null)
            {
                viewModel.CurrentUser = userSelected;
            }
        }
        // GET: Users/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            t__users t__user = db.t__users.Find(id);
            List <vl_HRC_HBC_HOLIDAY_DEPARTMENT_ROUTING> routingsList = db.vl_HRC_HBC_HOLIDAY_DEPARTMENT_ROUTING.Where(x => x.user_id == id).ToList();

            foreach (vl_HRC_HBC_HOLIDAY_DEPARTMENT_ROUTING item in routingsList)
            {
                item.person_in_charge_name = db.t__users.Find(item.person_in_charge_id).user_name;
            }

            List <vl_HRC_HBC_ASSIGNED_HOLIDAYS> holydaysList = db.vl_HRC_HBC_ASSIGNED_HOLIDAYS.Where(x => x.id == id).ToList();

            if (t__user == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new UserDetailsViewModel {
                User = t__user, routingsList = routingsList, holidaysList = holydaysList
            };

            return(View(viewModel));
        }
Exemple #16
0
        public async Task Details_ValidUserTwo2FA_Success()
        {
            string USER_ID = Guid.NewGuid().ToString();

            await dbContext.Users.AddAsync(new User("TestName", "TestUserName", "*****@*****.**", DateTime.Now) { Id = USER_ID, TwoFactorEnabled = true });

            await dbContext.SaveChangesAsync();

            var service = new AdminUserService(dbContext, userManager, roleManager, signInManager, new Mock <IServerNewsService>().Object);

            UserDetailsViewModel userDetails = await service.DetailsAsync(USER_ID);

            User foundUser = await dbContext.Users.FindAsync(USER_ID);

            Assert.IsNotNull(userDetails);

            Assert.AreEqual(foundUser.BirthDate, userDetails.BirthDate);
            Assert.AreEqual(foundUser.Email, userDetails.Email);
            Assert.AreEqual(foundUser.FullName, userDetails.FullName);
            Assert.AreEqual(foundUser.PhoneNumber, userDetails.PhoneNumber);
            Assert.AreEqual(foundUser.Qualification, userDetails.Qualification);
            Assert.AreEqual(foundUser.RegisteredDate, userDetails.RegisteredDate);
            Assert.AreEqual(foundUser.UserName, userDetails.Username);

            Assert.IsFalse(userDetails.IsPersonnel);
            Assert.IsFalse(userDetails.IsAdmin);
            Assert.IsFalse(userDetails.IsDoctor);
            Assert.IsTrue(userDetails.Is2FAEnabled);
            Assert.IsFalse(userDetails.IsEmailVerified);
        }
        public async Task <IActionResult> UserDetails()
        {
            var header = this.Request.Headers["sec-fetch-site"];

            if (header == "none")
            {
                return(RedirectToAction("Index", "Advertisement"));
            }
            User currentUser = await signInManager.UserManager.GetUserAsync(this.User);

            UserDetailsViewModel model = new UserDetailsViewModel()
            {
                Email       = currentUser.Email,
                Firstname   = currentUser.Firstname,
                Lastname    = currentUser.Lastname,
                Address     = currentUser.Address,
                Nationality = currentUser.Nationality,
                Birthdate   = currentUser.Birthdate,
                Sex         = currentUser.Sex,
                selectList  = new List <SelectListItem>
                {
                    new SelectListItem {
                        Text = "Male", Value = "Male"
                    },
                    new SelectListItem {
                        Text = "Female", Value = "Female"
                    }
                }
            };

            return(PartialView("_UserDetails", model));
        }
        public async Task <UserDetailsViewModel> GetUserDetailsAsync(ClaimsPrincipal user)
        {
            UserDetailsViewModel viewModel = null;

            var currentUser = await this.userManager.GetUserAsync(user);

            if (currentUser == null)
            {
                this.logger.LogWarning(ErrorMessages.UnableToLoadUser);
                throw new ApplicationException(ErrorMessages.UnableToLoadUser);
            }

            try
            {
                viewModel = this.mapper.Map <UserDetailsViewModel>(currentUser);

                if (currentUser.Picture != null && currentUser.Picture.Length <= NumericConstants.PictureSizeLimit)
                {
                    if (currentUser.PasswordHash == null)
                    {
                        viewModel.Picture = Encoding.ASCII.GetString(currentUser.Picture);
                    }
                    else
                    {
                        viewModel.Picture = Convert.ToBase64String(currentUser.Picture);
                    }
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }

            return(viewModel);
        }
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index"));
            }


            User user = userRepo.GetById(id.Value);

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

            UserDetailsViewModel userDetail = new UserDetailsViewModel()
            {
                Id        = user.Id,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Username  = user.Username,
                Email     = user.Email
            };

            if (user.ImageName != null)
            {
                userDetail.ImageName = user.ImageName;
            }

            return(View(userDetail));
        }
Exemple #20
0
        public async Task <IActionResult> EditUser([FromForm] UserDetailsViewModel userDetailsView)
        {
            if (userDetailsView == null)
            {
                throw new ArgumentNullException(nameof(userDetailsView));
            }

            var userDetailsDto = userDetailsView.MapToUserFullDetailsDtoDto();
            var result         = await _userAdminSvc.UpdateUserDetailsAsync(userDetailsDto).ConfigureAwait(false);

            string message;

            switch (result)
            {
            case ServiceResultStatusCode.Success:
                message = $"User details successfully updated. \"Username\"={userDetailsDto.Username}, \"UserId\"={userDetailsDto.UserId}, \"ServiceResultStatusCode\"={result}";
                _logger.LogInformation(message);
                Alert(message, AlertType.success);
                return(RedirectToAction("Index"));

            default:
                message = $"An error occurred. Could not update user details. \"Username\"={userDetailsDto.Username}, \"UserId\"={userDetailsDto.UserId}, \"ServiceResultStatusCode\"={result}";
                _logger.LogInformation(message);
                Alert(message, AlertType.danger);
                return(RedirectToAction("Index"));
            }
        }
Exemple #21
0
        public async Task <IActionResult> UserDetails(string id)
        {
            var user = await usersRepository.FindFullUserByIdAsync(id);

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

            var events = await CreateUserDetailsEventViewModels(user.UserEvents);

            var currentSemester = await semestersRepository.FindCurrentSemesterAsync();

            var viewModel = new UserDetailsViewModel()
            {
                UserId        = id,
                UserName      = user.UserName,
                Position      = user.Position,
                Parameters    = CreateUserDetailsParameterViewModels(user.ParameterValues),
                Achievements  = CreateUserDetailsAchievementViewModels(user.UserAchievements),
                CurrentEvents = events.Where(e => e.SemesterId == currentSemester?.Id),
                OldEvents     = events.Where(e => e.SemesterId != currentSemester?.Id),
            };

            return(View(viewModel));
        }
Exemple #22
0
        public ActionResult Dashboard()
        {
            #region retrieving the claim values for the currently logged in user (to retrieve him using his/her id)
            ClaimsIdentity currentIdentity = User.Identity as ClaimsIdentity;
            string         modelfullname   = (currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)).ToString();      //not used
            string         modelusername   = (currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)).ToString(); //not used
            var            modelid         = int.Parse((currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)).Value);
            #endregion

            UserDetailsViewModel model = null;

            using (PhotoExplorerEntities cx = new PhotoExplorerEntities())
            {
                UserEntityModel entity = cx.Users.FirstOrDefault(u => u.Id == modelid);

                #region mapping necessary properties from entitymodel to the viewmodel
                model = new UserDetailsViewModel()
                {
                    Id             = entity.Id,
                    Username       = entity.Username,
                    Fullname       = entity.Fullname,
                    Albums         = entity.Albums,
                    DateRegistered = entity.DateRegistered,
                    Email          = entity.Email,
                };
                #endregion
            }

            return(View(model));
        }
Exemple #23
0
 //
 // GET: /Details/
 public ActionResult Details(string id)
 {
     UserDetailsViewModel vm = new UserDetailsViewModel();
     vm.User = Repository.Instance.GetUserByUserName(id);
     vm.Posts = Repository.Instance.GetLatestPostForUser(vm.User.ID, 5);
     return View(vm);
 }
Exemple #24
0
        public void TestGetPhoneNumber_ShouldReturnCorrectly(string email, string address, string phoneNumber,
                                                             string username, string id)
        {
            var viewModel = new UserDetailsViewModel(email, address, phoneNumber, username, id);

            Assert.AreEqual(phoneNumber, viewModel.PhoneNumber);
        }
        public ActionResult Index()
        {
            #region retrieving the claim values for the currently logged in user (to retrieve him using his/her id)
            ClaimsIdentity currentIdentity = User.Identity as ClaimsIdentity;
            string         modelfullname   = (currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)).ToString();      //not used
            string         modelusername   = (currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)).ToString(); //not used
            var            modelid         = int.Parse((currentIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)).Value);
            #endregion


            UserDetailsViewModel model = EFMapper.EntityToModel(userRepo.GetUser(modelid));

            #region notused
            //UserDetailsViewModel model = null;

            //using (PhotoExplorerEntities cx = new PhotoExplorerEntities())
            //{
            //    UserEntityModel entity = cx.Users.FirstOrDefault(u => u.Id == modelid);

            //    #region mapping necessary properties from entitymodel to the viewmodel
            //    model = new UserDetailsViewModel()
            //    {
            //        Id = entity.Id,
            //        Username = entity.Username,
            //        Fullname = entity.Fullname,
            //        Albums = entity.Albums,
            //        DateRegistered = entity.DateRegistered,
            //        Email = entity.Email,
            //    };
            //    #endregion
            //}
            #endregion

            return(View(model));
        }
Exemple #26
0
        public ActionResult Detail(int id)
        {
            string        query  = string.Format("SELECT [Username], [Created], [Type] FROM [User] WHERE [Id] = {0}", id);
            SqlCommand    cmd    = new SqlCommand(query, Database.db);
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                UserDetailsViewModel entity = new UserDetailsViewModel
                {
                    Id       = id,
                    Username = reader.GetString(0),
                    Created  = reader.GetDateTime(1),
                    Type     = reader.GetInt32(2),
                };
                switch (entity.Type)
                {
                default:
                    break;

                case 0:
                    entity.TypeText = "Uživatel";
                    break;

                case 1:
                    entity.TypeText = "Moderátor";
                    break;

                case 2:
                    entity.TypeText = "Administrátor";
                    break;
                }
                entity.Ratings = new List <Rating>();
                query          = string.Format("SELECT rt.[Rating], rt.[MovieId], mo.[Title] FROM [Rating] rt, [Movie] mo WHERE mo.[Id] = rt.[MovieId] AND rt.[UserId] = {0}", id);
                cmd            = new SqlCommand(query, Database.db);
                reader         = cmd.ExecuteReader();
                while (reader.Read())
                {
                    entity.Ratings.Add(new Rating
                    {
                        Value     = reader.GetInt32(0),
                        MovieId   = reader.GetInt32(1),
                        MovieName = reader.GetString(2),
                    });
                }
                query  = string.Format("SELECT [Id] FROM [Comment] WHERE [UserId] = {0}", id);
                cmd    = new SqlCommand(query, Database.db);
                reader = cmd.ExecuteReader();
                int i = 0;
                while (reader.Read())
                {
                    i++;
                }
                entity.Comments = i;
                return(View(entity));
            }
            return(View(null));
        }
        public async Task <IActionResult> Details(UserDetailsViewModel model)
        {
            model._context         = _context;
            model._securityOptions = _securityOptions;
            model._emailService    = _emailService;
            model._user            = User;

            try
            {
                if (ModelState.IsValid)
                {
                    if (model.UserRoles.Any(x => x.Selected == true) == false)
                    {
                        ViewBag.Error = "At least one user role must be specified";
                    }
                    else if (string.IsNullOrEmpty(model.EmailAddress))
                    {
                        ViewBag.Error = "Email address must be specified";
                    }
                    else
                    {
                        Guid userID = Guid.Empty;

                        userID = await model.Save();

                        if (userID != Guid.Empty)
                        {
                            if (!string.IsNullOrEmpty(model._tmpPassword))
                            {
                                TempData["tmpPassword"] = model._tmpPassword;
                            }
                            else
                            {
                                TempData["tmpPassword"] = null;
                            }
                            return(RedirectToAction("Details", new { ID = userID, Success = true }));
                        }
                        else
                        {
                            ViewBag.Error = model.errorMessage;
                        }
                    }
                }
                else
                {
                    ViewBag.Error = "Please make sure the required fields are added including the login type.";
                }
            }
            catch (Exception ex)
            {
                HelperFunctions.Log(_context, PublicEnums.LogLevel.LEVEL_EXCEPTION, "Controllers.UsersController.Details", ex.Message, User, ex);
                ViewBag.Error = "An error occurred. Please try again later.";
            }
            finally
            {
                await model.PopulateLists();
            }
            return(View(model));
        }
Exemple #28
0
 public UserDetailsView(UserDetailsViewModel viewModel)
 {
     InitializeComponent();
     this.DataContext = viewModel;
     RegionContext.GetObservableContext(this).PropertyChanged +=
         (s, e) => viewModel.CurrentUser =
             RegionContext.GetObservableContext(this).Value as User;
 }
        public async Task UpdateUserProfile(UserDetailsViewModel user)
        {
            var _user = await _userRepository.GetByApplicationUserId(user.ID, user.ApplicationUserId);

            _user = user.ConvertToUser(_user);

            await _userRepository.UpdateUserProfile(_user);
        }
Exemple #30
0
        public async Task <IActionResult> Profile()
        {
            UserDetailsViewModel userDetailsViewModel = (await this.userService
                                                         .GetByUserNameAsync(User.Identity.Name))
                                                        .To <UserDetailsViewModel>();

            return(View(userDetailsViewModel));
        }
        //
        // GET: /Details/
        public ActionResult Details(string id)
        {
            UserDetailsViewModel vm = new UserDetailsViewModel();

            vm.User  = Repository.Instance.GetUserByUserName(id);
            vm.Posts = Repository.Instance.GetLatestPostForUser(vm.User.ID, 5);
            return(View(vm));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
        /// </summary>
        /// <param name="modalDialogProvider">The modal dialog service.</param>
        /// <param name="serviceFactory">The service factory.</param>
        public UsersViewModel(IMainViewModel mainViewModel, IModalDialogProvider modalDialogProvider, IServiceFactory serviceFactory)
            : base(mainViewModel, modalDialogProvider, serviceFactory)
        {
            UserDetailsViewModel = new UserDetailsViewModel(MainViewModel, ModalDialogProvider, ServiceFactory);
              UserListViewModel = new UserListViewModel(MainViewModel, UserDetailsViewModel, ModalDialogProvider, ServiceFactory);

              RoleDetailsViewModel = new RoleDetailsViewModel(MainViewModel, ModalDialogProvider, ServiceFactory);
              RoleListViewModel = new RoleListViewModel(MainViewModel, RoleDetailsViewModel, ModalDialogProvider, ServiceFactory);
        }
 public async Task<UserDetailsViewModel> GetUserDetailsViewModel(string id)
 {
     var user = await _userManager.FindByIdAsync(id);
     var detailsModel = new UserDetailsViewModel() { User = user, Lockout = new LockoutViewModel() };
     var isLocked = await _userManager.IsLockedOutAsync(user.Id);
     detailsModel.Lockout.Status = isLocked ? LockoutStatus.Locked : LockoutStatus.Unlocked;
     if (detailsModel.Lockout.Status == LockoutStatus.Locked)
     {
         detailsModel.Lockout.LockoutEndDate = (await _userManager.GetLockoutEndDateAsync(user.Id)).DateTime;
     }
     return detailsModel;
 }
Exemple #34
0
        public ActionResult EditProfile(UserDetailsViewModel user)
        {
            var userId = this.User.Identity.GetUserId();
            var userToUpdate = this.users.GetById(userId);
            userToUpdate.FirstName = user.FirstName;
            userToUpdate.LastName = user.LastName;
            userToUpdate.UserName = user.UserName;
            userToUpdate.Age = user.Age;
            this.users.Update(userToUpdate);

            return this.Redirect("/Users/Details");
        }
        //
        // GET: /Users/Details/5
        public async Task<ActionResult> Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var user = await UserManager.FindByIdAsync(id);

            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
            var detailsModel = new UserDetailsViewModel() {User = user, Lockout = new LockoutViewModel()};
            var isLocked = await UserManager.IsLockedOutAsync(user.Id);
            detailsModel.Lockout.Status = isLocked ? LockoutStatus.Locked : LockoutStatus.Unlocked;
            if (detailsModel.Lockout.Status == LockoutStatus.Locked)
            {
                detailsModel.Lockout.LockoutEndDate = (await UserManager.GetLockoutEndDateAsync(user.Id)).DateTime;
            }

            return View(detailsModel);
        }
Exemple #36
0
        public ActionResult Index()
        {
            var currentUser = this.users.GetUser(this.User.Identity.Name);
            var viewModel = new UserDetailsViewModel()
            {
                FirstName = currentUser.FirstName,
                LastName = currentUser.LastName,
                Avatar = currentUser.Avatar,
                About = currentUser.About
            };

            return this.View(viewModel);
        }
        public async Task<ActionResult> UserDetails(string id, int? messageId)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ApplicationUser user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }

            var vm = new UserDetailsViewModel
            {
                Id = user.Id,
                FullName = user.FullName,
                Address1 = user.Address1,
                City = user.City,
                ProvCode = user.ProvCode,
                CountryCode = user.CountryCode,
                PostalCode = user.PostalCode,
                Email = user.Email,
                ComputerInfo = user.ComputerInfo,
                MessageId = messageId ?? 0,
                UserName = user.UserName,
                UtcOffSet = user.UtcOffSet,
                Courses = _context.Courses.OrderBy(c => c.Title),
                CourseId = _context.Courses.OrderBy(c => c.Title).First().Id,
                Orders = _context.Orders.Where(t => t.UserName == user.UserName)
                   .OrderByDescending(t => t.OrderId)
                   .Select(t => new OrderListViewModel()
                   {
                       OrderId = t.OrderId,
                       OrderDate = t.OrderDate,
                       Username = t.UserName,
                       Total = t.Total,
                       PaymentType = t.PaymentType,
                       ConfirmationCode = t.ConfirmationCode

                   }),
                Enrollments = _context.Enrollments.Include("Course").Where(e => e.ApplicationUserId == user.Id)
                .Select(e => new EnrollmentViewModel()
                {
                    Id = e.Id,
                    CourseName = e.Course.Title,
                    PassedDate = e.PassedDate,
                    Score = e.Score

                })
            };


            if (messageId > 0)
            {
                var message = _context.Messages.Find(messageId);

                vm.Subject = "Re: " + message.Subject;
                vm.FromAddress = message.FromAddress;
                vm.IsResponseMessage = true;
                vm.Body = message.Body;
            }
            else
            {
                vm.FromAddress = user.Email;
            }

            return View(vm);
        }
        private void ResetOriginalMessageToNotWaiting(UserDetailsViewModel vm)
        {
            var originalMessage = _context.Messages.Find(vm.MessageId);
            originalMessage.Waiting = false;
            _context.Messages.Attach(originalMessage);
            _context.Entry(originalMessage).State = EntityState.Modified;

            _context.SaveChanges();
        }
        private async Task<int> SaveResponseToDataBase(UserDetailsViewModel vm)
        {
            var message = new Message
            {
                Subject = vm.Subject,
                Body = vm.Response,
                MessageDate = DateTime.UtcNow,
                FromAddress = _responseFromAddress,
                AdminUserName = _currentUser.User.UserName,
                RespondId = vm.MessageId,
                Incoming = false,
                Waiting = false

            };

            _context.Messages.Add(message);
            return await _context.SaveChangesAsync();
        }
        private void SendEmailResponse(UserDetailsViewModel vm)
        {

            var mailMessage = new MailMessage
            {
                Body = vm.Response + AppConstants.MessageToClientFooter,
                Subject = vm.Subject,
                From = new MailAddress(_responseFromAddress)
            };

            var toAddress = new MailAddress(vm.FromAddress);
            mailMessage.To.Add(toAddress);
            _emailService.SendAsync(mailMessage);
        }
        public async Task<ActionResult> UserDetails(UserDetailsViewModel vm, params string[] rolesSelectedOnView)
        {
            if (ModelState.IsValid)
            {

                var success = await SaveResponseToDataBase(vm);
                if (success == 1)
                    SendEmailResponse(vm);
                else
                {
                    ModelState.AddModelError("", "Did ");
                }
                if (vm.IsResponseMessage)
                { 
                    ResetOriginalMessageToNotWaiting(vm);
                }

                return RedirectToAction("Index", "Dashboard");
            }

            ModelState.AddModelError("", "Something failed.");
            return View(vm);
        }
        public ActionResult Update(string regAsTeacher = null)
        {
            var repository = RepositoryFactory.GetInstance(Session);
            try
            {
                ParseUser user = Session.GetLoggedInUser();
                ViewBag.IsAdmin = (user != null && !string.IsNullOrEmpty(Session.GetImpersonatingUserName())) || Session.GetLoggedInUserRoleName() == RoleNames.ADMINISTRATORS;

                if (user == null) return RedirectToAction("Login");

                var worldContentTypeRetriever = new WorldContentTypeRetriver(HttpContext, repository);
                var model = new UserDetailsViewModel();
                model.IsTeacher = user.GetBool("registerAsTeacher");

                if (!model.IsTeacher && regAsTeacher == null)
                {
                    return RedirectToAction("UpdateStudent");
                }

                user["registerAsTeacher"] = true;
                var residences = repository.FindAllResidences();
                var sugTavs = repository.FindSugTav();
                var sugTagmuls = repository.FindSugTagmul();
                var sugNirut = repository.FindSugNirut();
                var sugMehira = repository.FindSugMehira();
                var sugLanguages = repository.FindLanguages();
                var sugLessonPublishingStatus = repository.FindUserPublishingStatus();

                var userResidence = residences.FirstOrDefault(obj => obj.Name.Equals(user.GetString("residenceCountry")));
                var deviceTypes = repository.FindDeviceTypes();
                var contentTypes = worldContentTypeRetriever.GetContentTypes(user, Session.GetLoggedInUserRoleName());

                var currencies = repository.FindCurrencies();
                var uiLanguages = repository.FindInterfaceLanguages();
                var userStatuses = repository.FindUserStatus();
                IEnumerable<UserGroup> groups = (repository.FindGroups()).ToArray();
                IEnumerable<UserGroup> subGroups = (repository.FindSubGroups()).ToArray();
                var sugOseks = repository.FindAllSugOsek();

                model.SugTav = sugTavs;
                model.SaleStatus = sugMehira;
                model.SugTagmuls = sugTagmuls.ConvertToSugTagmul(userResidence != null && userResidence.Israel);
                model.SugNiruts = sugNirut;
                model.SugMehiras = sugMehira;
                model.SugLanguages = sugLanguages;
                model.SugLessonPublishingStatus = sugLessonPublishingStatus;

                model.Groups = groups;
                model.SubGroups = subGroups;
                model.DeviceTypes = deviceTypes;
                model.UserPrefferences.ContentTypes = contentTypes;
                model.UserPrefferences.Currencies = currencies;
                model.UserPrefferences.Languages = uiLanguages;
                model.UserStatusValues = userStatuses;
                model.SugOseks = sugOseks;

                model.SelectedSugTav = user.GetPointerObjectId("sugTav");
                model.Residence = user.GetPointerObjectId("residence");
                model.SelectedSugTagmul = user.GetPointerObjectId("sugTagmul");
                model.SelectedSugNirut = user.GetPointerObjectId("sugNirut");
                model.SelectedSugMehiras = user.GetPointerObjectId("sugMehira");
                model.TeachingLanguage1 = user.GetPointerObjectId("teachingLanguage1");
                model.TeachingLanguage2 = user.GetPointerObjectId("teachingLanguage2");
                model.TeachingLanguage3 = user.GetPointerObjectId("teachingLanguage3");
                model.UserPrefferences.SelectedContentType = user.GetPointerObjectId("contentType");
                model.UserPrefferences.SelectedCurrency = user.GetPointerObjectId("currency");
                model.UserPrefferences.SelectedLanguage = user.GetPointerObjectId("interfaceLanguage");
                model.SelectedSugOsek = user.GetPointerObjectId("sugOsek");
                //   model.SelectedUserStatus = currentUserStatus.ObjectId;

                model.FirstName = user.GetString("firstName_he_il").Trim();
                model.LastName = user.GetString("lastName_he_il").Trim();
                model.GovId = user.GetString("govId");
                model.FirstNameEnglish = user.GetString("firstName_en_us").Trim();
                model.LastNameEnglish = user.GetString("lastName_en_us").Trim();
                model.Email = user.GetString("email");
                model.Phone = user.GetString("phoneNumber");
                model.MailRecipientAddress = user.GetString("mailRecipientAddress");
                model.OtherTeachingLocation = user.GetString("otherTeachingLocation");
                model.TeachesFromYear = user.GetString("teachesFromYear");
                model.TeacherHomePage = user.GetString("teacherHomePage");
                model.CityOfResidence = user.GetString("cityOfResidence_he_il");
                model.CityOfResidence_en_us = user.GetString("cityOfResidence_en_us");
                model.SelectedSaleStatus = user.GetString("saleStatus");
                model.TeacherDescription = user.GetString("teacherDescription");
                model.TeacherDescriptionEnglish = user.GetString("teacherDescription_en_us");

                model.SelectedDeviceType = user.GetPointerObjectId("deviceType");
                model.SelectedDeviceType = model.DeviceTypes.FirstOrDefault(deviceType => deviceType.Key.Split(new char[] { '|' })[0] == model.SelectedDeviceType).Key;

                model.PaymentDetails.AccountNumber = user.GetString("bankAccountNumber");
                model.PaymentDetails.IRSNumber = user.GetString("irsFileNumber");
                model.PaymentDetails.VATNumber = user.GetString("vatFileNumber");
                model.PaymentDetails.BankName = user.GetString("bankName");
                model.PaymentDetails.BankBranch = user.GetString("bankBranch");
                model.PaymentDetails.BeneficiaryFulllName = user.GetString("beneficiaryFulllName");
                model.PaymentDetails.PayPalEmail = user.GetString("paypalEmail");

                model.LessonCost = user.GetNullableInt("lessonCost");
                model.ExtraFeeForStudentHouse = user.GetNullableInt("extraFeeForStudentHouse");

                model.Ashkenaz = user.GetBool("isAshkenazVersion");
                model.Morocco = user.GetBool("isMorocoVersion");
                model.Sefaradi = user.GetBool("isSepharadiVersion");
                model.Yemen = user.GetBool("isYemenVersion");
                model.OtherTeachingNosah = user.GetBool("isOtherTeachingNosah");

                model.TeachesAtHome = user.GetBool("teachesAtHome");
                model.TeachesAtStudentHouse = user.GetBool("teachesAtStudentHome");
                model.ShowContanctDetails = user.GetBool("showContactDetails");

                var userAdminData = user.GetPointerObject<UserAdminData>("adminData");
                var agentUser = userAdminData.GetPointerObject<ParseUser>("agent");
                if (userAdminData != null)
                {
                    model.AdminData.TCPTeacherCommission = userAdminData.TcpTeacherCommission.ToString("n2");
                    model.AdminData.AgentUserName = agentUser != null ? agentUser.Username : string.Empty;
                    model.AdminData.ACPAgentCommission = userAdminData.AcpTeacherCommission.ToString("n2");
                    model.AdminData.STRCommissionRatio = userAdminData.StrCommissionRatio;
                    model.AdminData.UserPublishingStatus = userAdminData.GetPointerObjectId("userPublishingStatus");
                    model.AdminData.UserStatus = userAdminData.GetPointerObjectId("userStatus");

                    model.AdminData.LockCountry = userAdminData.LockCountry;
                    model.AdminData.LockCurrency = userAdminData.LockCurrency;
                    model.AdminData.LockSugNirut = userAdminData.LockSugNirut;
                    model.AdminData.LockSugOsek = userAdminData.LockSugOsek;
                    model.AdminData.OriginalTaxPercent = userAdminData.OriginalTaxPercent;
                    model.AdminData.AdminRemarks = userAdminData.AdminRemarks;

                    if (userAdminData.Group != null)
                    {
                        var savedSelectedGroup = userAdminData.Group.ObjectId;
                        var selectedSubGroup = subGroups.SingleOrDefault(o => o.ObjectId == savedSelectedGroup);
                        var selectedGroup = groups.SingleOrDefault(o => o.ObjectId == savedSelectedGroup);
                        if (selectedSubGroup != null)
                        {
                            selectedGroup = groups.Single(o => o.ObjectId == selectedSubGroup.Parent.ObjectId);
                        }

                        model.AdminData.Group = selectedGroup != null ? selectedGroup.ObjectId : string.Empty;
                        model.AdminData.SubGroup = selectedSubGroup != null ? selectedSubGroup.ObjectId : string.Empty;
                    }
                }

                model.PictureUrl = user.Keys.Contains("picture") ? ((ParseFile)user["picture"]).Url.ToString() : MentorSystem.DEFAULT_PROFILE_IMAGE;
                var residenceTitle = residences.FirstOrDefault(residence => residence.Id == model.Residence);
                if (residenceTitle != null)
                    model.ResidenceTitle = !string.IsNullOrEmpty(model.Residence) ? residenceTitle.Name : string.Empty;

                var residenceCountry = GetResidenceCountry(residences, model.Residence);

                model.ResidenceCountry = residenceCountry.Name;
 
                ViewBag.DeviceUnSupportedText = Strings.GetLocalizedString(Strings.UnSupportedDevice);
                model.Messages.CountryLocked = Strings.GetLocalizedString(Strings.CountryLocked);
                model.Messages.SugOsekLocked = Strings.GetLocalizedString(Strings.SugOsekLocked);
                model.Messages.CurrencyLocked = Strings.GetLocalizedString(Strings.CurrencyLocked);
                model.Messages.SugNirutLocked = Strings.GetLocalizedString(Strings.SugNirutLocked);
                model.Messages.AgentNotFound = Strings.GetLocalizedString(Strings.AgentNotFound);
                return View("Update", model);
            }
            finally 
            {
                
                repository.Dispose();
            }
           
        }
        public async Task<ActionResult> Update(UserDetailsViewModel model)
        {
            Exception ex = null;
            var repository = RepositoryFactory.GetInstance(Session);
            try
            {
                var residences = repository.FindAllResidences();
                model.FirstName = model.FirstName.Trim();
                model.LastName = model.LastName.Trim();
                model.FirstNameEnglish = model.FirstNameEnglish.Trim();
                model.LastNameEnglish = model.LastNameEnglish.Trim();
                model.ResidenceCountryId = GetResidenceCountry(residences, model.Residence).Id;
                HttpContext.Request.Cookies.ClearCurrencyCookie();
                await new MyMentorUserManager(repository, Session).Update(model, HttpContext);
                ViewBag.UpdateSuccess = true;
                ViewBag.ScriptToRun = model.ScriptToRun;
                ViewBag.UpdateSuccess = model.UpdateSuccess;
            }
            catch (Exception e)
            {
                mLogger.Log(LogLevel.Error, e);
                ViewBag.UpdateSuccess = false;
                ex = e;
            }
            finally
            {
                repository.Dispose();
            }
            if (ex != null)
            {
                await ParseLogger.Log("update", ex);
            }

            if (ViewBag.UpdateSuccess != null)
            {
                ViewBag.UpdateStudentMessage = model.UpdateSuccess.Value ?
                     Strings.GetLocalizedString(Strings.UpdateStudentSuccess) :
                     Strings.GetLocalizedString(Strings.UpdateStudentFail);
            }

            SetUserPrefferences(model.UserPrefferences);
            return  Update();
        }