public ActionResult AddNews(News getNews)
 {
     if(ModelState.IsValid == true)
     { 
         DiplomEntities5 dc = new DiplomEntities5();
         dc.News.Add(getNews);
         dc.SaveChanges();
         getNews = null;
         ViewBag.Message = "Новость успешно опубликована";
     }
     return View(getNews);
 }
 public ActionResult MessagesStaff(Messages newMessage)
 {
     using (DiplomEntities5 dc = new DiplomEntities5())
     {
         if (ModelState.IsValid == true)
         {
             dc.Messages.Add(newMessage);
             dc.SaveChanges();
             ModelState.Clear();
             newMessage = null;
         }
     }
     return View(newMessage);
 }
 public ActionResult SaveChangesApp(List<Applications> getChanges)
 {
     DiplomEntities5 dc = new DiplomEntities5();
     foreach(Applications app in getChanges)
     {
         if(app.isRead == 0)
         { 
             var appToChange = dc.Applications.Where(a => a.Id.Equals(app.Id)).FirstOrDefault();
             appToChange.isConfirmed = app.isConfirmed;
             appToChange.DateOfRead = DateTime.Now;
             appToChange.isRead = 1;
             appToChange.Reader = Session["LogedUserSname"].ToString() + " " + Session["LogedUserName"].ToString().First() + ". " + Session["LogedUserPname"].ToString().First(); 
             dc.SaveChanges();
         }
     }
     ViewBag.Message = "Изменения успешно сохранены";
     int course = Convert.ToInt32(Session["CourseApp"]);
     int group = Convert.ToInt32(Session["GroupApp"]);
     var Group = dc.Applications.Where(a => a.Users.Group == group &&
                                         a.Users.Course == course).OrderByDescending(a => a.Id).ToList<Applications>();
     return View("ViewApplications", Group);
 }
 public ActionResult Appliance(ApplicationView getApp)
 {
     Applications newApp = new Applications();
     newApp.StudentId = Convert.ToInt32(Session["LogedUserId"].ToString());
     newApp.Head = "Декану факультета инновационной подготовки Зеневич А. М. ";
     if(getApp.isMale == 1)
     {
         newApp.Head += "Студента ";
     }
     else
     {
         newApp.Head += "Студентки ";
     }
     newApp.Head += Session["LogedUserCourse"].ToString();
     newApp.Head += " курса дневной формы обучения ";
     newApp.Head += "специальности управление информационными ресурсами ";
     newApp.Head += "Института управленческих кадров";
     newApp.Reason = getApp.Reason;
     newApp.isRead = 0;
     newApp.DateOfCreation = DateTime.Now;
     newApp.DateOfMiss = getApp.DateOfMiss;
     DiplomEntities5 dc = new DiplomEntities5();
     dc.Applications.Add(newApp);
     dc.SaveChanges();
     ViewBag.Message = "Заявление успешно отправлено.";
     ViewBag.NumAllowApp = NumAllowedApp();
     return View();
 }
        public ActionResult Index(LogedUser user)
        {
            using(DiplomEntities5 dc = new DiplomEntities5())
            {
                if(ModelState.IsValid)
                { 
                    var v = dc.Users.Where(a => a.Login.Equals(user.Login) && a.Password.Equals(user.Password)).FirstOrDefault();
                    if(v != null)
                    {
                        
                        if ((v.RoleId == 1 || v.RoleId == 2) && v.RoleId != 7
                            ) { 
                            //Itterate number of user course
                            DateTime now = DateTime.Now;
                            int CountCourseInDb = now.Year - (Convert.ToInt32(v.Login.ToString().Substring(0, 2)) + 2000);
                            int CourseValueDb = Convert.ToInt32(v.Course);

                            if (now.Month >= 9)
                            {
                                CountCourseInDb++;
                            }
                            if (CountCourseInDb != CourseValueDb)
                            {
                                v.Course = CountCourseInDb;
                                if (CountCourseInDb == 5)
                                {
                                    v.RoleId = 7;
                                }
                                dc.SaveChanges();
                                Session["NewCourse"] = 1;
                                
                            }
                        }

                        if (v.RoleId == 7)
                        {
                            ViewBag.Message = "Вы отчислены из университета. Доступ закрыт";
                            return View(user);
                        }
                        if (v.RoleId == 4)
                        {
                            DateTime now = DateTime.Now;
                            int numStud = 0;
                            int numStudToBeRased = 0;
                            foreach(Users student in dc.Users)
                            { 
                                //If there is October now or late, skip this function
                                if (now.Month != 9)
                                {
                                    dc.Utility.Where(a => a.Id.Equals(3)).FirstOrDefault().Limit = 0;
                                    break;
                                }
                                if(student.RoleId == 1 || student.RoleId == 2)
                                {
                                    numStud++;
                                    int CountCourseInDb = now.Year - (Convert.ToInt32(student.Login.ToString().Substring(0, 2)) + 2000);
                                    int CourseValueDb = Convert.ToInt32(student.Course);

                                    if (now.Month >= 9)
                                    {
                                        CountCourseInDb++;
                                    }
                                    if (CountCourseInDb != CourseValueDb)
                                    {
                                        numStudToBeRased++;
                                    }
                                }
                            }
                            Session["NumStudent"] = numStud;
                            Session["NumStudentToRase"] = numStudToBeRased;
                            int isNewYear = dc.Utility.Where(a => a.Id.Equals(3)).FirstOrDefault().Limit;
                            if(isNewYear == 0 && now.Month == 9)
                            {
                                Session["NewStudYear"] = 1;
                            }
                            
                        }
                        Session["LogedUserId"] = v.UserId.ToString();
                        Session["LogedUserName"] = v.Name.ToString();
                        Session["LogedUserSname"] = v.Sirname.ToString();
                        Session["LogedUserPname"] = v.Patername.ToString();
                        Session["LogedUserRole"] = v.RoleId.ToString();
                        Session["LogedUserGroup"] = v.Group.ToString();
                        Session["LogedUserCourse"] = v.Course.ToString();
                        return RedirectPermanent("Profile/Index");
                    }
                    else
                    {
                        ViewBag.Message = "Ошибка авторизации";
                    }
                }
                
            }
            return View(user);
        }
 public ActionResult EditGroup(List<Users> getStudent)
 {
     DiplomEntities5 dc = new DiplomEntities5();
     foreach (Users stud in getStudent)
     {
         var DbStud = dc.Users.Where(a => a.UserId.Equals(stud.UserId)).FirstOrDefault();
         if (!DbStud.RoleId.Equals(stud.RoleId))
         {
             DbStud.RoleId = stud.RoleId;
         }
     }
     ViewBag.Message = "Изменения успешно сохранены";
     dc.SaveChanges();
     if(Session["NumGroup"].ToString().Equals("1"))
     {
         return Redirect("~/Profile/GroupOneMethodist");
     }
     else if (Session["NumGroup"].ToString().Equals("2"))
     {
         return Redirect("~/Profile/GroupTwoMethodist");
     }
     else if (Session["NumGroup"].ToString().Equals("3"))
     {
         return Redirect("~/Profile/GroupThreeMethodist");
     }
     return null;
 }
        public ActionResult Erase()
        {
            DiplomEntities5 dc = new DiplomEntities5();

            foreach (Missings item in dc.Missings)
            {
                dc.Missings.Remove(item);
            }

            foreach (Applications item in dc.Applications)
            {
                dc.Applications.Remove(item);
            }

            foreach (News item in dc.News)
            {
                dc.News.Remove(item);
            }

            foreach (Changes item in dc.Changes)
            {
                dc.Changes.Remove(item);
            }

            dc.Utility.Where(a => a.Id.Equals(3)).FirstOrDefault().Limit = 1;
            dc.SaveChanges();
            
            return View("Methodist");
        }
 public ActionResult Changes()
 {
     if(Session["LogedUserRole"].ToString().Equals("4"))
     {
         return Redirect("~/Profile/ChangesForMethodist");
     }
     DiplomEntities5 dc = new DiplomEntities5();
     foreach(Changes item in dc.Changes)
     {
         if(item.isRead == 0 && item.UserId.ToString().Equals(Session["LogedUserId"].ToString()))
         {
             item.isRead = 1;
         }
     }
     dc.SaveChanges();
     ViewBag.chan = dc.Changes.OrderByDescending(a => a.Id);
     return View();
 }
 public ActionResult SetLim()
 {
     try
     {
         int numAppInWeek = Convert.ToInt32(Request["numApp"]);
         DiplomEntities5 dc = new DiplomEntities5();
         var Row = dc.Utility.Where(a => a.Id.Equals(2)).FirstOrDefault();
         Row.Limit = numAppInWeek;
         dc.SaveChanges();
     }
     catch
     {
         goto metka;
     }
     metka:
     string num = Session["GroupApp"].ToString();
     if (Session["GroupApp"].ToString().Equals("1"))
     {
         return View("ViewApplications",GetAppOfGroup(1));
     }
     else if (Session["GroupApp"].ToString().Equals("2"))
     {
         return View("ViewApplications", GetAppOfGroup(2));
     }
     else if (Session["GroupApp"].ToString().Equals("3"))
     {
         return View("ViewApplications", GetAppOfGroup(3));
     }
     return null;
 }
 public ActionResult SetLimMiss()
 {
     try { 
     int numMissInMonth = Convert.ToInt32(Request["numMiss"]);
     DiplomEntities5 dc = new DiplomEntities5();
     var Row = dc.Utility.Where(a => a.Id.Equals(1)).FirstOrDefault();
     Row.Limit = numMissInMonth;
     dc.SaveChanges();
     }
     catch { 
         return Redirect("MonthReportForZDean");
     }
     return Redirect("MonthReportForZDean");
 }
        public ActionResult Rase()
        {
            DateTime now = DateTime.Now;
            DiplomEntities5 dc = new DiplomEntities5();

            foreach (Users student in dc.Users)
            {
                if (student.RoleId == 1 || student.RoleId == 2)
                {
                    int year = Convert.ToInt32(student.Login.ToString().Substring(0, 2));
                    int CountCourseInDb = now.Year - (year + 2000);
                    int CourseValueDb = Convert.ToInt32(student.Course);

                    if (now.Month >= 9)
                    {
                        CountCourseInDb++;
                    }
                    if (CountCourseInDb != CourseValueDb)
                    {
                        if (CountCourseInDb == 5)
                        {
                            student.RoleId = 7;
                        }
                        else
                        {
                            student.Course = CountCourseInDb;
                        }
                    }
                }
            }
            dc.SaveChanges();
            return View("Methodist");
        }
 public ActionResult ChangeAvatar(HttpPostedFileBase NewAvatar)
 {
     if(NewAvatar != null)
     {
         DiplomEntities5 dc = new DiplomEntities5();
         MemoryStream memory = new MemoryStream();
         
         string fileName = System.IO.Path.GetFileName(NewAvatar.FileName);
         NewAvatar.SaveAs(Server.MapPath("~/Content/Avatars/" + fileName));
         NewAvatar.InputStream.CopyTo(memory);
         int userId = Convert.ToInt32(Session["LogedUserId"]);
         var UserToSave = dc.Users.Where(a => a.UserId.Equals(userId)).FirstOrDefault();
         UserToSave.Avatar = memory.GetBuffer();
         dc.SaveChanges();
     }
     return Redirect("~/Profile/Index");
 }
        public ActionResult RegisterDean(RegDean FormRegUser, HttpPostedFileBase Avatar)
        {
            using (DiplomEntities5 dc = new DiplomEntities5())
            {
                var anyUserEmail = dc.Users.Any(a => a.Email.Equals(FormRegUser.Email));
                if (anyUserEmail)
                {
                    ModelState.AddModelError("Email", "Пользователь с таким email уже зарегистрирован");
                }

                var anyUserLogin = dc.Users.Any(a => a.Login.Equals(FormRegUser.Login));
                if (anyUserLogin)
                {
                    ModelState.AddModelError("Login", "Пользователь с таким логином уже зарегистрирован");
                }
                if (FormRegUser.Captcha != (string)Session[CaptchaImage.CaptchaValueKey])
                {
                    ModelState.AddModelError("Captcha", "Текст с картинки введён не верно");
                    return View(FormRegUser);
                }
                if (ModelState.IsValid == true)
                {
                    MemoryStream memory = new MemoryStream();
                    if (Avatar == null)
                    {
                        Bitmap avatar = new Bitmap(Server.MapPath("~/Content/Avatars/default_avatar.gif"));
                        avatar.Save(memory, ImageFormat.Gif);
                    }
                    else
                    {
                        string fileName = System.IO.Path.GetFileName(Avatar.FileName);
                        Avatar.SaveAs(Server.MapPath("~/Content/Avatars/" + fileName));
                        Avatar.InputStream.CopyTo(memory);
                    }
                    Users UserToSave = new Users();
                    UserToSave.Name = FormRegUser.Name;
                    UserToSave.Sirname = FormRegUser.Sirname;
                    UserToSave.Patername = FormRegUser.Patername;
                    UserToSave.Password = FormRegUser.Password;
                    UserToSave.RoleId = FormRegUser.RoleId;
                    UserToSave.Group = FormRegUser.Group;
                    UserToSave.Login = FormRegUser.Login;
                    UserToSave.Course = FormRegUser.Course;
                    UserToSave.Email = FormRegUser.Email;
                    UserToSave.Avatar = memory.GetBuffer();
                    UserToSave.Birthday = FormRegUser.Birthday;
                    dc.Users.Add(UserToSave);
                    dc.SaveChanges();
                    ModelState.Clear();
                    FormRegUser = null;
                    ViewBag.Message = "Регистрация прошла успешно";
                }
            }
            return View(FormRegUser);
        }
 public ActionResult AddMiss(AddMiss getMiss)
 {
     if(ModelState.IsValid == true)
     {
         DiplomEntities5 dc = new DiplomEntities5();
         Missings newRow = new Missings();
         newRow.StudentId = getMiss.StudentId;
         newRow.Form = getMiss.Form;
         newRow.Discipline = getMiss.Discipline;
         newRow.IsRead = getMiss.IsRead;
         newRow.IsValid = getMiss.IsValid;
         newRow.Date = getMiss.Date;
         dc.Missings.Add(newRow);
         dc.SaveChanges();
         ViewBag.Message = "Запись добавлена";
         getMiss = null;
     }
     return View(getMiss);
     
 }
 public ActionResult DeleteMiss()
 {
     int Id = Convert.ToInt32(Request["id"]);
     DiplomEntities5 dc = new DiplomEntities5();
     Missings RowToDel = dc.Missings.Where(a => a.Id.Equals(Id)).FirstOrDefault();
     dc.Missings.Remove(RowToDel);
     dc.SaveChanges();
     return View("MissForPraepostor");
 }
 public ActionResult EditNews(List<News> getChanges)
 {
     DiplomEntities5 dc = new DiplomEntities5();
     foreach(News item in getChanges)
     {
         var DbItem = dc.News.Where(a => a.Id.Equals(item.Id)).FirstOrDefault();
         if(DbItem != item)
         {
             DbItem.Title = item.Title;
             DbItem.Content = item.Content;
             DbItem.Date = item.Date;
             dc.SaveChanges();
         }
     }
     string mess = "Изменения успешно сохранены";
     return Redirect("~/Profile/Methodist?Message=" + mess);
 }
 public ActionResult EditMiss(List<Missings> getChanges)
 {
     DiplomEntities5 dc = new DiplomEntities5();
     foreach (Missings miss in getChanges)
     {
         var DbMiss = dc.Missings.Where(a => a.Id.Equals(miss.Id)).FirstOrDefault();
         if (!DbMiss.IsValid.Equals(miss.IsValid))
         {
             DbMiss.IsValid = miss.IsValid;
         }
     }
     ViewBag.Message = "Изменения успешно сохранены";
     dc.SaveChanges();
     List<Missings> MissingDb = new List<Missings>();
     foreach (HtmlInputs.Models.Missings item in dc.Missings.OrderByDescending(a => a.Id))
     {
         if (item.Users.Group.ToString().Equals(Session["LogedUserGroup"].ToString()) && item.Users.Course.ToString().Equals(Session["LogedUserCourse"].ToString()))
         {
             MissingDb.Add(item);
         }
     }
     return View(MissingDb);
 }
 public ActionResult AddChanges(Changes getChanges)
 {
     DiplomEntities5 dc = new DiplomEntities5();
     List<Changes> RecordSet = new List<Changes>();
     foreach(Users item in dc.Users)
     {
         if(item.RoleId == 1 || item.RoleId == 2 || item.RoleId == 4)
         {
             var obj = new Changes();
             obj.UserId = item.UserId;
             if(item.RoleId != 4)
             { 
                 obj.isRead = 0;
             }
             else
             {
                 obj.isRead = 1;
             }
             obj.Date = DateTime.Now;
             obj.Content = getChanges.Content;
             RecordSet.Add(obj);
         }
     }
     foreach(Changes item in RecordSet)
     {
         dc.Changes.Add(item);
         dc.SaveChanges();
     }
     getChanges = null;
     ViewBag.Message = "Изменение успешно опубликовано";
     return View(getChanges);
 }
        public ActionResult Register(RegUser FormRegUser, HttpPostedFileBase Avatar)
        {
            using (DiplomEntities5 dc = new DiplomEntities5())
            {
                var anyUserEmail = dc.Users.Any(a => a.Email.Equals(FormRegUser.Email));
                if (anyUserEmail)
                {
                    ModelState.AddModelError("Email", "Пользователь с таким email уже зарегистрирован");
                }

                var anyUserLogin = dc.Users.Any(a => a.Login.Equals(FormRegUser.Login));
                if (anyUserLogin)
                {
                    ModelState.AddModelError("Login", "Пользователь с таким логином уже зарегистрирован");
                }
                if (FormRegUser.Captcha != (string)Session[CaptchaImage.CaptchaValueKey])
                {
                    ModelState.AddModelError("Captcha", "Текст с картинки введён не верно");
                    return View(FormRegUser);
                }

                DateTime now = DateTime.Now;
                int RegUserCourse = now.Year - (Convert.ToInt32(FormRegUser.Login.ToString().Substring(0, 2)) + 2000);
                foreach (Users student in dc.Users)
                {
                    int yearFromLogin = Convert.ToInt32(student.Login.ToString().Substring(0, 2));
                    if ((yearFromLogin != RegUserCourse) && (FormRegUser.Course == student.Course))
                    {
                        ModelState.AddModelError("Login", "Ошибка системы. Для решения проблемы обратитесь к методисту");
                        return View(FormRegUser);
                    }
                }
                if(ModelState.IsValid == true)
                {
                    

                    MemoryStream memory = new MemoryStream();
                    if (Avatar == null)
                    {
                        Bitmap avatar = new Bitmap(Server.MapPath("~/Content/Avatars/default_avatar.gif"));
                        avatar.Save(memory, ImageFormat.Gif);
                    }
                    else
                    {
                        string fileName = System.IO.Path.GetFileName(Avatar.FileName);
                        Avatar.SaveAs(Server.MapPath("~/Content/Avatars/" + fileName));
                        Avatar.InputStream.CopyTo(memory);
                    }
                    Users UserToSave = new Users();
                    UserToSave.Name = FormRegUser.Name;
                    UserToSave.Sirname = FormRegUser.Sirname;
                    UserToSave.Patername = FormRegUser.Patername;
                    UserToSave.Password = FormRegUser.Password;
                    UserToSave.RoleId = FormRegUser.RoleId;
                    UserToSave.Group = FormRegUser.Group;
                    UserToSave.Login = FormRegUser.Login;
                    UserToSave.Course = FormRegUser.Course;
                    UserToSave.Email = FormRegUser.Email;
                    UserToSave.Avatar = memory.GetBuffer();
                    UserToSave.Birthday = FormRegUser.Birthday;
                        dc.Users.Add(UserToSave);
                        dc.SaveChanges();
                        ModelState.Clear();
                        FormRegUser = null;
                        ViewBag.Message = "Регистрация прошла успешно";
                }
            }
            return View(FormRegUser);
        }