예제 #1
0
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            bool result = false;

            using (ZcrlContext zc = new ZcrlContext())
            {
                var userForDelete = (from u in zc.Users
                                     where (u.Login == username)
                                     select u).FirstOrDefault();

                var userProfile = (from p in zc.Profiles
                                   where (p.RelatedUser.Login == username)
                                   select p).FirstOrDefault();

                if (userProfile != null && deleteAllRelatedData)
                {
                    zc.Profiles.Remove(userProfile);
                    zc.Users.Remove(userForDelete);
                    zc.SaveChanges();
                    result = true;
                }
                if (userForDelete != null)
                {
                    zc.Users.Remove(userForDelete);
                    zc.SaveChanges();
                    result = true;
                }
            }

            return(result);
        }
예제 #2
0
        public ActionResult EditUserBiography(ZcrlPortal.Models.UserProfile profile)
        {
            int profileEditorId = int.Parse(Profile["Id"].ToString());

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

            using (zcrlDbContext = new ZcrlContext())
            {
                var requiredProfile = (from p in zcrlDbContext.Profiles where (p.Id == profile.Id) select p).FirstOrDefault();
                if (requiredProfile != null)
                {
                    requiredProfile.AboutMe    = profile.AboutMe;
                    ViewBag.editProfileSuccess = true;
                    zcrlDbContext.SaveChanges();

                    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())
                    });
                    zcrlDbContext.SaveChanges();
                }
            }

            TempData["Success"] = true;
            return(RedirectToAction("EditProfile"));
        }
예제 #3
0
        public ActionResult DeleteUser(int?id)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                var deletedProfile = (from p in zcrlDbContext.Profiles where (p.Id == id) select p).FirstOrDefault();
                if (deletedProfile != null)
                {
                    // Таким образои хотя бы один админ останется :)
                    if (deletedProfile.Id == (int)Profile["Id"])
                    {
                        TempData["Error"] = "Ви не можете видалити самі себе!";
                        return(RedirectToAction("UsersList"));
                    }

                    string deletedProfileName = deletedProfile.LastName + " " + deletedProfile.FirstName + " " + deletedProfile.MiddleName;

                    ViewBag.Mode = CrudMode.Delete;
                    int userId = deletedProfile.RelatedUser.Id;

                    // Удаляем фото
                    if (deletedProfile.PhotoFileName != null && (System.IO.File.Exists(System.IO.Path.Combine(UPLOADPHOTO_DIR, deletedProfile.PhotoFileName))))
                    {
                        System.IO.File.Delete(System.IO.Path.Combine(UPLOADPHOTO_DIR, deletedProfile.PhotoFileName));
                    }

                    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(), deletedProfile.LastName, deletedProfile.FirstName.First(), deletedProfile.MiddleName.First())
                    });
                    zcrlDbContext.Profiles.Remove(deletedProfile);
                    zcrlDbContext.SaveChanges();

                    var deletedUser = (from u in zcrlDbContext.Users where (u.Id == userId) select u).First();
                    zcrlDbContext.Users.Remove(deletedUser);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Пользователь " + deletedProfileName + " успешно удалён!";
                    return(RedirectToAction("UsersList"));
                }
                else
                {
                    return(RedirectToAction("UsersList"));
                }
            }
        }
예제 #4
0
        private void logChanges(AdvBanner oldBanner, AdvBanner newBanner)
        {
            string changes = null;

            if (oldBanner.Name != newBanner.Name)
            {
                changes += string.Format("Користувач <b>{0} {1}.{2}.</b> змінив назву банера з '{3}' на '{4}'<br />", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), oldBanner.Name, newBanner.Name);
            }
            if (oldBanner.DestUrl != newBanner.DestUrl)
            {
                changes += string.Format("Користувач <b>{0} {1}.{2}.</b> змінив адресу посилання банера з '{3}' на '{4}'<br />", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), oldBanner.DestUrl, newBanner.DestUrl);
            }

            if (!string.IsNullOrWhiteSpace(changes))
            {
                using (zcrlDbContext = new ZcrlContext())
                {
                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = LogRecordType.BannerAddEdit,
                        Content     = changes
                    });
                    zcrlDbContext.SaveChanges();
                }
            }
        }
예제 #5
0
        public ActionResult ChangeChapter(StaticChapter chap)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                var historyChapter = (from c in zcrlDbContext.Chapters
                                      where (c.Id == chap.Id)
                                      select c).First();
                if (historyChapter == null)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                historyChapter.Content = chap.Content;
                zcrlDbContext.SaveChanges();

                switch (chap.ChapterType)
                {
                case StaticChapterType.History:
                {
                    return(RedirectToAction("History", "Home"));
                }

                case StaticChapterType.PortalInformation:
                {
                    return(RedirectToAction("Information", "Home"));
                }

                default:
                {
                    return(RedirectToAction("News", "Home"));
                }
                }
            }
        }
예제 #6
0
        public ActionResult DeleteRegRequest(long?id)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                var deletedRequest = (from rr in zcrlDbContext.UserRegistrationRequests
                                      where (rr.Id == id) select rr).FirstOrDefault();

                if (deletedRequest != null)
                {
                    string deletedRequestOwner = deletedRequest.LastName + " " + deletedRequest.FirstName + " " + deletedRequest.MiddleName;

                    zcrlDbContext.UserRegistrationRequests.Remove(deletedRequest);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Заявка користувача " + deletedRequestOwner + " відмовлена!";
                    return(RedirectToAction("RegistrationRequestsList"));
                }
                else
                {
                    return(RedirectToAction("RegistrationRequestsList"));
                }
            }
        }
예제 #7
0
        public ActionResult Download(long?id)
        {
            if (!id.HasValue)
            {
                return(RedirectToAction("NotFound", "Error"));
            }

            string filePath = null;
            string fileName = null;

            using (zcrlDbContext = new ZcrlContext())
            {
                var fileInDb = (from dbF in zcrlDbContext.UploadFiles where (dbF.Id == id.Value) select dbF).FirstOrDefault();
                if (fileInDb == null)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(fileInDb.FileName))
                    {
                        return(RedirectToAction("NotFound", "Error"));
                    }
                    filePath = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), fileInDb.FileName);
                    fileName = clearFileName(fileInDb.DisplayName) + System.IO.Path.GetExtension(fileInDb.FileName);
                }
                fileInDb.DownloadCount++;
                zcrlDbContext.SaveChanges();
            }

            byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

            return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }
예제 #8
0
        public ActionResult Register(RegistrationRequest request)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("News", "Home"));
            }

            if (ModelState.IsValid)
            {
                using (zcrlDbContext = new ZcrlContext())
                {
                    var existUser    = (from u in zcrlDbContext.Users where (u.Login == request.Login) select u).FirstOrDefault();
                    var existRequest = (from r in zcrlDbContext.UserRegistrationRequests where (r.Login == request.Login) select r).FirstOrDefault();

                    if (existUser != null || existRequest != null)
                    {
                        ViewBag.RegistrationError = "Такий логін вже зареєстрований";
                        return(View(request));
                    }

                    if (!string.IsNullOrWhiteSpace(request.Email))
                    {
                        var existUserEmail    = (from p in zcrlDbContext.Profiles where (p.Email == request.Email.ToLower()) select p).FirstOrDefault();
                        var existRequestEmail = (from r in zcrlDbContext.UserRegistrationRequests where (r.Email == request.Email.ToLower()) select r).FirstOrDefault();

                        if (existUserEmail != null || existRequestEmail != null)
                        {
                            ViewBag.RegistrationError = "Така адреса електронної пошти вже зареєстрована";
                            return(View(request));
                        }
                    }
                }

                ViewBag.RegistrationSuccess = true;
                using (zcrlDbContext = new ZcrlContext())
                {
                    zcrlDbContext.UserRegistrationRequests.Add(request);
                    zcrlDbContext.SaveChanges();
                }

                // Уведомляем администратора о регистрации
                sendEmail("*****@*****.**",
                          "ЗАЯВКА НА РЕЄСТРАЦІЮ",
                          string.Format("<b>{0} {1} {2} подав(ла) заявку на реєстрацію на порталі Запорізької ЦРЛ</b>",
                                        request.LastName, request.FirstName, request.MiddleName));

                return(View());
            }
            else
            {
                ViewBag.RegistrationError = ModelState.Values.First(f => f.Errors.Count() >= 1).Errors.First().ErrorMessage;
                return(View(request));
            }
        }
예제 #9
0
        public ActionResult EditFileInList(UploadFile updatedFile, HttpPostedFileBase attachedFile)
        {
            string error = getModelError(updatedFile);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                return(View("AddEditFile", updatedFile));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                var requiredFile = (from f in zcrlDbContext.UploadFiles
                                    where ((f.FileType == UploadFileType.AdminPrivateUpload) && (f.Id == updatedFile.Id))
                                    select f).FirstOrDefault();
                if (requiredFile != null)
                {
                    if (attachedFile.isValidFile())
                    {
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(requiredFile.FileName))
                            {
                                if (System.IO.File.Exists(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredFile.FileName)))
                                {
                                    System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredFile.FileName));
                                }
                            }

                            string newFileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(attachedFile.FileName);
                            string newPath     = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), newFileName);
                            attachedFile.SaveAs(newPath);
                            updatedFile.FileName = newFileName;
                        }
                        catch
                        {
                            TempData["Error"] = "Помилка при завантаженні файлу";
                            return(View("AddEditFile", updatedFile));
                        }
                    }
                    requiredFile.DisplayName = updatedFile.DisplayName;
                    requiredFile.FileName    = updatedFile.FileName;

                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Файл успішно змінений";
                    return(RedirectToAction("FilesList"));
                }
                else
                {
                    return(RedirectToAction("NotFound", "Error"));
                }
            }
        }
예제 #10
0
        public ActionResult Delete(LogRecordType recordsGroup)
        {
            string redirectActionName = null;

            using (zcrlDbContext = new ZcrlContext())
            {
                var logsList = (from l in zcrlDbContext.LogJournal where (l.RecordType == recordsGroup) select l);

                if (logsList != null)
                {
                    zcrlDbContext.LogJournal.RemoveRange(logsList);
                    zcrlDbContext.SaveChanges();
                }
                switch (recordsGroup)
                {
                case LogRecordType.UserChanges:
                case LogRecordType.RegistrationsRequests:
                {
                    redirectActionName = "UsersLog";
                    break;
                }

                case LogRecordType.BannerAddEdit:
                {
                    redirectActionName = "BannersLog";
                    break;
                }

                case LogRecordType.NewsAddEdit:
                {
                    redirectActionName = "NewsLog";
                    break;
                }

                case LogRecordType.ArticlesAddEdit:
                {
                    redirectActionName = "ArticleLog";
                    break;
                }

                case LogRecordType.TendersAddEdit:
                {
                    redirectActionName = "TenderLog";
                    break;
                }
                }

                TempData["SuccessMessage"] = "Журнал очіщєно";
                return(RedirectToAction(redirectActionName));
            }
        }
예제 #11
0
        public ActionResult AcceptRegRequest(long?id)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                var regRequest = (from rr in zcrlDbContext.UserRegistrationRequests where (rr.Id == id) select rr).FirstOrDefault();

                if (regRequest != null)
                {
                    string requestOwner = regRequest.LastName + " " + regRequest.FirstName + " " + regRequest.MiddleName;

                    zcrlDbContext.Profiles.Add(new UserProfile(regRequest));
                    zcrlDbContext.SaveChanges();

                    if (!string.IsNullOrWhiteSpace(regRequest.Email))
                    {
                        sendEmail(regRequest.Email,
                                  "ЗАЯВКА НА РЕЄСТРАЦІЮ",
                                  string.Format("Шановна(ий) {0} {1} {2}!<br /><br />Ваша заявка на реєстрацію на порталі Запорізької ЦРЛ була задовільнена. Тепер Ви можете увійти до системи використовуючи логін та пароль, що вказали при реєстрації в системі.<br /> -------------------------------<br /> З повагою, адміністрація <a href=\"zcrl.in.ua\">веб-порталу Запорізької ЦРЛ</a>!", regRequest.LastName, regRequest.FirstName, regRequest.MiddleName)
                                  );
                    }

                    zcrlDbContext.UserRegistrationRequests.Remove(regRequest);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Заявка користувача " + requestOwner + " задовільнена!";
                    return(RedirectToAction("RegistrationRequestsList"));
                }
                else
                {
                    return(RedirectToAction("RegistrationRequestsList"));
                }
            }
        }
예제 #12
0
        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
        {
            string userName = (string)context["UserName"];
            SettingsPropertyValueCollection spvCollection = new SettingsPropertyValueCollection();

            if (!string.IsNullOrWhiteSpace(userName))
            {
                using (ZcrlContext zc = new ZcrlContext())
                {
                    var requiredProfile = (from p in zc.Profiles
                                           where (p.RelatedUser.Login == userName)
                                           select p).FirstOrDefault();

                    if (requiredProfile != null)
                    {
                        foreach (SettingsProperty prop in collection)
                        {
                            SettingsPropertyValue spv = new SettingsPropertyValue(prop);
                            spv.PropertyValue = requiredProfile.GetType().GetProperty(prop.Name).GetValue(requiredProfile, null);
                            spvCollection.Add(spv);
                            zc.SaveChanges();
                        }
                    }
                    else
                    {
                        foreach (SettingsProperty prop in collection)
                        {
                            SettingsPropertyValue spv = new SettingsPropertyValue(prop);
                            spv.PropertyValue = null;
                            spvCollection.Add(spv);
                            zc.SaveChanges();
                        }
                    }
                }
            }

            return(spvCollection);
        }
예제 #13
0
        public ActionResult AddBanner(AdvBanner banner, HttpPostedFileBase bannerFile)
        {
            string userInputError = getModelError(banner);

            if (!string.IsNullOrWhiteSpace(userInputError))
            {
                TempData["Error"] = userInputError;
                ViewBag.Mode      = CrudMode.Add;
                return(View("AddEditBanner", banner));
            }
            if (!bannerFile.IsImage())
            {
                TempData["Error"] = "Невірний формат файлу для банеру";
                ViewBag.Mode      = CrudMode.Add;
                return(View("AddEditBanner", banner));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                AdvBanner newBanner = new AdvBanner()
                {
                    Name = banner.Name, DestUrl = banner.DestUrl, ViewPriority = banner.ViewPriority
                };
                try
                {
                    string newFileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(bannerFile.FileName);
                    string newFilePath = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), newFileName);
                    bannerFile.SaveAs(newFilePath);
                    newBanner.ImgName = newFileName;
                    zcrlDbContext.Banners.Add(newBanner);
                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now, RecordType = LogRecordType.BannerAddEdit,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> створив баннер <b>{3}</b>.", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), newBanner.Name)
                    });
                    zcrlDbContext.SaveChanges();
                }
                catch
                {
                    TempData["Error"] = "Помилка при заватаженні файлу, повторіть свою спробу пізніше";
                    ViewBag.Mode      = CrudMode.Edit;
                    return(View("AddEditBanner", banner));
                }

                TempData["SuccessMessage"] = "Баннер успішно додано!";
                return(RedirectToAction("BannersList"));
            }
        }
예제 #14
0
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            if (upload.ContentLength <= 0)
            {
                return(null);
            }

            // here logic to upload image
            // and get file path of the image

            var newfileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName);
            var path        = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), newfileName);

            upload.SaveAs(path);

            using (zcrlDbContext = new ZcrlContext())
            {
                int         uploaderId = (int)Profile["Id"];
                UserProfile editor     = (from p in zcrlDbContext.Profiles
                                          where (p.UserId == uploaderId)
                                          select p).First();
                UploadFile uploadedFile = new UploadFile()
                {
                    Author      = editor,
                    FileName    = newfileName,
                    FileType    = UploadFileType.PublicationUpload,
                    DisplayName = "ZCRL_IMG"
                };

                zcrlDbContext.UploadFiles.Add(uploadedFile);
                zcrlDbContext.SaveChanges();
            }

            var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
                                    Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
                                    UPLOADFILE_DIR.Substring(2), newfileName);

            // passing message success/failure
            const string message = "Image was saved correctly";

            // since it is an ajax request it requires this string
            var output = string.Format(
                "<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
                CKEditorFuncNum, url, message);

            return(Content(output));
        }
예제 #15
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            bool result = false;

            using (ZcrlContext zc = new ZcrlContext())
            {
                var requiredRole = (from r in zc.Roles where (r.Name == roleName) select r).FirstOrDefault();
                if (requiredRole != null)
                {
                    zc.Roles.Remove(requiredRole);
                    zc.SaveChanges();
                    result = true;
                }
            }

            return(result);
        }
예제 #16
0
        public ActionResult DeleteFile(long?id)
        {
            if (!id.HasValue)
            {
                return(RedirectToAction("NotFound", "Error"));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                var requiredFile = (from uf in zcrlDbContext.UploadFiles
                                    where ((uf.FileType == UploadFileType.AdminPrivateUpload) && (uf.Id == id.Value))
                                    select uf).FirstOrDefault();

                if (requiredFile != null)
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(requiredFile.FileName))
                        {
                            if (System.IO.File.Exists(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredFile.FileName)))
                            {
                                System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredFile.FileName));
                            }
                        }
                    }
                    catch
                    {
                        return(RedirectToAction("ApplicationError", "Error"));
                    }

                    zcrlDbContext.UploadFiles.Remove(requiredFile);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Файл успішно видалений";
                    return(RedirectToAction("FilesList"));
                }
                else
                {
                    return(RedirectToAction("NotFound", "Error"));
                }
            }
        }
예제 #17
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            bool result = false;

            using (ZcrlContext zc = new ZcrlContext())
            {
                var userForChanging = (from u in zc.Users
                                       where (u.Login == username)
                                       select u).FirstOrDefault();

                if (userForChanging != null && Crypto.VerifyHashedPassword(userForChanging.Password, oldPassword + SALT))
                {
                    userForChanging.Password = Crypto.HashPassword(newPassword + SALT);
                    zc.SaveChanges();
                    result = true;
                }
            }

            return(result);
        }
예제 #18
0
        public ActionResult AddFileToList(UploadFile newFile, HttpPostedFileBase attachedFile)
        {
            string error = getModelError(newFile);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                ViewBag.Mode      = CrudMode.Add;
                return(View("AddEditFile", newFile));
            }

            if (!attachedFile.isValidFile())
            {
                TempData["Error"] = "Невірний або пошкоджений файл!";
                ViewBag.Mode      = CrudMode.Add;
                return(View("AddEditFile", newFile));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                try
                {
                    string newFileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(attachedFile.FileName);
                    string newPath     = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), newFileName);
                    attachedFile.SaveAs(newPath);
                    newFile.FileName = newFileName;
                }
                catch
                {
                    TempData["Error"] = "Помилка при завантаженні файлу, повсторіть спробу пізніше!";
                    ViewBag.Mode      = CrudMode.Add;
                    return(View("AddEditFile", newFile));
                }

                zcrlDbContext.UploadFiles.Add(newFile);
                zcrlDbContext.SaveChanges();

                TempData["SuccessMessage"] = "Файл успішно завантажений";
                return(RedirectToAction("FilesList"));
            }
        }
예제 #19
0
 public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
 {
     using (ZcrlContext zc = new ZcrlContext())
     {
         foreach (string roleName in roleNames)
         {
             var requiredRole = (from r in zc.Roles where r.Name == roleName select r).FirstOrDefault();
             if (requiredRole != null)
             {
                 foreach (string userName in usernames)
                 {
                     var requiredUser = (from u in zc.Users where (u.Login == userName) select u).FirstOrDefault();
                     if (requiredUser != null)
                     {
                         requiredRole.UsersInRole.Remove(requiredUser);
                     }
                 }
             }
         }
         zc.SaveChanges();
     }
 }
예제 #20
0
        public ActionResult DeleteBanner(int?id)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                var deletedBanner = (from b in zcrlDbContext.Banners where (b.Id == id) select b).FirstOrDefault();

                if (deletedBanner != null)
                {
                    string bannerName = deletedBanner.Name;

                    if (System.IO.File.Exists(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), deletedBanner.ImgName)))
                    {
                        System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), deletedBanner.ImgName));
                    }

                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = LogRecordType.BannerAddEdit,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> видалив баннер <b>{3}</b>.", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), deletedBanner.Name)
                    });
                    zcrlDbContext.Banners.Remove(deletedBanner);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Баннер " + bannerName + " успішно видалений!";
                    return(RedirectToAction("BannersList"));
                }
                else
                {
                    return(RedirectToAction("BannersList"));
                }
            }
        }
예제 #21
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"));
            }
        }
예제 #22
0
        public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
        {
            string userName = (string)context["UserName"];

            if (!string.IsNullOrWhiteSpace(userName))
            {
                using (ZcrlContext zc = new ZcrlContext())
                {
                    var requiredProfile = (from p in zc.Profiles
                                           where (p.RelatedUser.Login == userName)
                                           select p).FirstOrDefault();

                    if (requiredProfile != null)
                    {
                        foreach (SettingsPropertyValue propVal in collection)
                        {
                            requiredProfile.GetType().GetProperty(propVal.Property.Name).SetValue(requiredProfile, propVal.PropertyValue);
                        }

                        zc.SaveChanges();
                    }
                }
            }
        }
예제 #23
0
        public ActionResult DeleteTenderItem(long?id)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                int itemsCount  = 0;
                var deletedItem = (from it in zcrlDbContext.TenderItems where (it.Id == id) select it).FirstOrDefault();

                if (deletedItem != null)
                {
                    try
                    {
                        if (System.IO.File.Exists(Path.Combine(Server.MapPath(UPLOADFILE_DIR), deletedItem.RelatedFile.FileName)))
                        {
                            System.IO.File.Delete(Path.Combine(Server.MapPath(UPLOADFILE_DIR), deletedItem.RelatedFile.FileName));
                        }
                    }
                    catch
                    {
                        TempData["Error"] = "Внутрішня помилка, повторіть спробу пізніше";
                        return(RedirectToAction("Tender", "Home"));
                    }

                    itemsCount = (from it in zcrlDbContext.TenderItems where (it.TenderYearId == deletedItem.TenderYearId) select it).Count();

                    int  yearOfDeletedItem = deletedItem.Year.Value;
                    long oldFileId         = deletedItem.UploadFileId;

                    zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = Models.LogRecordType.TendersAddEdit,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> видалив файл <b>{3}</b>", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), deletedItem.RelatedFile.DisplayName)
                    });
                    zcrlDbContext.TenderItems.Remove(deletedItem);
                    zcrlDbContext.SaveChanges();

                    var oldFile = (from f in zcrlDbContext.UploadFiles where (f.Id == oldFileId) select f).FirstOrDefault();
                    if (oldFile != null)
                    {
                        zcrlDbContext.UploadFiles.Remove(oldFile);
                        zcrlDbContext.SaveChanges();
                    }

                    ViewBag.Mode = CrudMode.Delete;
                    TempData["SuccessMessage"] = "Файл успішно видалений!";

                    if (itemsCount > 1)
                    {
                        return(RedirectToAction("Tender", "Home", new { year = yearOfDeletedItem }));
                    }
                    else
                    {
                        return(RedirectToAction("Tender", "Home"));
                    }
                }
                else
                {
                    return(RedirectToAction("Tender", "Home"));
                }
            }
        }
예제 #24
0
        public ActionResult EditTenderItem(TenderItem item, HttpPostedFileBase attachedFile)
        {
            string error = getModelError(item);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                ViewBag.Mode      = CrudMode.Edit;
                return(View("AddEditItem", item));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                var editableTenderItem = (from t in zcrlDbContext.TenderItems
                                          where (t.Id == item.Id) select t).FirstOrDefault();

                if (editableTenderItem != null)
                {
                    ViewBag.Mode = CrudMode.Edit;

                    // Если обновляют загружаемый файл
                    try
                    {
                        if ((attachedFile != null) && (attachedFile.ContentLength > 0))
                        {
                            // Удаляем старый
                            if (System.IO.File.Exists(Path.Combine(Server.MapPath(UPLOADFILE_DIR), editableTenderItem.RelatedFile.FileName)))
                            {
                                System.IO.File.Delete(Path.Combine(Server.MapPath(UPLOADFILE_DIR), editableTenderItem.RelatedFile.FileName));
                            }

                            string newFileName     = Guid.NewGuid().ToString() + Path.GetExtension(attachedFile.FileName);
                            string newFileNamePath = Path.Combine(Server.MapPath(UPLOADFILE_DIR), newFileName);
                            attachedFile.SaveAs(newFileNamePath);
                            editableTenderItem.RelatedFile.FileName = newFileName;

                            zcrlDbContext.SaveChanges();

                            zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                            {
                                СreatedDate = DateTime.Now,
                                RecordType  = Models.LogRecordType.TendersAddEdit,
                                Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> змінив файл <b>{3}</b>", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), editableTenderItem.RelatedFile.DisplayName)
                            });
                            zcrlDbContext.SaveChanges();
                        }
                    }
                    catch
                    {
                        TempData["Error"] = "Помилка завантаження файлу, повторіть спробу пізніше";
                        return(RedirectToAction("AddEditItem", item));
                    }

                    if (editableTenderItem.RelatedFile.DisplayName != item.RelatedFile.DisplayName)
                    {
                        zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                        {
                            СreatedDate = DateTime.Now,
                            RecordType  = Models.LogRecordType.TendersAddEdit,
                            Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> змінив назву файлу <b>{3}</b> на <b>{4}</b>", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), editableTenderItem.RelatedFile.DisplayName, item.RelatedFile.DisplayName)
                        });
                        editableTenderItem.RelatedFile.DisplayName = item.RelatedFile.DisplayName;
                    }

                    //editableTenderItem.PublicationDate = DateTime.Now;
                    editableTenderItem.DataGroupId  = item.DataGroupId;
                    editableTenderItem.TenderYearId = item.TenderYearId;

                    zcrlDbContext.SaveChanges();

                    ViewBag.Mode = CrudMode.Edit;
                    TempData["SuccessMessage"] = "Файл успішно змінений!";

                    return(RedirectToAction("Tender", "Home", new { year = editableTenderItem.Year.Value }));
                }
                else
                {
                    return(RedirectToAction("Tender", "Home"));
                }
            }
        }
예제 #25
0
        public ActionResult Delete(int?id)
        {
            string        redirectActionName  = null;
            string        publicationTypeName = null;
            LogRecordType recordTypeForLog    = LogRecordType.NewsAddEdit;
            string        logAddEditItemName  = null;

            using (zcrlDbContext = new ZcrlContext())
            {
                if (!id.HasValue)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                var requiredPublicationItem = (from n in zcrlDbContext.PortalPublications where (n.Id == id.Value) select n).FirstOrDefault();

                if (requiredPublicationItem != null)
                {
                    switch (requiredPublicationItem.InformationType)
                    {
                    case PublicationType.Article:
                    {
                        if (User.IsInRole("Doctors") && (requiredPublicationItem.Author.UserId != (int)Profile["Id"]))
                        {
                            return(RedirectToAction("AccessError", "Error"));
                        }
                        redirectActionName  = "Articles";
                        publicationTypeName = "Стаття";
                        recordTypeForLog    = LogRecordType.ArticlesAddEdit;
                        logAddEditItemName  = "статтю";
                        break;
                    }

                    case PublicationType.News:
                    {
                        if (User.IsInRole("Doctors"))
                        {
                            return(RedirectToAction("AccessError", "Error"));
                        }
                        redirectActionName  = "News";
                        publicationTypeName = "Новина";
                        recordTypeForLog    = LogRecordType.NewsAddEdit;
                        logAddEditItemName  = "новину";
                        break;
                    }
                    }

                    if (!string.IsNullOrWhiteSpace(requiredPublicationItem.TitleImage))
                    {
                        if (System.IO.File.Exists(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredPublicationItem.TitleImage)))
                        {
                            System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredPublicationItem.TitleImage));
                        }
                    }

                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = recordTypeForLog,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> видалив {3} <b>{4}</b>",
                                                    (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(),
                                                    logAddEditItemName, requiredPublicationItem.Title)
                    });

                    zcrlDbContext.PortalPublications.Remove(requiredPublicationItem);
                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = publicationTypeName + " успішно видалена";
                    return(RedirectToAction(redirectActionName, "Home"));
                }
                else
                {
                    return(RedirectToAction("NotFound", "Error"));
                }
            }
        }
예제 #26
0
        public ActionResult DeleteTitleImg(int?imgId)
        {
            if (!imgId.HasValue)
            {
                return(RedirectToAction("NotFound", "Error"));
            }

            LogRecordType recordTypeForLog   = LogRecordType.NewsAddEdit;
            string        logAddEditItemName = null;

            using (zcrlDbContext = new ZcrlContext())
            {
                var requiredPublication = (from p in zcrlDbContext.PortalPublications
                                           where (p.Id == imgId.Value) select p).FirstOrDefault();

                if (requiredPublication != null)
                {
                    switch (requiredPublication.InformationType)
                    {
                    case PublicationType.Article:
                    {
                        if (User.IsInRole("Doctors") && (requiredPublication.Author.UserId != (int)Profile["Id"]))
                        {
                            return(RedirectToAction("AccessError", "Error"));
                        }
                        recordTypeForLog   = LogRecordType.ArticlesAddEdit;
                        logAddEditItemName = "статті";
                        break;
                    }

                    case PublicationType.News:
                    {
                        if (User.IsInRole("Doctors"))
                        {
                            return(RedirectToAction("AccessError", "Error"));
                        }
                        recordTypeForLog   = LogRecordType.NewsAddEdit;
                        logAddEditItemName = "новини";
                        break;
                    }
                    }

                    try
                    {
                        if (!string.IsNullOrWhiteSpace(requiredPublication.TitleImage))
                        {
                            if (System.IO.File.Exists(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredPublication.TitleImage)))
                            {
                                System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), requiredPublication.TitleImage));
                            }
                        }
                    }
                    catch
                    {
                        TempData["Error"] = "Помилка при видаленні файлу. Спробуйте пізніше.";
                        return(RedirectToAction("Edit", new { id = imgId.Value }));
                    }

                    requiredPublication.TitleImage = null;

                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = recordTypeForLog,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> видалив картинку заголовку {3} <b>{4}</b>",
                                                    (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(),
                                                    logAddEditItemName, requiredPublication.Title)
                    });

                    zcrlDbContext.SaveChanges();

                    TempData["SuccessMessage"] = "Картинка для заголовку видалена!";
                    return(RedirectToAction("Edit", new { id = imgId.Value }));
                }
                else
                {
                    return(RedirectToAction("NotFound", "Error"));
                }
            }
        }
예제 #27
0
        public ActionResult Add(Publication newPublicationItem, HttpPostedFileBase attachedFile, int[] selectedThemes)
        {
            if (User.IsInRole("Doctors") && newPublicationItem.InformationType != PublicationType.Article)
            {
                return(RedirectToAction("AccessError", "Error"));
            }

            if (newPublicationItem.InformationType == PublicationType.Article)
            {
                using (zcrlDbContext = new ZcrlContext())
                {
                    ViewBag.Themes = (from t in zcrlDbContext.PortalDataGroups
                                      where (t.RelatedGroup == DataGroupType.ArticleGroup)
                                      select t).ToList();
                }
            }

            string        redirectActionName  = null;
            string        publicationTypeName = null;
            LogRecordType recordTypeForLog    = LogRecordType.NewsAddEdit;
            string        logAddEditItemName  = null;

            string error = getModelError(newPublicationItem);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                ViewBag.Mode      = CrudMode.Add;
                ViewBag.Title     = getTitleForPage(newPublicationItem.InformationType, CrudMode.Add);
                return(View("AddEditItem", newPublicationItem));
            }
            if (!attachedFile.IsImage() && attachedFile != null)
            {
                TempData["Error"] = "Невірний формат зображення для заголовку";
                ViewBag.Mode      = CrudMode.Add;
                ViewBag.Title     = getTitleForPage(newPublicationItem.InformationType, CrudMode.Add);
                return(View("AddEditItem", newPublicationItem));
            }

            // Получаем максимально допустимую длинну заголовка новости
            System.ComponentModel.DataAnnotations.MaxLengthAttribute[] maxLengthAttribs = Attribute.GetCustomAttributes(typeof(Publication).GetProperty("Title"),
                                                                                                                        typeof(System.ComponentModel.DataAnnotations.MaxLengthAttribute)) as System.ComponentModel.DataAnnotations.MaxLengthAttribute[];
            int maxTitleLength = maxLengthAttribs.Length > 0 ? maxLengthAttribs.Last().Length : 0;

            if ((maxTitleLength > 0) && (newPublicationItem.Title.Length > maxTitleLength))
            {
                TempData["Error"] = "Максимально допустима довжина заголовку " + maxTitleLength + " символів";
                ViewBag.Mode      = CrudMode.Add;
                ViewBag.Title     = getTitleForPage(newPublicationItem.InformationType, CrudMode.Add);
                return(View("AddEditItem", newPublicationItem));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                if (attachedFile != null)
                {
                    try
                    {
                        string uploadImgName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(attachedFile.FileName);
                        string uploadImgPath = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), uploadImgName);

                        attachedFile.SaveAs(uploadImgPath);
                        newPublicationItem.TitleImage = uploadImgName;
                    }
                    catch
                    {
                        TempData["Error"] = "Помилка завантаження зображення";
                        ViewBag.Mode      = CrudMode.Add;
                        ViewBag.Title     = getTitleForPage(newPublicationItem.InformationType, CrudMode.Add);
                        return(View("AddEditItem", newPublicationItem));
                    }
                }

                newPublicationItem.PublicationDate = DateTime.Now;
                newPublicationItem.Title           = newPublicationItem.Title.Trim();

                zcrlDbContext.PortalPublications.Add(newPublicationItem);

                if ((newPublicationItem.InformationType == PublicationType.Article) && (selectedThemes != null))
                {
                    newPublicationItem.Themes.Clear();
                    foreach (int theme in selectedThemes)
                    {
                        var requiredTheme = (from t in zcrlDbContext.PortalDataGroups
                                             where ((t.RelatedGroup == DataGroupType.ArticleGroup) && (t.Id == theme))
                                             select t).FirstOrDefault();
                        if (requiredTheme != null)
                        {
                            newPublicationItem.Themes.Add(requiredTheme);
                        }
                    }
                }

                zcrlDbContext.SaveChanges();


                switch (newPublicationItem.InformationType)
                {
                case PublicationType.Article:
                {
                    redirectActionName  = "Articles";
                    publicationTypeName = "Стаття";
                    recordTypeForLog    = LogRecordType.ArticlesAddEdit;
                    logAddEditItemName  = "статтю";
                    break;
                }

                case PublicationType.News:
                {
                    redirectActionName  = "News";
                    publicationTypeName = "Новина";
                    recordTypeForLog    = LogRecordType.NewsAddEdit;
                    logAddEditItemName  = "новину";
                    break;
                }
                }

                zcrlDbContext.LogJournal.Add(new LogRecord()
                {
                    СreatedDate = DateTime.Now, RecordType = recordTypeForLog,
                    Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> додав нову {3} <b>{4}</b>",
                                                (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(),
                                                logAddEditItemName, newPublicationItem.Title)
                });

                zcrlDbContext.SaveChanges();

                TempData["SuccessMessage"] = publicationTypeName + " успішно створена";
                return(RedirectToAction(redirectActionName, "Home"));
            }
        }
예제 #28
0
        public ActionResult AddTenderItem(TenderItem item, HttpPostedFileBase attachedFile)
        {
            using (zcrlDbContext = new ZcrlContext())
            {
                string error = getModelError(item);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    TempData["Error"]  = error;
                    ViewBag.Mode       = CrudMode.Add;
                    ViewBag.GroupsList = (from tg in zcrlDbContext.PortalDataGroups
                                          where (tg.RelatedGroup == DataGroupType.TenderGroup)
                                          select new ZcrlPortal.ViewModels.SelectListItem()
                    {
                        DisplayName = tg.Name, Value = tg.Id
                    }).ToList();
                    ViewBag.YearsList = (from y in zcrlDbContext.TenderYears
                                         select new ZcrlPortal.ViewModels.SelectListItem()
                    {
                        DisplayName = y.Value.ToString(), Value = y.Id
                    }).ToList();
                    return(View("AddEditItem", item));
                }
                if (!attachedFile.isValidFile())
                {
                    TempData["Error"]  = "Невірний формат файлу";
                    ViewBag.Mode       = CrudMode.Add;
                    ViewBag.GroupsList = (from tg in zcrlDbContext.PortalDataGroups
                                          where (tg.RelatedGroup == DataGroupType.TenderGroup)
                                          select new ZcrlPortal.ViewModels.SelectListItem()
                    {
                        DisplayName = tg.Name, Value = tg.Id
                    }).ToList();
                    ViewBag.YearsList = (from y in zcrlDbContext.TenderYears
                                         select new ZcrlPortal.ViewModels.SelectListItem()
                    {
                        DisplayName = y.Value.ToString(), Value = y.Id
                    }).ToList();
                    return(View("AddEditItem", item));
                }

                try
                {
                    string newFileName     = Guid.NewGuid().ToString() + Path.GetExtension(attachedFile.FileName);
                    string newFileNamePath = Path.Combine(Server.MapPath(UPLOADFILE_DIR), newFileName);
                    attachedFile.SaveAs(newFileNamePath);
                    UploadFile newFile = new UploadFile()
                    {
                        FileName      = newFileName,
                        DisplayName   = item.RelatedFile.DisplayName,
                        UserProfileId = item.RelatedFile.UserProfileId,
                        FileType      = UploadFileType.TenderUpload
                    };
                    zcrlDbContext.UploadFiles.Add(newFile);
                    zcrlDbContext.SaveChanges();
                }
                catch
                {
                    TempData["Error"] = "Помилка завантаження файлу, повторіть спробу пізніше";
                    return(RedirectToAction("AddEditItem", item));
                }

                item.UploadFileId = (from f in zcrlDbContext.UploadFiles
                                     where (f.UserProfileId == item.RelatedFile.UserProfileId)
                                     orderby f.Id ascending
                                     select f).ToList().Last().Id;
                item.PublicationDate = DateTime.Now;
                item.RelatedFile     = null;

                zcrlDbContext.TenderItems.Add(item);
                zcrlDbContext.SaveChanges();

                zcrlDbContext.LogJournal.Add(new ZcrlPortal.Models.LogRecord()
                {
                    СreatedDate = DateTime.Now,
                    RecordType  = Models.LogRecordType.TendersAddEdit,
                    Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> додав файл <b>{3}</b>", (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(), item.RelatedFile.DisplayName)
                });
                zcrlDbContext.SaveChanges();

                ViewBag.Mode = CrudMode.Add;
                TempData["SuccessMessage"] = "Файл успішно доданий!";

                int redirectTenderYear = (from y in zcrlDbContext.TenderYears
                                          where (y.Id == item.TenderYearId) select y).First().Value;

                return(RedirectToAction("Tender", "Home", new { year = redirectTenderYear }));
            }
        }
예제 #29
0
        public ActionResult Edit(Publication newPublicationItem, HttpPostedFileBase attachedFile, int[] selectedThemes)
        {
            string        publicationTypeName = null;
            LogRecordType recordTypeForLog    = LogRecordType.NewsAddEdit;
            string        logAddEditItemName  = null;

            if (newPublicationItem.InformationType == PublicationType.Article)
            {
                using (zcrlDbContext = new ZcrlContext())
                {
                    ViewBag.Themes = (from t in zcrlDbContext.PortalDataGroups
                                      where (t.RelatedGroup == DataGroupType.ArticleGroup)
                                      select t).ToList();
                }
            }

            string error = getModelError(newPublicationItem);

            if (!string.IsNullOrWhiteSpace(error))
            {
                TempData["Error"] = error;
                ViewBag.Mode      = CrudMode.Edit;
                ViewBag.Title     = getTitleForPage(newPublicationItem.InformationType, CrudMode.Edit);
                return(View("AddEditItem", newPublicationItem));
            }

            using (zcrlDbContext = new ZcrlContext())
            {
                Publication editablePublication = (from p in zcrlDbContext.PortalPublications
                                                   where (p.Id == newPublicationItem.Id)
                                                   select p).FirstOrDefault();
                if (editablePublication == null)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }

                // Отсеиваем ненужные роли
                switch (newPublicationItem.InformationType)
                {
                case PublicationType.Article:
                {
                    if (User.IsInRole("Doctors") && (editablePublication.Author.UserId != (int)Profile["Id"]))
                    {
                        return(RedirectToAction("AccessError", "Error"));
                    }
                    publicationTypeName = "Стаття";
                    recordTypeForLog    = LogRecordType.ArticlesAddEdit;
                    logAddEditItemName  = "статті";
                    break;
                }

                case PublicationType.News:
                {
                    if (User.IsInRole("Doctors"))
                    {
                        return(RedirectToAction("AccessError", "Error"));
                    }
                    publicationTypeName = "Новина";
                    recordTypeForLog    = LogRecordType.NewsAddEdit;
                    logAddEditItemName  = "новини";
                    break;
                }

                default:
                {
                    return(RedirectToAction("AccessError", "Error"));
                }
                }

                if (attachedFile.IsImage())
                {
                    try
                    {
                        string uploadImgName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(attachedFile.FileName);
                        string uploadImgPath = System.IO.Path.Combine(Server.MapPath(UPLOADFILE_DIR), uploadImgName);

                        attachedFile.SaveAs(uploadImgPath);
                        editablePublication.TitleImage = uploadImgName;

                        zcrlDbContext.LogJournal.Add(new LogRecord()
                        {
                            СreatedDate = DateTime.Now,
                            RecordType  = recordTypeForLog,
                            Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> змінив картинку заголовку {3} <b>{4}</b>",
                                                        (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(),
                                                        logAddEditItemName, editablePublication.Title)
                        });
                        zcrlDbContext.SaveChanges();
                    }
                    catch
                    {
                        TempData["Error"] = "Помилка завантаження зображення, повторіть спробу пізніше";
                        ViewBag.Title     = getTitleForPage(editablePublication.InformationType, CrudMode.Edit);
                        return(View(editablePublication));
                    }
                }

                if (editablePublication.Title != newPublicationItem.Title.Trim())
                {
                    zcrlDbContext.LogJournal.Add(new LogRecord()
                    {
                        СreatedDate = DateTime.Now,
                        RecordType  = recordTypeForLog,
                        Content     = string.Format("Користувач <b>{0} {1}.{2}.</b> змінив заголовок {3} <b>{4}</b> на <b>{5}</b>",
                                                    (string)Profile["LastName"], ((string)Profile["FirstName"]).First(), ((string)Profile["MiddleName"]).First(),
                                                    logAddEditItemName, editablePublication.Title, newPublicationItem.Title)
                    });
                }

                editablePublication.Title   = newPublicationItem.Title.Trim();
                editablePublication.Content = newPublicationItem.Content;
                editablePublication.Summary = newPublicationItem.Summary;

                if ((editablePublication.InformationType == PublicationType.Article) && (selectedThemes != null))
                {
                    editablePublication.Themes.Clear();
                    foreach (int theme in selectedThemes)
                    {
                        var requiredTheme = (from t in zcrlDbContext.PortalDataGroups
                                             where ((t.RelatedGroup == DataGroupType.ArticleGroup) && (t.Id == theme))
                                             select t).FirstOrDefault();
                        if (requiredTheme != null)
                        {
                            editablePublication.Themes.Add(requiredTheme);
                        }
                    }
                }

                zcrlDbContext.SaveChanges();

                TempData["SuccessMessage"] = publicationTypeName + " успішно змінена";
                return(RedirectToAction("PublicationDetails", "Home", new { id = editablePublication.Id }));
            }
        }
예제 #30
0
        public ActionResult ChangePassword(int id, string oldPass, string newPass, string confirmNewPass)
        {
            int editorId = int.Parse(Profile["Id"].ToString());

            using (zcrlDbContext = new ZcrlContext())
            {
                ZcrlPortal.Models.UserProfile requiredProfile = (from p in zcrlDbContext.Profiles
                                                                 where (p.Id == id)
                                                                 select p).FirstOrDefault();

                ZcrlPortal.SecurityProviders.ZcrlMembershipProvider prov = new SecurityProviders.ZcrlMembershipProvider();

                if (requiredProfile == null)
                {
                    return(RedirectToAction("ChangePassword"));
                }

                if (User.IsInRole("Administrators"))
                {
                    if ((newPass == confirmNewPass) && (!string.IsNullOrEmpty(newPass) && !string.IsNullOrEmpty(confirmNewPass)))
                    {
                        prov.ChangePasswordByAdmin(requiredProfile.RelatedUser.Login, newPass);
                        TempData["Success"] = true;

                        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())
                        });
                        zcrlDbContext.SaveChanges();

                        return(RedirectToAction("EditProfile", new { id = requiredProfile.Id }));
                    }
                    else
                    {
                        TempData["Error"] = "Паролі не співпадають або ви не заповнили якесь поле";
                        return(RedirectToAction("ChangePassword"));
                    }
                }
                else
                {
                    if (editorId != requiredProfile.Id)
                    {
                        return(RedirectToAction("ChangePassword"));
                    }
                    else
                    {
                        // Проверяем правильный ли старый пароль
                        if (prov.ValidateUser(requiredProfile.RelatedUser.Login, oldPass))
                        {
                            if ((newPass == confirmNewPass) && (!string.IsNullOrEmpty(newPass) && !string.IsNullOrEmpty(confirmNewPass)))
                            {
                                prov.ChangePassword(requiredProfile.RelatedUser.Login, oldPass, newPass);

                                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())
                                });
                                zcrlDbContext.SaveChanges();

                                TempData["Success"] = true;
                                return(RedirectToAction("EditProfile"));
                            }
                            else
                            {
                                TempData["Error"] = "Паролі не співпадають або ви не заповнили якесь поле";
                                return(RedirectToAction("ChangePassword"));
                            }
                        }
                        else
                        {
                            TempData["Error"] = "Старий пароль не вірний";
                            return(RedirectToAction("ChangePassword"));
                        }
                    }
                }
            }
        }