public AccountController(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, RoleManager <IdentityRole> roleManager, AcademyDbContext db) { this.userManager = userManager; this.signInManager = signInManager; this.roleManager = roleManager; this.db = db; }
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 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 Page_Load(object sender, EventArgs e) { Session[KeyLectureActive] = false; Session[KeyLectureAndUserExist] = false; string username = Context.User.Identity.Name; int lectureId = Convert.ToInt32(RouteData.Values["lectureId"]); var context = new AcademyDbContext(); var user = context.Users.FirstOrDefault(u => u.UserName == username); var lecture = context.Lectures.Find(lectureId); if (user != null && lecture != null) { if (lecture.HomeworkDueDate < DateTime.Now || !user.Courses.Contains(lecture.Course)) { Response.Clear(); ErrorSuccessNotifier.ShowAfterRedirect = false; ErrorSuccessNotifier.AddErrorMessage("You do not have the right to upload a homework for this lecture."); } else { Session[KeyLectureAndUserExist] = true; Session[KeyLectureActive] = true; } } else { ErrorSuccessNotifier.AddErrorMessage("The lecture does not exist or there is no currently logged in user."); } }
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 Page_PreRender(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { string username = User.Identity.Name; var context = new AcademyDbContext(); var user = context.Users.FirstOrDefault(u => u.UserName == username); var registerPanel = this.FormViewCourse.FindControl("PanelRegisterForCourse") as Panel; int courseId = Convert.ToInt32(RouteData.Values["courseId"]); var course = context.Courses.FirstOrDefault(c => c.Id == courseId); if (course != null && !user.Courses.Contains(course) && course.FreePlaces > 0) { (registerPanel.FindControl("ButtonRegisterForCourse") as Button).Visible = true; } else if (user.Courses.Contains(course)) { var label = new Label() { Text = "You are already registered for this course." }; registerPanel.Controls.Add(label); } else { var label = new Label() { Text = "There are no free places for this course." }; registerPanel.Controls.Add(label); } } }
protected void DropDownListCourses_SelectedIndexChanged(object sender, EventArgs e) { var context = new AcademyDbContext(); var index = this.DropDownListCourses.SelectedValue; ViewState["courseId"] = index; this.GridViewHomeworks.DataBind(); this.DropDownListCourses.SelectedValue = index; }
protected void CreateUser_Click(object sender, EventArgs e) { string userName = UserName.Text; var manager = new AuthenticationIdentityManager(new IdentityStore(new AcademyDbContext())); ApplicationUser u = new ApplicationUser(userName) { UserName = userName, FirstName = this.TextBoxFirstName.Text, LastName = this.TextBoxLastName.Text, Email = this.TextBoxEmail.Text, JoinDate = DateTime.Now, }; var context = new AcademyDbContext(); string fileName = string.Empty; var fileUpload = this.FileUploadAvatar; if (fileUpload.HasFile) { if (fileUpload.PostedFile.ContentLength < 102400 && (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); u.AvatarPath = MainPath + fileName; } else { ErrorSuccessNotifier.ShowAfterRedirect = true; ErrorSuccessNotifier.AddErrorMessage("The uploaded avatar exceeds 100KB or is in a wrong format."); Response.Redirect(Request.RawUrl, false); return; } } else { u.AvatarPath = DefaultImagePath; } IdentityResult result = manager.Users.CreateLocalUser(u, Password.Text); if (result.Success) { manager.Authentication.SignIn(Context.GetOwinContext().Authentication, u.Id, isPersistent: false); ErrorSuccessNotifier.ShowAfterRedirect = true; ErrorSuccessNotifier.AddSuccessMessage("Registration completed successfully."); OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorSuccessNotifier.AddErrorMessage(result.Errors.FirstOrDefault()); } }
public IQueryable<ApplicationUser> GridViewUsers_GetData() { var context = new AcademyDbContext(); var userId = Context.User.Identity.GetUserId(); return context.Users .Include(u => u.Courses) .Include(u => u.Roles) .Where(u => u.Id != userId); }
public IQueryable <ApplicationUser> GridViewUsers_GetData() { var context = new AcademyDbContext(); var userId = Context.User.Identity.GetUserId(); return(context.Users .Include(u => u.Courses) .Include(u => u.Roles) .Where(u => u.Id != userId)); }
// The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable<Course> GridViewMyCourses_GetData() { var context = new AcademyDbContext(); return context.Courses .Include("Lecturer") .Include("Students") .OrderBy(c => c.Id) .Where(c => c.Students .Any(st => st.UserName == HttpContext.Current.User.Identity.Name)); }
public Forum.Models.Lecture FormViewUploadHomework_GetItem([RouteData]int lectureId) { if (Convert.ToBoolean(Session[KeyLectureActive]) && Convert.ToBoolean(Session[KeyLectureAndUserExist])) { var context = new AcademyDbContext(); return context.Lectures.Find(lectureId); } this.PanelWrapper.Visible = false; return null; }
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); }
// The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable <Course> GridViewMyCourses_GetData() { var context = new AcademyDbContext(); return(context.Courses .Include("Lecturer") .Include("Students") .OrderBy(c => c.Id) .Where(c => c.Students .Any(st => st.UserName == HttpContext.Current.User.Identity.Name))); }
public Forum.Models.Lecture FormViewUploadHomework_GetItem([RouteData] int lectureId) { if (Convert.ToBoolean(Session[KeyLectureActive]) && Convert.ToBoolean(Session[KeyLectureAndUserExist])) { var context = new AcademyDbContext(); return(context.Lectures.Find(lectureId)); } this.PanelWrapper.Visible = false; return(null); }
public IQueryable<Forum.Models.ApplicationUser> ListViewUserInfo_GetData() { var context = new AcademyDbContext(); string userId = Context.User.Identity.GetUserId(); var user = context.Users.Find(userId); if (user != null) { return new List<ApplicationUser> { user }.AsQueryable(); } return null; }
public static IServiceCollection UseMigrations(this IServiceCollection serviceCollection, string connectionString) { serviceCollection.AddScoped <IMigrationContext>((serviceProvider) => { var ctxOptions = new DbContextOptionsBuilder <AcademyDbContext>() .UseSqlServer(connectionString) .Options; var context = new AcademyDbContext(ctxOptions); return(context); }); return(serviceCollection); }
protected void Page_Load(object sender, EventArgs e) { var username = Context.User.Identity.Name; var context = new AcademyDbContext(); var user = context.Users.FirstOrDefault(u => u.UserName == username); if (user != null) { var avatarPath = user.AvatarPath; var avatarImage = this.LoginViewUser.FindControl("ImageUserAvatar") as Image; avatarImage.ImageUrl = avatarPath; avatarImage.Width = 30; avatarImage.Height = 30; } }
public IQueryable <Forum.Models.ApplicationUser> ListViewUserInfo_GetData() { var context = new AcademyDbContext(); string userId = Context.User.Identity.GetUserId(); var user = context.Users.Find(userId); if (user != null) { return(new List <ApplicationUser> { user }.AsQueryable()); } return(null); }
void Application_Start(object sender, EventArgs e) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<AcademyDbContext, Configuration>()); var context = new AcademyDbContext(); context.Lectures.ToList(); var endedCourses = context.Courses.Where(c=>c.EndDate<DateTime.Now).ToList(); foreach (var course in endedCourses) { course.IsClosed = true; } // Code that runs on application startup BundleConfig.RegisterBundles(BundleTable.Bundles); RouteConfig.RegisterRoutes(RouteTable.Routes); }
protected void GridViewCourses_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if ((e.Row.RowState & DataControlRowState.Edit) > 0) { DropDownList ddList = (DropDownList)e.Row.FindControl("DropDownListLecturerEdit"); //bind dropdownlist var context = new AcademyDbContext(); var id = int.Parse(Session["course-id"].ToString()); var lectureId = context.Courses.FirstOrDefault(x => x.Id == id).Lecturer.Id; ddList.SelectedValue = lectureId; } } }
public string GetHomeworkLinks(int lectureId) { var context = new AcademyDbContext(); string result = ""; //get current user string username = User.Identity.Name; var user = context.Users.FirstOrDefault(u => u.UserName == username); var lecture = context.Lectures.FirstOrDefault(x => x.Id == lectureId); if (lecture.HomeworkDueDate < DateTime.Now) { foreach (GridViewRow row in this.GridViewLectures.Rows) { var datakey = Convert.ToInt32(GridViewLectures.DataKeys[row.RowIndex]["Id"]); if (datakey == lectureId) { (row.FindControl("PanelUpload") as Panel).Visible = false; break; } } } if (user.Courses.Contains(lecture.Course)) { var hw = lecture.Homeworks.FirstOrDefault(x => x.Student == user); if (hw != null) { result += "<a href='../../" + hw.HomeworkPath.Remove(0, 2) + "'>Download</a><br/>"; } if (lecture.HomeworkDueDate > DateTime.Now) { result += "<a href='../Homeworks/" + lectureId + "'>Upload</a>"; } else { result += "<em>Expired</em>"; } } return(result); }
protected void GridViewMyCourses_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if ((e.Row.RowState & DataControlRowState.Edit) > 0) { DropDownList ddList = (DropDownList)e.Row.FindControl("DropDownListLecturerEdit"); //bind dropdownlist var context = new AcademyDbContext(); var id = int.Parse(Session["course-id"].ToString()); var lectureId = context.Courses.FirstOrDefault(x => x.Id == id).Lecturer.Id; ddList.SelectedValue = lectureId; } } }
// The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable<Forum.Models.Homework> GridViewHomeworks_GetData([ViewState("courseId")]string courseId = null) { var context = new AcademyDbContext(); if (courseId != null) { var Id = Convert.ToInt32(courseId); return context.Homeworks .Include(h => h.Lecture) .Include(h => h.Student) .Where(x => x.Lecture.Course.Id == Id); } int selectedCourseId=int.Parse(this.DropDownListCourses.SelectedValue); return context.Homeworks .Include(h => h.Lecture) .Include(h => h.Student) .Where(x => x.Lecture.Course.Id == selectedCourseId); }
void Application_Start(object sender, EventArgs e) { Database.SetInitializer(new MigrateDatabaseToLatestVersion <AcademyDbContext, Configuration>()); var context = new AcademyDbContext(); context.Lectures.ToList(); var endedCourses = context.Courses.Where(c => c.EndDate < DateTime.Now).ToList(); foreach (var course in endedCourses) { course.IsClosed = true; } // Code that runs on application startup BundleConfig.RegisterBundles(BundleTable.Bundles); RouteConfig.RegisterRoutes(RouteTable.Routes); }
public static IServiceCollection UseRegisterDbContext(this IServiceCollection serviceCollection, string connectionString, IsolationLevel level = IsolationLevel.ReadUncommitted) { //First, configure the SqlConnection and open it //This is done for every request/response serviceCollection.AddScoped <DbConnection>((serviceProvider) => { var dbConnection = new SqlConnection(connectionString); dbConnection.Open(); return(dbConnection); }); //Start a new transaction based on the SqlConnection //This is done for every request/response serviceCollection.AddScoped <DbTransaction>((serviceProvider) => { var dbConnection = serviceProvider .GetService <DbConnection>(); return(dbConnection.BeginTransaction(level)); }); //Create DbOptions for the DbContext, use the DbConnection //This is done for every request/response serviceCollection.AddScoped <DbContextOptions>((serviceProvider) => { var dbConnection = serviceProvider.GetService <DbConnection>(); return(new DbContextOptionsBuilder <AcademyDbContext>() .UseSqlServer(dbConnection) .Options); }); //Finally, create the DbContext, using the transaction //This is done for every request/response serviceCollection.AddScoped((serviceProvider) => { var transaction = serviceProvider.GetService <DbTransaction>(); var options = serviceProvider.GetService <DbContextOptions>(); var context = new AcademyDbContext(options); context.Database.UseTransaction(transaction); return(context); }); return(serviceCollection); }
public string GetHomeworkLinks(int lectureId) { var context = new AcademyDbContext(); string result = ""; //get current user string username = User.Identity.Name; var user = context.Users.FirstOrDefault(u => u.UserName == username); var lecture = context.Lectures.FirstOrDefault(x => x.Id == lectureId); if (lecture.HomeworkDueDate < DateTime.Now) { foreach (GridViewRow row in this.GridViewLectures.Rows) { var datakey = Convert.ToInt32(GridViewLectures.DataKeys[row.RowIndex]["Id"]); if (datakey == lectureId) { (row.FindControl("PanelUpload") as Panel).Visible = false; break; } } } if (user.Courses.Contains(lecture.Course)) { var hw = lecture.Homeworks.FirstOrDefault(x => x.Student == user); if (hw != null) { result += "<a href='../../" + hw.HomeworkPath.Remove(0, 2) + "'>Download</a><br/>"; } if (lecture.HomeworkDueDate > DateTime.Now) { result += "<a href='../Homeworks/" + lectureId + "'>Upload</a>"; } else { result += "<em>Expired</em>"; } } return result; }
protected void Page_Load() { if (!IsPostBack) { // Determine the sections to render ILoginManager manager = new IdentityManager(new IdentityStore()).Logins; if (manager.HasLocalLogin(User.Identity.GetUserId())) { changePasswordHolder.Visible = true; } else { setPassword.Visible = true; changePasswordHolder.Visible = false; } CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1; // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); SuccessMessage = message == "ChangePwdSuccess" ? "Your password has been changed." : message == "SetPwdSuccess" ? "Your password has been set." : message == "RemoveLoginSuccess" ? "The account was removed." : String.Empty; successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage); } } var username = Context.User.Identity.Name; var context = new AcademyDbContext(); var user = context.Users.FirstOrDefault(u => u.UserName == username); if (user != null) { var avatarPath = user.AvatarPath; var avatarImage = this.PlaceHolderChangeAvatar.FindControl("ImageUserAvatar") as Image; avatarImage.ImageUrl = avatarPath; } }
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."); } }
public StudentsController(AcademyDbContext context) { _context = context; //if (context.StudentSet.Count() == 0) //{ // var std1 = new Student(); // std1.Id = Guid.NewGuid(); // std1.Name = "Perico"; // var std2 = new Student(); // std2.Id = Guid.NewGuid(); // std2.Name = "Lola"; // context.StudentSet.Add(std1); // context.StudentSet.Add(std2); // context.SaveChanges(); //} }
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); }
// The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable <Forum.Models.Homework> GridViewHomeworks_GetData([ViewState("courseId")] string courseId = null) { var context = new AcademyDbContext(); if (courseId != null) { var Id = Convert.ToInt32(courseId); return(context.Homeworks .Include(h => h.Lecture) .Include(h => h.Student) .Where(x => x.Lecture.Course.Id == Id)); } int selectedCourseId = int.Parse(this.DropDownListCourses.SelectedValue); return(context.Homeworks .Include(h => h.Lecture) .Include(h => h.Student) .Where(x => x.Lecture.Course.Id == selectedCourseId)); }
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."); } }
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."); }
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; }
// The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable<Course> GridViewStudentCourses_GetData() { var context = new AcademyDbContext(); return context.Courses.Include("Lecturer").OrderBy(c => c.Id); }
public IQueryable<Role> DropDownListRole_GetData() { var context = new AcademyDbContext(); return context.Roles; }
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(); }
public IQueryable<Forum.Models.Course> GridViewAnonymousCourses_GetData() { var context = new AcademyDbContext(); return context.Courses; }
protected void Page_Load(object sender, EventArgs e) { var context = new AcademyDbContext(); }
public IQueryable<Resource> DropDownListResourceType_GetData() { var context = new AcademyDbContext(); return context.Resources; }
public Forum.Models.Course FormViewCourse_GetItem([RouteData] int courseId) { var context = new AcademyDbContext(); return(context.Courses.Find(courseId)); }
public IQueryable<Course> DropDownListCourses_GetData([ViewState("courseId")]string courseId = null) { var context = new AcademyDbContext(); return context.Courses; }
public StudentRepository(AcademyDbContext context) { _context = context; }
public Forum.Models.Course FormViewCourse_GetItem([RouteData]int courseId) { var context = new AcademyDbContext(); return context.Courses.Find(courseId); }