Example #1
0
        protected void LinkButtonEmptyLectureInsert_Click(object sender, EventArgs e)
        {
            int      courseId        = Convert.ToInt32(this.RouteData.Values["courseId"]);
            var      table           = (sender as LinkButton).Parent;
            string   title           = (table.FindControl("TextBoxEmptyLectureTitleInsert") as TextBox).Text;
            string   description     = (table.FindControl("TextBoxEmptyLectureLocationInsert") as TextBox).Text;
            string   location        = (table.FindControl("TextBoxEmptyLectureLocationInsert") as TextBox).Text;
            DateTime homeworkDueDate = DateTime.Parse((table.FindControl("TextBoxEmptyHomeworkDue") as TextBox).Text);

            var context = new AcademyDbContext();
            var course  = context.Courses.Find(courseId);
            var lecture = new Forum.Models.Lecture()
            {
                Title           = title,
                Location        = location,
                HomeworkDueDate = homeworkDueDate
            };

            context.Lectures.Add(lecture);
            try
            {
                context.SaveChanges();
                lecture.Course = course;
                context.SaveChanges();
                ErrorSuccessNotifier.AddSuccessMessage("Lecture created successfully.");
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }

            this.GridViewLectures.SelectMethod = "GridViewLectures_GetData";
            this.GridViewLectures.DataBind();
        }
        public void DeleteById(int id)
        {
            Project project = _context.Projects.FirstOrDefault(x => x.Id == id);

            if (project != null)
            {
                _context.Projects.Remove(project);
            }
            _context.SaveChanges();
        }
Example #3
0
        public void DeleteById(int id)
        {
            Student student = _context.Students.FirstOrDefault(x => x.Id == id);

            if (student != null)
            {
                _context.Students.Remove(student);
            }
            _context.SaveChanges();
        }
Example #4
0
        public ActionResult Create([Bind(Include = "StudentId,FirstName,LastName,EmailAddress,PhoneNum")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Student.Add(student);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(student));
        }
        public ActionResult Create([Bind(Include = "UserId,FirstName,LastName,EmailAddress,PhoneNum,Password,Role")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(user));
        }
        public ActionResult Create([Bind(Include = "InstructorId,FirstName,LastName,EmailAddress,PhoneNum")] Instructor instructor)
        {
            if (ModelState.IsValid)
            {
                db.Instructors.Add(instructor);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(instructor));
        }
        public void Create(CreateCourseCategoryDto dto)
        {
            var entity = new CourseCategory()
            {
                ParentCategoryId = dto.ParentId,
                Title            = dto.Title
            };

            _dbContext.CourseCategories.Add(entity);
            _dbContext.SaveChanges();
        }
Example #8
0
        public ActionResult Create([Bind(Include = "CourseId,Name,Address,X,Y,Description,StartDate,EndDate,InstructorId")] Course course)
        {
            if (ModelState.IsValid)
            {
                db.Courses.Add(course);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(course));
        }
Example #9
0
        public ActionResult Create([Bind(Include = "CourseId,Name,Address,Description,StartDate,EndDate,InstructorId")] Course course)
        {
            if (ModelState.IsValid)
            {
                db.Courses.Add(course);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.InstructorId = new SelectList(db.Instructors, "InstructorId", "FirstName", course.InstructorId);
            return(View(course));
        }
Example #10
0
        public void GridViewLectures_DeleteItem(int id)
        {
            var context = new AcademyDbContext();

            Forum.Models.Lecture item = context.Lectures.Find(id);
            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                ErrorSuccessNotifier.AddErrorMessage("The lecture was not found.");
                return;
            }

            try
            {
                context.Lectures.Remove(item);
                context.SaveChanges();

                this.GridViewLectures.SelectMethod = "GridViewLectures_GetData";
                this.GridViewLectures.DataBind();
                ErrorSuccessNotifier.AddInfoMessage("Lecture deleted successfully.");
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }
        }
        public void GridViewLectures_DeleteItem(int id)
        {
            var context = new AcademyDbContext();
            Forum.Models.Lecture item = context.Lectures.Find(id);
            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                ErrorSuccessNotifier.AddErrorMessage("The lecture was not found.");
                return;
            }

            try
            {
                context.Lectures.Remove(item);
                context.SaveChanges();

                this.GridViewLectures.SelectMethod = "GridViewLectures_GetData";
                this.GridViewLectures.DataBind();
                ErrorSuccessNotifier.AddInfoMessage("Lecture deleted successfully.");

            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }
        }
        protected void ChangeAvatar_Click(object sender, EventArgs e)
        {
            var    context  = new AcademyDbContext();
            string username = Context.User.Identity.Name;
            var    user     = context.Users.FirstOrDefault(u => u.UserName == username);

            if (user != null)
            {
                string fileName = string.Empty;

                var fileUpload = this.FileUploadAvatar;
                if (fileUpload.HasFile &&
                    (fileUpload.PostedFile.ContentType == PngImageFormat ||
                     fileUpload.PostedFile.ContentType == JpegImageFormat ||
                     fileUpload.PostedFile.ContentType == GifImageFormat))
                {
                    fileName = username.Replace("<", string.Empty).Replace(">", string.Empty) + GetAvatarExtension(FileUploadAvatar.PostedFile.FileName);
                    fileUpload.SaveAs(Server.MapPath(MainPath) + fileName);

                    user.AvatarPath = MainPath + fileName;
                    context.SaveChanges();

                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddSuccessMessage("Avatar changed successfully.");
                    Response.Redirect(Request.RawUrl, false);
                }
                else
                {
                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddErrorMessage("The uploaded avatar exceeds 100KB or is in a wrong format.");
                    Response.Redirect(Request.RawUrl, false);
                    return;
                }
            }
        }
        protected void ChangeEmail_Click(object sender, EventArgs e)
        {
            var userId  = Context.User.Identity.GetUserId();
            var context = new AcademyDbContext();
            var user    = context.Users.Find(userId);

            user.Email = this.TextBoxNewEmail.Text;

            context.SaveChanges();
            Response.Redirect(Request.RawUrl, false);
        }
        protected void GridViewCourses_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = (int)e.Keys["Id"];
            var context = new AcademyDbContext();
            var existingCourse = context.Courses.FirstOrDefault(c => c.Id == id);
            var lectures = existingCourse.Lectures.ToList();
            foreach (var lecture in lectures)
            {
                context.Homeworks.RemoveRange(lecture.Homeworks);
                context.Lectures.Remove(lecture);
            }

            context.SaveChanges();

            context.Courses.Remove(existingCourse);
            context.SaveChanges();

            e.Cancel = true;
            (sender as GridView).DataBind();

            ErrorSuccessNotifier.AddInfoMessage("Course successfully deleted.");
        }
Example #15
0
        public void SaveAmountOfWork(AmountOfWorkVM work, int id) // REDO FÖR TESTING (kanske bör göra extra metod)
        {
            var order   = context.Customer.Where(c => c.CustomerId == id).Select(c => c.Order).SingleOrDefault();
            var orderId = order.OrderId;

            var orderToWork = context.OrderToWork.Where(o => o.OrderId == orderId).ToArray();

            context.OrderToWork.RemoveRange(orderToWork);

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Demolition, HourlyRate = work.HourlyRateDemolition, AmountOfHours = work.DemolitionHours
            });

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Drain, HourlyRate = work.HourlyRateDrain, AmountOfHours = work.DrainHours
            });

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Ventilation, HourlyRate = work.HourlyRateVentilation, AmountOfHours = work.VentilationHours
            });

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Tile, HourlyRate = work.HourlyRateTile, AmountOfHours = work.TileHours
            });

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Electricity, HourlyRate = work.HourlyRateElectricity, AmountOfHours = work.ElectricityHours
            });

            context.OrderToWork.Add(new OrderToWork {
                OrderId = orderId, WorkId = (int)WorkType.Mounting, HourlyRate = work.HourlyRateMounting, AmountOfHours = work.MountingHours
            });

            order.TravelCost   = work.TravelCost;
            order.WorkDiscount = work.WorkDiscount;
            order.IsComplete   = true;

            context.SaveChanges();
        }
Example #16
0
        protected void GridViewCourses_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id             = (int)e.Keys["Id"];
            var context        = new AcademyDbContext();
            var existingCourse = context.Courses.FirstOrDefault(c => c.Id == id);
            var lectures       = existingCourse.Lectures.ToList();

            foreach (var lecture in lectures)
            {
                context.Homeworks.RemoveRange(lecture.Homeworks);
                context.Lectures.Remove(lecture);
            }

            context.SaveChanges();

            context.Courses.Remove(existingCourse);
            context.SaveChanges();

            e.Cancel = true;
            (sender as GridView).DataBind();

            ErrorSuccessNotifier.AddInfoMessage("Course successfully deleted.");
        }
Example #17
0
        protected void LinkButtonEmptyCourseInsert_Click(object sender, EventArgs e)
        {
            var      table       = (sender as LinkButton).Parent;
            string   title       = (table.FindControl("TextBoxEmptyCourseNameInsert") as TextBox).Text;
            string   description = (table.FindControl("TextBoxEmptyCourseDescriptionInsert") as TextBox).Text;
            string   lecturer    = (table.FindControl("DropDownListEmptyLecturerInsert") as DropDownList).SelectedValue;
            int      freePlaces  = int.Parse((table.FindControl("TextBoxEmptyCourseFreePlacesInsert") as TextBox).Text);
            DateTime startDate   = DateTime.Parse((table.FindControl("TextBoxEmptyCourseStartDateInsert") as TextBox).Text);
            DateTime endDate     = DateTime.Parse((table.FindControl("TextBoxEmptyCourseEndDateInsert") as TextBox).Text);

            var context = new AcademyDbContext();

            var existingCourse = context.Courses.FirstOrDefault(c => c.Title == title);

            if (existingCourse != null)
            {
                ErrorSuccessNotifier.AddErrorMessage("Course successfully added.");
                //throw new InvalidOperationException("Course already exists.");
            }

            var existingUser = context.Users.FirstOrDefault(x => x.Id == lecturer);

            if (existingUser == null)
            {
                throw new ArgumentException();
            }

            var courseToInsert = new Course()
            {
                Title       = title,
                Description = description,
                Lecturer    = existingUser,
                FreePlaces  = freePlaces,
                StartDate   = startDate,
                EndDate     = endDate
            };

            context.Courses.Add(courseToInsert);
            context.SaveChanges();

            this.GridViewCourses.DataBind();

            ErrorSuccessNotifier.AddSuccessMessage("Course successfully added.");
        }
        public void GridViewUsers_UpdateItem(string id)
        {
            var context = new AcademyDbContext();

            Forum.Models.ApplicationUser item = context.Users.Find(id);

            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            var editIndex = this.GridViewUsers.EditIndex;

            bool isLecturer = (this.GridViewUsers.Rows[editIndex].FindControl("CheckBoxIsLecturer") as CheckBox).Checked;

            if (isLecturer)
            {
                var lecturerRole = context.Roles.First(r => r.Name == "Lecturer");
                item.Roles.Clear();
                item.Roles.Add(new UserRole()
                {
                    Role = lecturerRole
                });
            }
            else
            {
                item.Roles.Clear();
            }

            TryUpdateModel(item);

            if (ModelState.IsValid)
            {
                context.SaveChanges();
                ErrorSuccessNotifier.AddSuccessMessage("User edited successfully.");
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There was an error editing the user. Please try again.");
            }
        }
        protected void ButtonRegisterForCourse_Click(object sender, EventArgs e)
        {
            string username = Context.User.Identity.Name;

            var context  = new AcademyDbContext();
            var user     = context.Users.FirstOrDefault(u => u.UserName == username);
            int courseId = Convert.ToInt32(RouteData.Values["courseId"]);
            var course   = context.Courses.FirstOrDefault(c => c.Id == courseId);

            if (user != null && course != null && course.FreePlaces > 0)
            {
                user.Courses.Add(course);
                course.Students.Add(user);
                course.FreePlaces--;

                context.SaveChanges();
            }

            Response.Redirect(Request.RawUrl, false);
        }
        public void GridViewLectures_UpdateItem(int id)
        {
            var context = new AcademyDbContext();
            Forum.Models.Lecture item = context.Lectures.Find(id);
            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                context.SaveChanges();
                ErrorSuccessNotifier.AddInfoMessage("Lecture updated successfully.");
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There was an error updating the lecture. Please try again.");
            }
        }
Example #21
0
        public void GridViewLectures_UpdateItem(int id)
        {
            var context = new AcademyDbContext();

            Forum.Models.Lecture item = context.Lectures.Find(id);
            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                context.SaveChanges();
                ErrorSuccessNotifier.AddInfoMessage("Lecture updated successfully.");
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There was an error updating the lecture. Please try again.");
            }
        }
Example #22
0
        protected void GridViewCourses_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string   courseTitle       = ((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxCourseTitleEdit") as TextBox).Text;
            string   courseDescription = ((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxCourseDescriptionEdit") as TextBox).Text;
            string   courseLecturerId  = ((sender as GridView).Rows[e.RowIndex].FindControl("DropDownListLecturerEdit") as DropDownList).SelectedValue;
            int      courseFreePlaces  = int.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxFreePlacesEdit") as TextBox).Text.ToString());
            DateTime startDate         = DateTime.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxStartDateEdit") as TextBox).Text.ToString());
            DateTime endDate           = DateTime.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxEndDateEdit") as TextBox).Text.ToString());

            int id = (int)e.Keys["Id"];

            var context = new AcademyDbContext();

            var existingCourse = context.Courses.FirstOrDefault(x => x.Id == id);

            if (existingCourse == null)
            {
                throw new InvalidOperationException("Course does not exist");
            }

            var existingUser = context.Users.FirstOrDefault(x => x.Id == courseLecturerId);

            if (existingUser == null)
            {
                throw new ArgumentException("Lecturer does not exist");
            }

            existingCourse.Title       = courseTitle;
            existingCourse.Description = courseDescription;
            existingCourse.Lecturer    = existingUser;
            existingCourse.FreePlaces  = courseFreePlaces;
            existingCourse.StartDate   = startDate;
            existingCourse.EndDate     = endDate;

            context.SaveChanges();
            //ErrorSuccessNotifier.AddInfoMessage("Course successfully edited.");
            e.Cancel = true;
            (sender as GridView).EditIndex = -1;
        }
        public void GridViewUsers_UpdateItem(string id)
        {
            var context = new AcademyDbContext();
            Forum.Models.ApplicationUser item = context.Users.Find(id);

            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            var editIndex = this.GridViewUsers.EditIndex;

            bool isLecturer = (this.GridViewUsers.Rows[editIndex].FindControl("CheckBoxIsLecturer") as CheckBox).Checked;
            if (isLecturer)
            {
                var lecturerRole = context.Roles.First(r => r.Name == "Lecturer");
                item.Roles.Clear();
                item.Roles.Add(new UserRole() { Role = lecturerRole });
            }
            else
            {
                item.Roles.Clear();
            }

            TryUpdateModel(item);

            if (ModelState.IsValid)
            {
                context.SaveChanges();
                ErrorSuccessNotifier.AddSuccessMessage("User edited successfully.");
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There was an error editing the user. Please try again.");
            }
        }
        protected void GridViewCourses_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string courseTitle = ((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxCourseTitleEdit") as TextBox).Text;
            string courseDescription = ((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxCourseDescriptionEdit") as TextBox).Text;
            string courseLecturerId = ((sender as GridView).Rows[e.RowIndex].FindControl("DropDownListLecturerEdit") as DropDownList).SelectedValue;
            int courseFreePlaces = int.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxFreePlacesEdit") as TextBox).Text.ToString());
            DateTime startDate = DateTime.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxStartDateEdit") as TextBox).Text.ToString());
            DateTime endDate = DateTime.Parse(((sender as GridView).Rows[e.RowIndex].FindControl("TextBoxEndDateEdit") as TextBox).Text.ToString());

            int id = (int)e.Keys["Id"];

            var context = new AcademyDbContext();

            var existingCourse = context.Courses.FirstOrDefault(x => x.Id == id);

            if (existingCourse == null)
            {
                throw new InvalidOperationException("Course does not exist");
            }

            var existingUser = context.Users.FirstOrDefault(x => x.Id == courseLecturerId);

            if (existingUser == null)
            {
                throw new ArgumentException("Lecturer does not exist");
            }

            existingCourse.Title = courseTitle;
            existingCourse.Description = courseDescription;
            existingCourse.Lecturer = existingUser;
            existingCourse.FreePlaces = courseFreePlaces;
            existingCourse.StartDate = startDate;
            existingCourse.EndDate = endDate;

            context.SaveChanges();
            //ErrorSuccessNotifier.AddInfoMessage("Course successfully edited.");
            e.Cancel = true;
            (sender as GridView).EditIndex = -1;
        }
        protected void ChangeEmail_Click(object sender, EventArgs e)
        {
            var userId = Context.User.Identity.GetUserId();
            var context = new AcademyDbContext();
            var user = context.Users.Find(userId);
            user.Email = this.TextBoxNewEmail.Text;

            context.SaveChanges();
            Response.Redirect(Request.RawUrl, false);
        }
        protected void LinkButtonEmptyCourseInsert_Click(object sender, EventArgs e)
        {
            var table = (sender as LinkButton).Parent;
            string title = (table.FindControl("TextBoxEmptyCourseNameInsert") as TextBox).Text;
            string description = (table.FindControl("TextBoxEmptyCourseDescriptionInsert") as TextBox).Text;
            string lecturer = (table.FindControl("DropDownListEmptyLecturerInsert") as DropDownList).SelectedValue;
            int freePlaces = int.Parse((table.FindControl("TextBoxEmptyCourseFreePlacesInsert") as TextBox).Text);
            DateTime startDate = DateTime.Parse((table.FindControl("TextBoxEmptyCourseStartDateInsert") as TextBox).Text);
            DateTime endDate = DateTime.Parse((table.FindControl("TextBoxEmptyCourseEndDateInsert") as TextBox).Text);

            var context = new AcademyDbContext();

            var existingCourse = context.Courses.FirstOrDefault(c => c.Title == title);

            if (existingCourse != null)
            {
                ErrorSuccessNotifier.AddErrorMessage("Course successfully added.");
                //throw new InvalidOperationException("Course already exists.");
            }

            var existingUser = context.Users.FirstOrDefault(x => x.Id == lecturer);

            if (existingUser == null)
            {
                throw new ArgumentException();
            }

            var courseToInsert = new Course()
            {
                Title = title,
                Description = description,
                Lecturer = existingUser,
                FreePlaces = freePlaces,
                StartDate = startDate,
                EndDate = endDate
            };

            context.Courses.Add(courseToInsert);
            context.SaveChanges();

            this.GridViewCourses.DataBind();

            ErrorSuccessNotifier.AddSuccessMessage("Course successfully added.");
        }
        protected void ButtonUploadHomework_Click(object sender, EventArgs e)
        {
            var context = new AcademyDbContext();
            int lectureId = Convert.ToInt32(RouteData.Values["lectureId"]);
            var lecture = context.Lectures.Find(lectureId);
            string username = Context.User.Identity.Name;
            var user = context.Users.FirstOrDefault(u => u.UserName == username);
            if (lecture == null)
            {
                ErrorSuccessNotifier.AddErrorMessage("The lecture does not exist.");
            }

            if (user == null)
            {
                ErrorSuccessNotifier.AddErrorMessage("The user does not exist.");
            }

            var fileUpload = this.FileUploadHomework;

            ErrorSuccessNotifier.ShowAfterRedirect = true;
            if (fileUpload.HasFile)
            {
                if (fileUpload.PostedFile.ContentLength <= 16777216)
                {
                    if (fileUpload.PostedFile.FileName.EndsWith(".zip") || fileUpload.PostedFile.FileName.EndsWith(".rar"))
                    {
                        if (!Directory.Exists(Server.MapPath(DefaultHomeworksPath + lectureId)))
                        {
                            Directory.CreateDirectory(Server.MapPath(DefaultHomeworksPath + lectureId));
                        }

                        string userForFileName = username.Replace("<", string.Empty).Replace(">", string.Empty);

                        string fileName = string.Format(
                            "HW_{0}_{1}{2}", userForFileName,
                            Regex.Replace(lecture.Title, @"[\W]", "_"),
                            GetFileExtension(fileUpload.PostedFile.FileName));
                        string homeworkPath = DefaultHomeworksPath + lectureId + "/" + fileName;
                        fileUpload.SaveAs(Server.MapPath(homeworkPath));

                        var existingHomework = context.Homeworks.FirstOrDefault(h => h.HomeworkPath == homeworkPath);
                        if (existingHomework == null)
                        {
                            var newHomework = context.Homeworks.Add(new Forum.Models.Homework()
                            {
                                Student = user,
                                StudentId = user.Id,
                                Lecture = lecture,
                                LectureId = lecture.Id,
                                HomeworkPath = homeworkPath,
                                SubmissionTime = DateTime.Now
                            });
                        }
                        else
                        {
                            existingHomework.SubmissionTime = DateTime.Now;
                        }

                        try
                        {
                            context.SaveChanges();
                        }
                        catch (Exception)
                        {
                            ErrorSuccessNotifier.AddErrorMessage(
                                "There was a problem uploading the homework. Please contact the lecturer for this course.");
                            Response.Redirect(Request.RawUrl, false);
                            return;
                        }

                        ErrorSuccessNotifier.AddSuccessMessage("Homework uploaded successfully.");
                        Response.Redirect(string.Format("~/Student/Courses/{0}", lecture.Course.Id), false);
                    }
                    else
                    {
                        ErrorSuccessNotifier.AddErrorMessage("The file is in a wrong format. Allowed formats: .zip, .rar.");
                        Response.Redirect(Request.RawUrl, false);
                    }
                }
                else
                {
                    ErrorSuccessNotifier.AddErrorMessage("The file size exceeds the limit of 16 MB.");
                    Response.Redirect(Request.RawUrl, false);
                }
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There is no file to upload.");
                Response.Redirect(Request.RawUrl, false);
            }
        }
        protected void ButtonRegisterForCourse_Click(object sender, EventArgs e)
        {
            string username = Context.User.Identity.Name;

            var context = new AcademyDbContext();
            var user = context.Users.FirstOrDefault(u => u.UserName == username);
            int courseId = Convert.ToInt32(RouteData.Values["courseId"]);
            var course = context.Courses.FirstOrDefault(c => c.Id == courseId);

            if (user != null && course != null && course.FreePlaces > 0)
            {
                user.Courses.Add(course);
                course.Students.Add(user);
                course.FreePlaces--;

                context.SaveChanges();
            }

            Response.Redirect(Request.RawUrl, false);
        }
        protected void ButtonInsertLecture_Click(object sender, EventArgs e)
        {
            int courseId = Convert.ToInt32(this.RouteData.Values["courseId"]);
            string title = (this.GridViewLectures.FooterRow.FindControl("TextBoxInsertTitle") as TextBox).Text;
            string location = (this.GridViewLectures.FooterRow.FindControl("TextBoxInsertLocation") as TextBox).Text;
            DateTime homeworkDueDate = DateTime.Parse((this.GridViewLectures.FooterRow.FindControl("TextBoxInsertHomeworkDue") as TextBox).Text);

            var context = new AcademyDbContext();
            var course = context.Courses.Find(courseId);
            var lecture = new Forum.Models.Lecture()
            {
                Title = title,
                Location = location,
                HomeworkDueDate = homeworkDueDate
            };

            context.Lectures.Add(lecture);
            try
            {
                context.SaveChanges();
                lecture.Course = course;
                context.SaveChanges();
                ErrorSuccessNotifier.AddSuccessMessage("Lecture created successfully.");
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex.Message);
            }

            this.GridViewLectures.SelectMethod = "GridViewLectures_GetData";
            this.GridViewLectures.DataBind();
        }
        protected void ChangeAvatar_Click(object sender, EventArgs e)
        {
            var context = new AcademyDbContext();
            string username = Context.User.Identity.Name;
            var user = context.Users.FirstOrDefault(u => u.UserName == username);

            if (user != null)
            {
                string fileName = string.Empty;

                var fileUpload = this.FileUploadAvatar;
                if (fileUpload.HasFile &&
                    (fileUpload.PostedFile.ContentType == PngImageFormat ||
                    fileUpload.PostedFile.ContentType == JpegImageFormat ||
                    fileUpload.PostedFile.ContentType == GifImageFormat))
                {
                    fileName = username.Replace("<", string.Empty).Replace(">", string.Empty) + GetAvatarExtension(FileUploadAvatar.PostedFile.FileName);
                    fileUpload.SaveAs(Server.MapPath(MainPath) + fileName);

                    user.AvatarPath = MainPath + fileName;
                    context.SaveChanges();

                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddSuccessMessage("Avatar changed successfully.");
                    Response.Redirect(Request.RawUrl, false);
                }
                else
                {
                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddErrorMessage("The uploaded avatar exceeds 100KB or is in a wrong format.");
                    Response.Redirect(Request.RawUrl, false);
                    return;
                }
            }
        }
        protected void ButtonUploadHomework_Click(object sender, EventArgs e)
        {
            var    context   = new AcademyDbContext();
            int    lectureId = Convert.ToInt32(RouteData.Values["lectureId"]);
            var    lecture   = context.Lectures.Find(lectureId);
            string username  = Context.User.Identity.Name;
            var    user      = context.Users.FirstOrDefault(u => u.UserName == username);

            if (lecture == null)
            {
                ErrorSuccessNotifier.AddErrorMessage("The lecture does not exist.");
            }

            if (user == null)
            {
                ErrorSuccessNotifier.AddErrorMessage("The user does not exist.");
            }

            var fileUpload = this.FileUploadHomework;

            ErrorSuccessNotifier.ShowAfterRedirect = true;
            if (fileUpload.HasFile)
            {
                if (fileUpload.PostedFile.ContentLength <= 16777216)
                {
                    if (fileUpload.PostedFile.FileName.EndsWith(".zip") || fileUpload.PostedFile.FileName.EndsWith(".rar"))
                    {
                        if (!Directory.Exists(Server.MapPath(DefaultHomeworksPath + lectureId)))
                        {
                            Directory.CreateDirectory(Server.MapPath(DefaultHomeworksPath + lectureId));
                        }

                        string userForFileName = username.Replace("<", string.Empty).Replace(">", string.Empty);

                        string fileName = string.Format(
                            "HW_{0}_{1}{2}", userForFileName,
                            Regex.Replace(lecture.Title, @"[\W]", "_"),
                            GetFileExtension(fileUpload.PostedFile.FileName));
                        string homeworkPath = DefaultHomeworksPath + lectureId + "/" + fileName;
                        fileUpload.SaveAs(Server.MapPath(homeworkPath));

                        var existingHomework = context.Homeworks.FirstOrDefault(h => h.HomeworkPath == homeworkPath);
                        if (existingHomework == null)
                        {
                            var newHomework = context.Homeworks.Add(new Forum.Models.Homework()
                            {
                                Student        = user,
                                StudentId      = user.Id,
                                Lecture        = lecture,
                                LectureId      = lecture.Id,
                                HomeworkPath   = homeworkPath,
                                SubmissionTime = DateTime.Now
                            });
                        }
                        else
                        {
                            existingHomework.SubmissionTime = DateTime.Now;
                        }

                        try
                        {
                            context.SaveChanges();
                        }
                        catch (Exception)
                        {
                            ErrorSuccessNotifier.AddErrorMessage(
                                "There was a problem uploading the homework. Please contact the lecturer for this course.");
                            Response.Redirect(Request.RawUrl, false);
                            return;
                        }

                        ErrorSuccessNotifier.AddSuccessMessage("Homework uploaded successfully.");
                        Response.Redirect(string.Format("~/Student/Courses/{0}", lecture.Course.Id), false);
                    }
                    else
                    {
                        ErrorSuccessNotifier.AddErrorMessage("The file is in a wrong format. Allowed formats: .zip, .rar.");
                        Response.Redirect(Request.RawUrl, false);
                    }
                }
                else
                {
                    ErrorSuccessNotifier.AddErrorMessage("The file size exceeds the limit of 16 MB.");
                    Response.Redirect(Request.RawUrl, false);
                }
            }
            else
            {
                ErrorSuccessNotifier.AddErrorMessage("There is no file to upload.");
                Response.Redirect(Request.RawUrl, false);
            }
        }