Ejemplo n.º 1
0
        public async Task <ActionResult> UpdateProfile(UserProfileVM userProfileVM, string updateType)
        {
            Enum.TryParse(updateType, out UserProfileUpdateType updateTypeEnum);

            if (updateTypeEnum == UserProfileUpdateType.Unknown)
            {
                ModelState.AddModelError("updateType", "Invalid update type provided. Please check the request URL parameter.");
                return(View("Index", userProfileVM));
            }

            if (userService.GetUserId() != userProfileVM.UserId)
            {
                ModelState.AddModelError("UserId", "You cannot save the profile of another user.");
                return(View("Index", userProfileVM));
            }

            var existingProfile = await userProfileUOW.UserProfiles.GetUserProfileAsync(userService.GetUserId());

            UpdateProfileProperties(userProfileVM, existingProfile, updateTypeEnum);

            userProfileUOW.UserProfiles.InsertOrUpdate(existingProfile);

            await userProfileUOW.CompleteAsync();

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 2
0
        public JsonResult SearchUserListByDetails(int iGenderID = 0, int iStatusID = 0, int iCityID = 0)
        {
            var userProfileList = db.UserProfiles.ToList();
            var userList        = (from context in db.UserRegistrations
                                   join userproifle in db.UserProfiles on context.UserID equals userproifle.UserID
                                   where iGenderID > 0 ? userproifle.Gender.Value == iGenderID : false &&
                                   iStatusID > 0 ? userproifle.MritalStatus.Value == iStatusID : false &&
                                   iCityID > 0 ? userproifle.DistrictID.Value == iCityID : false
                                   select(new UserProfileVM
            {
                FirstName = context.FirstName,
                MiddleName = context.MiddleName,
                LastName = context.LastName,
                MyAppID = userproifle.MyAppID,
                Email = context.Email,
                BirthYear = userproifle.DateOfBirth.HasValue ? userproifle.DateOfBirth.Value.Year : 0,
                BirthPlace = userproifle.BirthPlace,
                BirthTime = userproifle.BirthTime,
                Gotra = userproifle.Gotra,
                EducationDetail = userproifle.EducationDetail,
                Mobile = context.Mobile,
                ImagePath = userproifle.ImagePath,
                UserID = userproifle.UserID
            })).ToList();



            UserProfileVM objUserProfileVM = new UserProfileVM();

            string vResult = RenderPartialViewToString("~/Views/SearchUser/ucSearchResultList.cshtml", userList);

            return(Json(vResult, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 3
0
 public ManageAlbumVM(UserProfileVM userProfileVM, AlbumVM albumVM, List <PictureVM> picturesVM)
 {
     IsUsersAlbum  = userProfileVM.Id == albumVM.UserId;
     UserProfileVM = userProfileVM;
     AlbumVM       = albumVM;
     PicturesVM    = picturesVM;
 }
Ejemplo n.º 4
0
        public void Promote(int userProfileID)
        {
            UserProfileVM user = UserProfile.GetUserProfileByID(userProfileID);

            user.RoleID -= 1;
            UserProfile.UpdateUserProfile(user);
        }
Ejemplo n.º 5
0
        public ActionResult UserProfile(UserProfileVM model)
        {
            bool userNameIsChanged = false;

            if (!ModelState.IsValid)
            {
                return(View("UserProfile", model));
            }

            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                if (!model.Password.Equals(model.ConfirmPassword))
                {
                    ModelState.AddModelError("", "Passwords do not match.");
                    return(View("UserProfile", model));
                }
            }

            using (Db db = new Db())
            {
                string userName = User.Identity.Name;
                if (userName != model.Username)
                {
                    userName          = model.Username;
                    userNameIsChanged = true;
                }

                if (db.Users.Where(x => x.Id != model.Id).Any(x => x.Username == userName))
                {
                    ModelState.AddModelError("", $"Username {model.Username} already exist.");
                    model.Username = "";
                    return(View("UserProfile", model));
                }

                UserDTO dto = db.Users.Find(model.Id);

                dto.FirstName   = model.FirstName;
                dto.LastName    = model.LastName;
                dto.EmailAdress = model.EmailAdress;
                dto.Username    = model.Username;

                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    dto.Password = model.Password;
                }

                db.SaveChanges();
            }

            TempData["SM"] = "You have edited your profile!";

            if (!userNameIsChanged)
            {
                return(View("UserProfile", model));
            }
            else
            {
                return(RedirectToAction("Logout"));
            }
        }
Ejemplo n.º 6
0
        public void UpdateUserProfile(UserProfileVM userProfile)
        {
            HashHelper hashHelper = new HashHelper();

            userProfile.Password = hashHelper.GetHash(userProfile.Password);
            UserProfile.UpdateUserProfile(userProfile);
        }
Ejemplo n.º 7
0
        public ActionResult Order()
        {
            //Получение имени пользователя
            string userName = User.Identity.Name;

            //Объявление модели
            UserProfileVM model;

            if (userName != "")
            {
                using (Db db = new Db())
                {
                    //Получение пользователя
                    UserDTO dto = db.Users.FirstOrDefault(x => x.Username == userName);

                    //Инициализируем модель данными
                    model = new UserProfileVM(dto);
                }
            }
            else
            {
                //Оставляем модель пустой
                model = new UserProfileVM();

                //Установка сообщения в Tempdata
                TempData["M"] = "Для оформления заказа войдите в учетную запись!";
            }

            //Возврат модели в представление
            return(View("Order", model));
        }
Ejemplo n.º 8
0
        public ActionResult UserProfile(string id_encrypted)
        {
            UserProfileVM profile   = new UserProfileVM();
            int           userId    = Convert.ToInt32(id_encrypted);// (int)SessionManagement.LoggedInUser.UserId;
            UserModel     userModel = userBusiness.GetUserByUserId(userId);

            Mapper.Map(userModel, profile);
            if (profile.Address.Street != null)
            {
                profile.AddressDetails = profile.Address.Street;
            }
            if (profile.Address.City != null)
            {
                profile.AddressDetails = profile.AddressDetails + (profile.AddressDetails != null ? (",") : ("")) + profile.Address.City;
            }
            if (profile.Address.Country.CountryName != null)
            {
                profile.AddressDetails = profile.AddressDetails + (profile.AddressDetails != null ? (",") : ("")) + profile.Address.Country.CountryName;
            }
            if (profile.Address.Zipcode != null)
            {
                profile.AddressDetails = profile.AddressDetails + (profile.AddressDetails != null ? (",") : ("")) + profile.Address.Zipcode;
            }
            ViewBag.UserID = userId;
            return(View(profile));
        }
Ejemplo n.º 9
0
 public ActionResult UserProfilePost(UserProfileVM userProfile)
 {
     if (!ModelState.IsValid)
     {
         return(View(userProfile));
     }
     try
     {
         var userData = TicketUserData.FromContext(HttpContext);
         var command  = new UpdateUserCommand
         {
             Email     = userProfile.Email,
             FirstName = userProfile.FirstName,
             LastName  = userProfile.LastName,
             Password  = userProfile.Password,
             Phone     = userProfile.Phone,
             UserId    = userData.UserId
         };
         pipelineService.HandleCommand(command);
     }
     catch (DomainException ex)
     {
         ModelState.AddModelError(string.Empty, ex);
         return(View(userProfile));
     }
     return(Redirect("~"));
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> Index()
        {
            ApplicationUser applicationUser = await _userManager.GetUserAsync(HttpContext.User);

            List <string> roles = (List <string>) await _userManager.GetRolesAsync(applicationUser);

            UserProfile currentUser = await _repository.GetUserByIdAsync(new Guid(applicationUser.Id));

            if (currentUser == null)
            {
                return(RedirectToAction("MakeNewProfile"));
            }
            List <Picture> pictures = await _repository.GetAllPicturesAsync();

            ProfilePictureVM profilePictureVM  = new ProfilePictureVM(currentUser.ProfilePicture);
            UserProfileVM    userProfileVM     = new UserProfileVM(currentUser);
            List <PictureVM> picturesToPresent = new List <PictureVM>();

            foreach (var item in pictures)
            {
                picturesToPresent.Add(new PictureVM(item));
            }

            // get all users
            List <UserProfileVM> userProfilesVM = await GetAllUsersVMAsync(currentUser.Id);

            //get following users
            List <UserProfileVM> followingUserProfilesVM = GetFollowingUsersVM(currentUser);

            MainVM indexViewModel = new MainVM("Newest Pictures", userProfileVM, picturesToPresent, userProfilesVM, followingUserProfilesVM);

            return(View("Index", indexViewModel));
        }
Ejemplo n.º 11
0
        public ActionResult UserProfile(UserProfileVM model)
        {
            bool isNameChanged = false;

            //validate model
            if (!ModelState.IsValid)
            {
                return(View("UserProfile", model));
            }

            //check password changes
            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                if (!(model.Password == model.ConfirmPassword))
                {
                    ModelState.AddModelError("", "Password do not match");
                    return(View("UserProfile", model));
                }
            }
            using (Db db = new Db()) {
                //get user name
                string userName = User.Identity.Name;

                if (userName != model.UserName)
                {
                    userName      = model.UserName;
                    isNameChanged = true;
                }
                //check to unique name if it needs
                if (db.Users.Where(x => x.Id != model.Id).Any(x => x.UserName == userName))
                {
                    ModelState.AddModelError("", $"User name {model.UserName} is already exist");
                    model.UserName = "";
                    return(View("UserProfile", model));
                }
                //change model
                UserDTO dto = db.Users.Find(model.Id);
                //save data
                dto.UserName     = model.UserName;
                dto.EmailAddress = model.EmailAddress;
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    dto.Password = model.Password;
                }
                db.SaveChanges();
            }

            //record to  TempData
            TempData["SM"] = "You profile was changed";
            //return VIew with model

            if (!isNameChanged)
            {
                return(View("UserProfile", model));
            }
            else
            {
                return(RedirectToAction("Logout"));
            }
        }
Ejemplo n.º 12
0
        private async Task <UserProfileVM> BuildUserProfile(string email)
        {
            var getFromSession = GetUserProfile();

            if (!string.IsNullOrEmpty(getFromSession.Name))
            {
                return(getFromSession);
            }

            var user = await _userManager.GetUser(email);

            var userProfile = new UserProfileVM
            {
                Name             = $"{user.FirstName} {user.Surname}",
                Email            = user.EmailAddress,
                PhoneNo          = user.PhoneNumber,
                IsApproved       = user.IsApproved,
                AccessArea       = user.AllowedAccessAreas,
                BooksNotReturned = await _booksLibraryManager.BooksOnLoan(email)
            };

            if (userProfile.AccessArea != null && userProfile.AccessArea.Contains(UserLevel.AccessArea.LibraryAdmin))
            {
                userProfile.BookLendingRequests = await _booksLibraryManager.GetNewLendingRequests();

                userProfile.RegistrationWaitingToBeApproved = await _userManager.RegistrationWaitingToBeApproved();
            }

            var str = JsonConvert.SerializeObject(userProfile);

            HttpContext.Session.SetString("userProfile", str);
            return(userProfile);
        }
Ejemplo n.º 13
0
        public async Task <CommonResponce> UpdateAppUserProfileAsync(UserProfileVM oModel)
        {
            CommonResponce result = new CommonResponce {
                Stat = false, StatusMsg = ""
            };
            var oUser = await _DBUserRepository.GetUserByID(oModel.Id).ConfigureAwait(false);

            if (oUser != null)
            {
                oUser.Name   = oModel.UserName;
                oUser.Email  = oModel.Email;
                oUser.Mobile = oModel.Mobile;
                oUser.Dob    = oModel.Dob;

                await _DBUserRepository.Update(oUser).ConfigureAwait(false);

                result.Stat      = true;
                result.StatusMsg = "Successfully updated application User";
            }
            else
            {
                result.StatusMsg = "Not a valid User";
            }

            return(result);
        }
Ejemplo n.º 14
0
        public void DataGridSource()
        {
            int rowNo = 1;

            dgRegisteredUser.AutoGenerateColumns = false;
            _entities = new MicroAccountsEntities1();

            List <UserProfileVM> modelList = new List <UserProfileVM>();

            var dataList = _entities.tbl_UserProfile.ToList();

            foreach (var item in dataList)
            {
                UserProfileVM model = new UserProfileVM();
                model.rowNo       = rowNo;
                model.firstName   = item.firstName;
                model.lastName    = item.lastName;
                model.mobile      = item.mobile;
                model.email       = item.email;
                model.userId      = item.userId;
                model.createdDate = Convert.ToDateTime(item.createdDate).ToString("dd-MM-yyyy  hh:mm tt");
                model.updateDate  = Convert.ToDateTime(item.updateDate).ToString("dd-MM-yyyy  hh:mm tt");

                modelList.Add(model);
                rowNo++;
            }

            dgRegisteredUser.DataSource = modelList;
            lblTotalRows.Text           = modelList.Count.ToString();
        }
Ejemplo n.º 15
0
        public ActionResult UserProfile()
        {
            try
            {
                var id   = HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId();
                var user = NewUserManager().FindById(id);
                var data = new UserProfileVM()
                {
                    Email       = user.Email,
                    Id          = user.Id,
                    Name        = user.Name,
                    PhoneNumber = user.PhoneNumber,
                    Surname     = user.Surname,
                    UserName    = user.UserName,
                    AvatarPath  = string.IsNullOrEmpty(user.AvatarPath) ? "/assets/images/icon-noprofile.png" : user.AvatarPath,
                    Location    = user.Location
                };

                return(View(data));
            }
            catch (Exception ex)
            {
                TempData["Message"] = new ErrorVM()
                {
                    Text           = $"Bir hata oluştu {ex.Message}",
                    ActionName     = "UserProfile",
                    ControllerName = "Account",
                    ErrorCode      = 500
                };
                return(RedirectToAction("Error500", "Home"));
            }
        }
Ejemplo n.º 16
0
        public async Task <ActionResult> EditProfile(int id, DateTime?from, DateTime?to, string searchString)
        {
            if (from > to)
            {
                DateTime?temp = from;
                from = to;
                to   = temp;
            }
            UserProfileVM Model = new UserProfileVM();
            await _context.Users.ToListAsync();

            await _context.Blogs.ToListAsync();

            var service = new BlogService(_context);

            Model.User  = service.FindUser(id);
            Model.Blogs = service.FindBlogs(id);
            if (from != null)
            {
                Model.Blogs.RemoveAll(b => b.PublishedDateTime < from);
            }

            if (to != null)
            {
                Model.Blogs.RemoveAll(b => b.PublishedDateTime > to);
            }
            if (!String.IsNullOrEmpty(searchString))
            {
                Model.Blogs.RemoveAll(b => !(b.Content.Contains(searchString)) && !(b.Title.Contains(searchString)) && !(b.Summary.Contains(searchString)));
            }
            Model.Blogs.Sort((x, y) => DateTime.Compare(x.PublishedDateTime, y.PublishedDateTime));
            return(View("EditProfile", Model));
        }
        public ActionResult UserProfile(UserProfileVM userProfileVM)
        {
            if (!ModelState.IsValid)
            {
                return(View("UserProfile"));
            }

            var     store       = new UserStore <AppUser>(new ShoppingCartContext());
            var     userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <AppUserManager>();
            AppUser user        = userManager.FindByName(User.Identity.Name);

            //TODO
            user.Email        = userProfileVM.EMail;
            user.PasswordHash = userProfileVM.Password;

            if (!string.IsNullOrEmpty(userProfileVM.Password))
            {
                var result = userManager.Update(user);

                if (result.Succeeded)
                {
                    store.Context.SaveChanges();
                    TempData["SM"] = "User profile changed";
                }
            }

            return(RedirectToAction("UserProfile"));
        }
Ejemplo n.º 18
0
        public ActionResult GetUserProfile()
        {
            var           id            = HttpContext.Session.GetString("id");
            UserProfileVM userProfileVM = null;

            var authToken = HttpContext.Session.GetString("JWToken");

            client.DefaultRequestHeaders.Add("Authorization", authToken);

            var resTask = client.GetAsync("Accounts/" + id);

            resTask.Wait();

            var result = resTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync <UserProfileVM>();
                readTask.Wait();

                userProfileVM = readTask.Result;
            }

            return(Json((result, userProfileVM), new Newtonsoft.Json.JsonSerializerSettings()));
        }
Ejemplo n.º 19
0
        public ActionResult UserProfile(string userId)
        {
            UserProfileVM model = new UserProfileVM();

            //var userId = User.Identity.GetUserId();
            var user = db.Users.Find(userId);

            if (userId == null)
            {
                user = db.Users.Find(User.Identity.GetUserId());
            }
            model.User      = user;
            model.UserRole  = roleHelper.ListUserRoles(userId).FirstOrDefault();
            model.Tickets   = ticketHelper.ListMyTickets();
            model.ProjectIn = projHelper.ListUserProjects(userId);


            //model.ProjectIn = projHelper.ListUserProjects(userId);
            //model.ProjectOut = projHelper.ListOtherProjects(userId);
            //model.TicketsIn = ticketHelper.ListMyTickets();
            //model.Role = roleHelper.ListUserRoles(userId).FirstOrDefault();


            return(View(model));
        }
Ejemplo n.º 20
0
        public async Task <ActionResult> UserProfile()
        {
            try
            {
                var user = await _membershipTools.UserManager.GetUserAsync(HttpContext.User);

                var data = new UserProfileVM()
                {
                    Email       = user.Email,
                    Id          = user.Id,
                    Name        = user.Name,
                    PhoneNumber = user.PhoneNumber,
                    Surname     = user.Surname,
                    UserName    = user.UserName,
                    AvatarPath  = string.IsNullOrEmpty(user.AvatarPath) ? "/assets/images/icon-noprofile.png" : user.AvatarPath,
                    Latitude    = user.Latitude,
                    Longitude   = user.Longitude
                };

                return(View(data));
            }
            catch (Exception ex)
            {
                var errorVM = new ErrorVM()
                {
                    Text           = $"Bir hata oluştu {ex.Message}",
                    ActionName     = "UserProfile",
                    ControllerName = "Account",
                    ErrorCode      = "500"
                };
                TempData["ErrorMessage"] = JsonConvert.SerializeObject(errorVM);
                return(RedirectToAction("Error500", "Home"));
            }
        }
        public async Task <IHttpActionResult> PutUserProfile(int id, UserProfileVM userProfileVM)
        {
            UserProfile userProfile = ConvertToDBModel(userProfileVM);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != userProfile.ID)
            {
                return(BadRequest());
            }

            db.Entry(userProfile).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserProfileExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 22
0
        public Message ChangeProfile(UserProfileVM vm)
        {
            var user = Get(vm.Id);

            user.UserName    = user.UserName ?? vm.UserName;
            user.Gender      = vm.Gender;
            user.BirthDate   = vm.BirthDate;
            user.FirstName   = vm.FirstName;
            user.LastName    = vm.LastName;
            user.Email       = user.Email ?? vm.Email;
            user.PhoneNumber = vm.PhoneNumber;

            if (!string.IsNullOrEmpty(vm.Avatar))
            {
                user.Avatar = vm.Avatar;
            }

            try
            {
                ctx.SaveChanges();
                return(Message.Saved);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 23
0
        public ActionResult UpdateUserProfile(UserProfileVM userProfile, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var image = WebImage.GetImageFromRequest();

                if (image != null)
                {
                    var width  = image.Width;
                    var height = image.Height;
                    if (width > height)
                    {
                        var leftRightCrop = (width - height) / 2;
                        image.Crop(0, leftRightCrop, 0, leftRightCrop);
                    }
                    else if (height > width)
                    {
                        var topBottomCrop = (height - width) / 2;
                        image.Crop(topBottomCrop, 0, topBottomCrop, 0);
                    }

                    var filename = Path.GetFileName(image.FileName).Replace(' ', '_');
                    image.Save(Path.Combine(Server.MapPath("../Avatars/"), filename));
                    filename = Path.Combine("~/Avatars/" + filename);

                    userProfile.AvatarPath = Url.Content(filename);
                }

                var userId = User.Identity.GetUserId();
                var user   = db.Users.Find(userId);

                user.FirstName   = userProfile.FirstName;
                user.LastName    = userProfile.LastName;
                user.DisplayName = userProfile.DisplayName;
                user.Email       = userProfile.Email;
                user.UserName    = userProfile.Email;
                user.AvatarPath  = userProfile.AvatarPath;

                db.Users.Attach(user);
                db.Entry(user).Property(x => x.FirstName).IsModified   = true;
                db.Entry(user).Property(x => x.LastName).IsModified    = true;
                db.Entry(user).Property(x => x.DisplayName).IsModified = true;
                db.Entry(user).Property(x => x.Email).IsModified       = true;
                db.Entry(user).Property(x => x.UserName).IsModified    = true;
                db.Entry(user).Property(x => x.AvatarPath).IsModified  = true;
                db.SaveChanges();

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));

                ModelState.AddModelError("", message);
                return(View(userProfile));
            }
        }
Ejemplo n.º 24
0
        public ActionResult UserProfile()
        {
            var username = User.Identity.Name;
            var dto      = db.Users.FirstOrDefault(x => x.Username == username);
            var model    = new UserProfileVM(dto);

            return(View("UserProfile", model));
        }
Ejemplo n.º 25
0
 public MainVM(string pictureGroup, UserProfileVM userProfile, List <PictureVM> picturesToPresent, List <UserProfileVM> usersVM, List <UserProfileVM> followingUsersVM)
 {
     PictureGroup      = pictureGroup;
     UserProfile       = userProfile;
     PicturesToPresent = picturesToPresent;
     UsersVM           = usersVM;
     FollowingUsersVM  = followingUsersVM;
 }
Ejemplo n.º 26
0
        public ActionResult Profile()
        {
            string userName = this.User.Identity.Name;

            UserProfileVM vm = service.GetUserProfile(userName);

            return(View(vm));
        }
Ejemplo n.º 27
0
        public void Register(UserProfileVM userProfile)
        {
            HashHelper hashHelper = new HashHelper();

            userProfile.Password = hashHelper.GetHash(userProfile.Password);
            userProfile.RoleID   = 3;
            UserProfile.AddUserProfile(userProfile);
        }
Ejemplo n.º 28
0
        public ActionResult UserProfile(UserProfileVM model)
        {
            // Check model state
            if (!ModelState.IsValid)
            {
                return(View("UserProfile", model));
            }

            // Check if passwords match if need be
            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                if (!model.Password.Equals(model.ConfirmPassword))
                {
                    ModelState.AddModelError("", "Passwords do not match.");
                    return(View("UserProfile", model));
                }
            }

            using (Db db = new Db())
            {
                // Get username
                string username = User.Identity.Name;

                // Make sure username is unique
                if (db.Users.Where(x => x.Id != model.Id).Any(x => x.Username == username))
                {
                    ModelState.AddModelError("", "Username " + model.Username + " already exists.");
                    model.Username = "";
                    return(View("UserProfile", model));
                }

                // Edit DTO
                UserDTO dto = db.Users.Find(model.Id);

                dto.FirstName    = model.FirstName;
                dto.LastName     = model.LastName;
                dto.EmailAddress = model.EmailAddress;
                dto.Username     = model.Username;
                dto.Address      = model.Address;
                dto.Number       = model.Number;
                dto.DateOfBirth  = model.DateOfBirth;

                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    dto.Password = model.Password;
                }

                // Save
                db.SaveChanges();
            }

            // Set TempData message
            TempData["SM"] = "You have edited your profile!";

            // Redirect
            return(Redirect("~/Account/user-profile"));
        }
Ejemplo n.º 29
0
        public ActionResult UserProfile(UserProfileVM model)
        {
            //check model state
            if (!ModelState.IsValid)
            {
                return(View("UserProfile", model)); //being specific of paostback method
            }

            //check if passwords match if need be
            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                if (!model.Password.Equals(model.ConfirmPassword))
                {
                    ModelState.AddModelError("", "Passwords do not match");
                    return(View("UserProfile", model));
                }
            }


            using (CmsShoppingCartContext db = new CmsShoppingCartContext())
            {
                //Get username
                string username = User.Identity.Name;
                //Make sure username is unique
                if (db.Users.Where(x => x.Id != model.Id).Any(x => x.UserName == username))
                {
                    //if theres a match we have a problem
                    ModelState.AddModelError("", "Username" + model.UserName + "already exists");
                    model.UserName = ""; //reset username
                    return(View("UserProfile", model));
                }

                //Edit DTO
                UserDTO dto = db.Users.Find(model.Id);

                dto.FirstName    = model.FirstName;
                dto.UserName     = model.LastName;
                dto.EmailAddress = model.EmailAddress;
                dto.UserName     = model.UserName;

                if (!string.IsNullOrWhiteSpace(model.Password)) //if passowrd is not temp edeit otherwiserse do nothing
                {
                    //if it is
                    dto.Password = model.Password;
                }

                //Save
                db.SaveChanges();
            }

            //Set TempData message
            TempData["SM"] = "You have edited your profile";

            //Redirect

            return(Redirect("~/account/user-profile")); /////
        }
Ejemplo n.º 30
0
        private void CreateCookie(UserProfileVM userProfile)
        {
            FormsAuthentication.SetAuthCookie(userProfile.Username, true);
            var    authTicket      = new FormsAuthenticationTicket(1, userProfile.Username, DateTime.Now, DateTime.Now.AddMinutes(60), false, userProfile.Role.RoleName);
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            HttpContext.Response.Cookies.Add(authCookie);
        }
Ejemplo n.º 31
0
 //Users
 public UserProfileVM GetUserProfile(int accountID)
 {
     FarmSaleDBEntities1 db = new FarmSaleDBEntities1();
     AccountDetail accountDetail = db.AccountDetails.Where(ad => ad.accountID == accountID).FirstOrDefault();
     Account account = db.Accounts.Where(a => a.accountID == accountID).FirstOrDefault();
     Address address = db.Addresses.Where(adr => adr.addressID == accountDetail.addressID).FirstOrDefault();
     UserProfileVM profile = new UserProfileVM();
     profile.Username = account.username;
     profile.Email = account.email;
     profile.StreetNum = address.streetNum;
     profile.StreetName = address.streetName;
     profile.Province = address.province;
     profile.City = address.city;
     profile.Zip = address.zip;
     return profile;
 }