// DELETE api/memberships/5 public void Delete(string id) { //this is a bit hacky - but the association will be coming in here //and it's GUID | role //so parse that and unassign var splits = id.Split('|'); var userId = splits[0]; var roleId = splits[1]; //this is a new user/role assignment using (var db = new ApplicationDbContext()) { var role = db.Roles.FirstOrDefault(x => x.Id == roleId); var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); manager.RemoveFromRole(userId, role.Name); var note = new AspNetUserNote(); note.EnteredBy = User.Identity.Name; note.Note = "Removed user from " + role.Name + " role"; var user = db.Users.FirstOrDefault(x => x.Id == userId); user.Notes.Add(note); db.SaveChanges(); } }
public static Enrollment CreateNewEnrollment(Course course, ApplicationUser user, ApplicationDbContext context) { var passedDate = DateTime.Parse("1900-1-1"); var newEnrollment = new Enrollment { ApplicationUser = user, PassedDate=passedDate, Course= course, EnrollmentDate = DateTime.UtcNow }; context.Enrollments.Add(newEnrollment); try { context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Debug.Print("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Debug.Print("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } CreateScoRecordsForCourse(newEnrollment, context); return newEnrollment; }
// POST api/<controller> public dynamic Post([FromBody]dynamic model) { using (var db = new ApplicationDbContext()) { string id = model.note.user; var user = db.Users.FirstOrDefault(x => x.Id == id); var note = new AspNetUserNote(); note.CreatedAt = DateTime.Now; note.EnteredBy = User.Identity.Name; note.Note = model.note.note; user.Notes.Add(note); db.SaveChanges(); } return model; }
// PUT api/users/5 public dynamic Put(string id, dynamic model) { using (var db = new ApplicationDbContext()) { var user = db.Users.FirstOrDefault(x => x.Id == id); //load it up! if (user != null) { user.UserName = model.user.userName; user.First = model.user.first; user.Last = model.user.last; user.Email = model.user.email; user.Bio = model.user.bio; user.Twitter = model.user.twitter; db.SaveChanges(); } } return model; }
protected ApplicationDbContext CreateDbContext() { var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>(); optionsBuilder.UseInMemoryDatabase(); var db = new ApplicationDbContext(optionsBuilder.Options); db.Libraries.Add(new Library { CreatedByUserId = "dbo", CreatedOn = DateTimeOffset.Now, ModifiedOn = DateTimeOffset.Now, Name = "Test Library", Status = StatusTypes.Active }); db.SaveChanges(); return db; }
// POST api/memberships public void Post(dynamic model) { //this is a new user/role assignment using (var db = new ApplicationDbContext()) { string roleId = model.membership.role; var role = db.Roles.FirstOrDefault(x => x.Id == roleId); string userId = model.membership.user; var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); manager.AddToRole(userId, role.Name); var note = new AspNetUserNote(); note.EnteredBy = User.Identity.Name; note.Note = "Added user to " + role.Name + " role"; var user = db.Users.FirstOrDefault(x => x.Id == userId); user.Notes.Add(note); db.SaveChanges(); } }
private void LogEvent(string entry, string userName = null){ //HACK: This is such a ridiculous hack. There is evidently no UnitOfWork open here on //the user - attaching a log doesn't work. Lovely. using (var db = new ApplicationDbContext()) { var login = userName ?? User.Identity.Name; var user = db.Users.FirstOrDefault(x => x.UserName == login); if (user != null) { var log = new AspNetUserLog(); log.Entry = entry; user.Logs = user.Logs ?? new List<AspNetUserLog>(); user.Logs.Add(log); var result = db.SaveChanges(); } } }
public ActionResult Destroy_MyAvailableTime([DataSourceRequest]DataSourceRequest request, MeetingViewModel task) { if (ModelState.IsValid) { using (var context = new ApplicationDbContext()) { // Create a new Task entity and set its properties from the posted TaskViewModel var meeting = new Meeting { Id = task.Id, Title = task.Title, Start = task.Start, End = task.End, Description = task.Description, RecurrenceRule = task.RecurrenceRule, RecurrenceException = task.RecurrenceException, RecurrenceId = task.RecurrenceId, IsAllDay = task.IsAllDay, InstructorId = task.InstructorId }; context.Meetings.Attach(meeting); context.Meetings.Remove(meeting); context.SaveChanges(); } } // Return the removed task. Also return any validation errors. return Json(new[] { task }.ToDataSourceResult(request, ModelState)); }
public ActionResult Update_MyAvailableTime([DataSourceRequest]DataSourceRequest request, MeetingViewModel task) { if (ModelState.IsValid) { using (var context = new ApplicationDbContext()) { // Create a new Task entity and set its properties from the posted TaskViewModel var entity = new Meeting { Id = task.Id, Title = task.Title, Start = task.Start, End = task.End, Description = task.Description, RecurrenceRule = task.RecurrenceRule, RecurrenceException = task.RecurrenceException, RecurrenceId = task.RecurrenceId, IsAllDay = task.IsAllDay, InstructorId = task.InstructorId, MeetingTypeId = task.MeetingTypeId }; // Attach the entity context.Meetings.Attach(entity); // Change its state to Modified so Entity Framework can update the existing task instead of creating a new one context.Entry(entity).State = EntityState.Modified; // Update the entity in the database try { // Insert the entity in the database context.SaveChanges(); } catch (Exception ex) { Log4NetHelper.Log("Error Updating Available Meeting Available Meeting", LogLevel.ERROR, "MeetingsServices", 497, "tester", ex); } } } // Return the updated task. Also return any validation errors. return Json(new[] { task }.ToDataSourceResult(request, ModelState)); }
public static Meeting CreateMeetingforGtm(MeetingViewModel meeting, string courseTitle, string joinUrl, ApplicationUser instructor) { using (var context = new ApplicationDbContext()) { //Create a new Task entity and set its properties from the posted TaskViewModel var newMeeting = new Meeting { Title = meeting.Title, Start = meeting.Start, End = meeting.End, Description = meeting.Description, RecurrenceRule = meeting.RecurrenceRule, RecurrenceException = meeting.RecurrenceException, RecurrenceId = meeting.RecurrenceId, IsAllDay = false, CourseId = meeting.CourseId, GtmUrl = joinUrl, InstructorId = instructor.Id, MeetingTypeId = (int) MeetingType.ClassMeeting, StudentId = instructor.Id }; try { context.Meetings.Add(newMeeting); context.SaveChanges(); } //catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) //{ // //Exception raise = dbEx; // foreach (var validationErrors in dbEx.EntityValidationErrors) // { // foreach (var validationError in validationErrors.ValidationErrors) // { // string errorMessage = string.Format("{0}:{1}", // validationErrors.Entry.Entity.ToString(), // validationError.ErrorMessage); // // raise a new exception nesting // // the current instance as InnerException // //raise = new InvalidOperationException(errorMessage, raise); // } // } // Log4NetHelper.Log("Did not save new Class Meeting - Validation Error", LogLevel.ERROR, "MeetingServices", 585, "tester", dbEx); //} catch (Exception ex) { Log4NetHelper.Log("Did not save new Class Meeting", LogLevel.ERROR, "MeetingServices", 585, "tester", ex); } // Get the TaskID generated by the database meeting.Id = newMeeting.Id; return newMeeting; } }
public static Meeting CreateMyAvailableTime(MeetingViewModel meeting, string currentUserId) { using (var context = new ApplicationDbContext()) { //Create a new Task entity and set its properties from the posted TaskViewModel var entity = new Meeting { Id = meeting.Id, Title = meeting.Title, Start = meeting.Start, End = meeting.End, Description = meeting.Description, RecurrenceRule = meeting.RecurrenceRule, RecurrenceException = meeting.RecurrenceException, RecurrenceId = meeting.RecurrenceId, IsAllDay = meeting.IsAllDay, InstructorId = currentUserId, MeetingTypeId = Convert.ToInt32(MeetingType.Available) }; // Add the entity context.Meetings.Add(entity); try { // Insert the entity in the database context.SaveChanges(); } catch (Exception ex) { Log4NetHelper.Log("Choked Creating new Available Meeting", LogLevel.ERROR, "MeetingsServices", 497, "tester", ex); } // Get the TaskID generated by the database meeting.Id = entity.Id; return entity; } }
public static List<Meeting> BookCheckedDates(ApplicationDbContext context, ICurrentUser student, AvailableMeetingsViewModel form, IEnumerable<AvailableMeeting> availableMeetings) { var bookedMeetings = form.CheckedAvailableMeetings; var meetingsBooked = new List<Meeting>(); var i = 0; foreach (var meeting in availableMeetings) { //var meetingId = meeting.Id; //var xtra = meeting.IsChecked; //if (model.CheckedAvailableMeetings[i]) if (meeting.IsChecked) { var checkedMeeting = context.Meetings.Find(meeting.Id); var studentName = student.User.FirstName + " " + student.User.LastName.Substring(0, 1) + "."; var instructorName = checkedMeeting.Instructor.FirstName + " " + checkedMeeting.Instructor.LastName.Substring(0, 1) + "."; //Create GoToMeeting var meetingUrl = CreateGtmForAvailableSlot(context, checkedMeeting); if (!string.IsNullOrEmpty(meetingUrl)) { checkedMeeting.GtmUrl = meetingUrl; checkedMeeting.MeetingTypeId = (int) MeetingType.PrivateMeeting; checkedMeeting.StudentId = student.User.Id; checkedMeeting.Title = checkedMeeting.Title + " - " + studentName; checkedMeeting.Description = studentName + " has booked an online meeting with " + instructorName + " on " + checkedMeeting.Start.AddMinutes(TimeDateServices.GetUtcOffSet()) .ToString("dddd MMM-d-yyyy h-mm tt"); context.Entry(checkedMeeting).State = EntityState.Modified; meetingsBooked.Add(checkedMeeting); } //else //{ // Log4NetHelper.Log("Meeting Booking Failed", LogLevel.WARN, "BookCheckedDates", 328, studentName, null); //} } i++; } try { context.SaveChanges(); } catch (Exception ex) { Log4NetHelper.Log("Failed to Book Meeting", LogLevel.ERROR, "Meetings", 150, "Tester", ex); } return meetingsBooked; }
private static void DeletePriorMeetings(ApplicationDbContext context) { var earliestStartShown = DateTime.UtcNow.AddHours(-2); //Delete available times before present time (there is an instructor but no associated student) var range = context.Meetings.Where( m => m.Start < earliestStartShown && m.InstructorId != null && m.StudentId == null).ToList(); if (range.Any()) { context.Meetings.RemoveRange(range); context.SaveChanges(); } }
public static void CreateScoRecordsForCourse(Enrollment enrollment, ApplicationDbContext context) { var courseTemplateId = enrollment.Course.CourseTemplateId; var courseScos = context.CourseScos.Include(c => c.Sco).Where(cm => cm.CourseTemplateId == courseTemplateId); foreach (var item in courseScos) { var scoRecord = new ScoRecord { Title = item.Title, EnrollmentId = enrollment.Id, CatalogueNumber = item.CatalogueNumber, ScoId = item.Sco.Id, ScormName = "", ScormValue = "", LessonStatus = "", LastClosed = DateTime.Parse("1900-1-1"), Stored = DateTime.Parse("1900-1-1"), TimeStamp = DateTime.Parse("1900-1-1"), CourseTemplateId = enrollment.Course.CourseTemplateId, CourseId = enrollment.CourseId, ActorId = enrollment.ApplicationUserId, //IsEnabled = item.RequiredCourseScoId == 0, IsFinalExam = item.IsFinalExam }; //var requiredRecord = context.CourseScos.Find(item.RequiredCourseScoId); //if (requiredRecord != null) // scoRecord.RequiredScoId = requiredRecord.ScoId; context.ScoRecords.Add(scoRecord); } context.SaveChanges(); }
private bool ConfirmAccount(string confirmationToken) { var context = new ApplicationDbContext(); var user = context.Users.SingleOrDefault(u => u.ConfirmationToken == confirmationToken); if (user != null) { user.IsConfirmed = true; var dbSet = context.Set<ApplicationUser>(); dbSet.Attach(user); context.Entry(user).State = EntityState.Modified; context.SaveChanges(); return true; } return false; }
public static List<Meeting> BookCheckedDates2(ApplicationDbContext context, ICurrentUser student, IEnumerable<PickMeeting> pickMeetings) { var meetingsBooked = new List<Meeting>(); foreach (var meeting in pickMeetings) { if (meeting.IsPicked) { var checkedMeeting = context.Meetings.Find(meeting.Id); //Create GoToMeeting var meetingUrl = CreateGtmForAvailableSlot(context, checkedMeeting); if (!string.IsNullOrEmpty(meetingUrl)) { checkedMeeting.GtmUrl = meetingUrl; checkedMeeting.MeetingTypeId = (int) MeetingType.PrivateMeeting; checkedMeeting.StudentId = student.User.Id; checkedMeeting.Title = checkedMeeting.Title + " - " + student.User.FirstNameLastInitial; context.Entry(checkedMeeting).State = EntityState.Modified; meetingsBooked.Add(checkedMeeting); } else { Log4NetHelper.Log("Meeting Booking Failed", LogLevel.WARN, "BookCheckedDates", 328, student.User.UserName, null); } } } try { context.SaveChanges(); } catch (Exception ex) { Log4NetHelper.Log("Failed to Book Meeting", LogLevel.ERROR, "Meetings", 150, student.User.UserName, ex); } return meetingsBooked; }
public static Order AddOrder(OrderViewModel vm, ApplicationDbContext context) { var order = new Order { ConfirmationCode = vm.ConfirmationCode, Ppref = vm.Ppref, Correlationid = vm.CorrelationId, PaymentType = vm.PaymentOption, UserName = vm.UserName, FirstName = vm.FirstName, LastName = vm.LastName, City = vm.City, Country = vm.CountryCode, PostalCode = vm.PostalCode, OrderDate = DateTime.UtcNow, Total = vm.Amt, Phone = vm.Phone, Email = vm.Email, Tax1Amount = vm.Tax1Amount, Tax1Name = vm.Tax1Name, }; context.Orders.Add(order); try { context.SaveChanges(); //This gets the orderId that we use to for Order details table } catch (DbEntityValidationException e) { foreach (var error in e.EntityValidationErrors) { Console.WriteLine(@"Entity of Type ""{0}"" in state ""{1}"" has the following errors:", error.Entry.Entity.GetType().Name, error.Entry.State); foreach (var ve in error.ValidationErrors) { Console.WriteLine(@"-Property: '{0}', Error: '{1}", ve.PropertyName, ve.ErrorMessage); } } } return order; }