Example #1
0
        public ActionResult UserAdd(RegistrationRequest regRequest)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!ModelState.IsValid)
                {
                    TempData["Error"] = ModelState.Values.First(f => f.Errors.Count() >= 1).Errors.First().ErrorMessage;
                    return(View(regRequest));
                }

                var existsProfile = (from u in zcrlDbContext.Users where (u.Login == regRequest.Login) select u).FirstOrDefault();
                var existsRequest = (from r in zcrlDbContext.UserRegistrationRequests where (r.Login == regRequest.Login) select r).FirstOrDefault();
                if (existsProfile != null || existsRequest != null)
                {
                    TempData["Error"] = "Такий логін вже зареєстрований.";
                    return(View(regRequest));
                }

                string error = ZcrlDataValidator.getProfileInputError(new UserProfile(regRequest));
                if (!string.IsNullOrWhiteSpace(error))
                {
                    TempData["Error"] = error;
                    return(View(regRequest));
                }

                zcrlDbContext.Profiles.Add(new UserProfile(regRequest));
                zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                {
                    СreatedDate = DateTime.Now,
                    RecordType  = Models.LogRecordType.UserChanges,
                    Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> додав користувача <b>{3} {4}.{5}.</b>", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), regRequest.LastName, regRequest.FirstName.First(), regRequest.MiddleName.First())
                });
                zcrlDbContext.SaveChanges();

                TempData["SuccessMessage"] = "Користувач " + regRequest.LastName + " " + regRequest.FirstName + " успішно створений!";
                return(RedirectToAction("UsersList"));
            }
        }
Example #2
0
        public ActionResult EditProfile(ZcrlPortal.Models.UserProfile updatedProfile, HttpPostedFileBase photoFile)
        {
            int profileEditorId   = (int)Profile["Id"];
            int?redirectProfileId = null;

            if ((updatedProfile.Id != profileEditorId) && !User.IsInRole("Administrators"))
            {
                return(RedirectToAction("EditProfile"));
            }

            if (updatedProfile.Id != profileEditorId)
            {
                redirectProfileId = updatedProfile.Id;
            }

            ZcrlPortal.Models.UserProfile requiredProfile;
            ZcrlPortal.Models.UserProfile existProfile;

            string error = ZcrlDataValidator.getProfileInputError(updatedProfile);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                return(RedirectToAction("EditProfile", new { id = redirectProfileId }));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                // Профиль который необходимо изменить
                requiredProfile = (from p in zcrlDbContext.Profiles
                                   where (p.Id == updatedProfile.Id)
                                   select p).FirstOrDefault();

                if (updatedProfile.RelatedUser == null)
                {
                    existProfile = null;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(updatedProfile.RelatedUser.Login))
                    {
                        TempData["Error"] = "Ви не вказали логін";
                        return(RedirectToAction("EditProfile", new { id = redirectProfileId }));
                    }
                    string enteredLogin = updatedProfile.RelatedUser.Login.Trim();
                    // При изменении логина, ищем другой профиль с таким же логином
                    existProfile = (from p in zcrlDbContext.Profiles
                                    where ((p.RelatedUser.Login == enteredLogin) && (p.Id != updatedProfile.Id))
                                    select p).FirstOrDefault();
                }


                if (requiredProfile != null)
                {
                    if (User.IsInRole("Administrators") && existProfile != null)
                    {
                        TempData["Error"] = "Такий логін вже зареєстрований";
                        return(RedirectToAction("EditProfile", new { id = redirectProfileId }));
                    }

                    if (!string.IsNullOrWhiteSpace(updatedProfile.Email))
                    {
                        var existUserEmail    = (from p in zcrlDbContext.Profiles where ((p.Email == updatedProfile.Email) && (p.Id != updatedProfile.Id)) select p).FirstOrDefault();
                        var existRequestEmail = (from r in zcrlDbContext.UserRegistrationRequests where (r.Email == updatedProfile.Email) select r).FirstOrDefault();
                        if (existUserEmail != null || existRequestEmail != null)
                        {
                            TempData["Error"] = "Така адреса електронної пошти вже зареєстрована";
                            return(RedirectToAction("EditProfile", new { id = redirectProfileId }));
                        }
                    }

                    // Залогить изменения
                    logProfileChanges(requiredProfile, updatedProfile);

                    requiredProfile.FirstName       = updatedProfile.FirstName;
                    requiredProfile.LastName        = updatedProfile.LastName;
                    requiredProfile.MiddleName      = updatedProfile.MiddleName;
                    requiredProfile.Email           = (string.IsNullOrWhiteSpace(updatedProfile.Email)) ? null : updatedProfile.Email.ToLower();
                    requiredProfile.Education       = (updatedProfile.Education == null) ? null : updatedProfile.Education.Trim();
                    requiredProfile.JobTitle        = (updatedProfile.JobTitle == null) ? null : updatedProfile.JobTitle.Trim();
                    requiredProfile.TelephoneNumber = updatedProfile.TelephoneNumber;
                    requiredProfile.WorkLocation    = updatedProfile.WorkLocation;
                    requiredProfile.SiteAddress     = updatedProfile.SiteAddress;
                    requiredProfile.Sex             = updatedProfile.Sex;

                    try
                    {
                        if (photoFile.IsImage())
                        {
                            if (requiredProfile.PhotoFileName != null && System.IO.File.Exists(Path.Combine(Server.MapPath(UPLOADPHOTO_DIR), requiredProfile.PhotoFileName)))
                            {
                                System.IO.File.Delete(Path.Combine(Server.MapPath(UPLOADPHOTO_DIR), requiredProfile.PhotoFileName));
                            }

                            string newPhotoFileName = requiredProfile.Id.ToString() + Path.GetExtension(photoFile.FileName);
                            string newPhotoFilePath = Path.Combine(Server.MapPath(UPLOADPHOTO_DIR), newPhotoFileName);
                            photoFile.SaveAs(newPhotoFilePath);

                            requiredProfile.PhotoFileName = newPhotoFileName;

                            zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                            {
                                СreatedDate = DateTime.Now,
                                RecordType  = Models.LogRecordType.UserChanges,
                                Content     = (requiredProfile.Id == (int)Profile["Id"])
                                ? string.Format("Користувач <b>{0} {1}.{2}.</b> змінив свою фотографію.", requiredProfile.LastName, requiredProfile.FirstName.First(), requiredProfile.MiddleName.First())
                                : string.Format("Користувач <b>{0} {1}.{2}.</b> змінив фотографію користувача <b>{3} {4}.{5}.</b>.", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), requiredProfile.LastName, requiredProfile.FirstName.First(), requiredProfile.MiddleName.First())
                            });
                        }
                    }
                    catch
                    {
                        TempData["Error"] = "Помилка при завантаженні фотографії, повторіть спробу пізніше";
                        return(RedirectToAction("EditProfile", new { id = redirectProfileId }));
                    }

                    if (User.IsInRole("Administrators"))
                    {
                        requiredProfile.RelatedUser.Login  = updatedProfile.RelatedUser.Login.Trim();
                        requiredProfile.RelatedUser.RoleId = updatedProfile.RelatedUser.RoleId;
                        requiredProfile.DataGroupId        = updatedProfile.DataGroupId;
                        requiredProfile.IsPublicated       = updatedProfile.IsPublicated;
                        requiredProfile.ViewPriority       = updatedProfile.ViewPriority;
                    }

                    zcrlDbContext.SaveChanges();

                    if (profileEditorId == requiredProfile.Id)
                    {
                        Profile["FirstName"]     = requiredProfile.FirstName;
                        Profile["LastName"]      = requiredProfile.LastName;
                        Profile["MiddleName"]    = requiredProfile.MiddleName;
                        Profile["PhotoFileName"] = requiredProfile.PhotoFileName;
                        Profile["Sex"]           = requiredProfile.Sex;
                    }

                    TempData["Success"] = true;
                }
            }

            return(RedirectToAction("EditProfile"));
        }