public static void SendReading(Guid courseId, DateTime schedule, PerformContext context) { using (var db = new MedSimDbContext()) { var course = db.Courses.Include("CourseFormat.CourseType.CandidatePrereadings").Include("CourseParticipants.Participant").Include("HangfireJobs") .First(c => c.Id == courseId); var readings = GetSupplementReadings(course, schedule); using (var mail = new MailMessage()) { mail.To.AddParticipants(from cp in course.CourseParticipants where !cp.IsFaculty select cp.Participant); var confirmEmail = new CandidateReadingMessage { Course = course, }; mail.CreateHtmlBody(confirmEmail); foreach (var a in GetSupplementReadings(course, schedule)) { mail.Attachments.Add(a); } using (var smtp = new SmtpClient()) { smtp.Send(mail); } } db.CourseHangfireJobs.RemoveRange(course.HangfireJobs.Where(hj => hj.HangfireId == context.BackgroundJob.Id)); db.SaveChanges(); } }
public static DbQuery <Course> GetCourseIncludes(MedSimDbContext context) { return(context.Courses.Include("CourseParticipants.Participant.ProfessionalRole") .Include("CourseParticipants.Participant.Department.Institution") .Include("Department.Institution.Culture") .Include("CourseFormat.CourseType")); }
public static DbQuery<Course> GetCourseIncludes(MedSimDbContext context) { return context.Courses.Include("CourseParticipants.Participant.ProfessionalRole") .Include("CourseParticipants.Participant.Department.Institution") .Include("Department.Institution.Culture") .Include("CourseFormat.CourseType"); }
public void TestCreateIcal() { using (var db = new MedSimDbContext()) { var bm = GetTestAllRolesPrincipal(); var course = db.Courses.Find(Guid.Parse("0ca5d24f-292e-4004-bb08-096db4b440ad")); using (var appt = new AppointmentStream()) { using (var cal = Appointment.CreateCourseAppointment(course, bm.Identity)) { appt.Add(cal); using (var fileStream = File.Create(AppDomain.CurrentDomain.BaseDirectory + "calendar.ics")) { appt.GetStreams().First().CopyTo(fileStream); } } using (var cal = Appointment.CreateFacultyCalendar(course)) { appt.Replace(cal); using (var fileStream = File.Create(AppDomain.CurrentDomain.BaseDirectory + "calendar2Appt.ics")) { appt.GetStreams().First().CopyTo(fileStream); } } } } }
public void TestCreateTimetablesDocx() { Course course; using (var db = new MedSimDbContext()) { var testId = Guid.Parse("0237b617-022c-4bed-8ce3-48356a86e63f");//"f1afbbbb-b72f-43f4-8b36-7837fe8d1b80" course = CreateDocxTimetable.GetCourseIncludes(db).First(c => c.Id == testId); using (var stream = CreateDocxTimetable.CreateTimetableDocx(course, templ, true)) { using (var fileStream = new FileStream("testCourseFacultyTimetable.docx", FileMode.Create)) { stream.WriteTo(fileStream); } } using (var stream = CreateDocxTimetable.CreateTimetableDocx(course, templ, false)) { using (var fileStream = new FileStream("testCourseParticipantTimetable.docx", FileMode.Create)) { stream.WriteTo(fileStream); } } } }
public void TestCreateDatabase() { MedSimDbContext db = null; try { db = new MedSimDbContext(); Assert.IsTrue(db.Cultures.Any(), "MedSimDbContext accessed, but no cultures seeded"); } catch (DataException e) { var inner = e.InnerException as DbEntityValidationException; if (inner != null) { Debug.Write(string.Join("\r\n", inner.EntityValidationErrors.Select(i => string.Join(";", i.ValidationErrors.Select(v => v.ErrorMessage))))); } throw; } finally { if (db != null) { db.Dispose(); } } }
public static DbQuery<Course> GetCourseIncludes(MedSimDbContext context) { DbQuery<Course> returnVar = context.Courses; foreach (var i in _includeList) { returnVar = returnVar.Include(i); } return returnVar; }
static string GetMigrationId() { using (var db = new MedSimDbContext()) { string query = "select top 1 MigrationId from [dbo].[__MigrationHistory] where [ContextKey] = '" + typeof(MedSimDbContext).FullName + "' order by LEFT(MigrationId, 15) desc"; return(db.Database.SqlQuery <string>(query).FirstOrDefault()); } }
public void TestTreeTopMapping() { using (MedSimDbContext db = new MedSimDbContext()) { var u = db.Scenarios.ProjectToDto <Scenario, ScenarioDto>(CurrentUser).ToList(); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(u, Newtonsoft.Json.Formatting.Indented)); } }
public static DbQuery <Course> GetCourseIncludes(MedSimDbContext repo) { return(CreateDocxTimetable.GetCourseIncludes(repo) .Include("CourseParticipants.Department.Institution.Culture") .Include("Room") .Include("FacultyMeetingRoom") .Include("CourseFormat.CourseType.CandidatePrereadings")); }
public MedSimDtoRepository(IPrincipal user, MedSimDbContext validationContext = null) { _contextProvider = new EFContextProvider <MedSimDbContext>(/*user , allowedRoles: new[] { RoleConstants.AccessAllData } */); _currentUser = new CurrentPrincipal(user, validationContext); _validationHelper = new ValidateMedSim(_currentUser); _contextProvider.BeforeSaveEntitiesDelegate += BeforeSaveEntities; _contextProvider.AfterSaveEntitiesDelegate += _validationHelper.AfterSave; _user = user; }
static string GetMigrationId() { using (var db = new MedSimDbContext()) { const string query = "select top 1 MigrationId from __MigrationHistory order by LEFT(MigrationId, 15) desc"; return db.Database.SqlQuery<string>(query).FirstOrDefault(); } }
public static DbQuery <Course> GetCourseIncludes(MedSimDbContext context) { DbQuery <Course> returnVar = context.Courses; foreach (var i in _includeList) { returnVar = returnVar.Include(i); } return(returnVar); }
public MedSimDtoRepository(IPrincipal user, MedSimDbContext validationContext = null) { _contextProvider = new EFContextProvider<MedSimDbContext>(/*user , allowedRoles: new[] { RoleConstants.AccessAllData } */); _currentUser = new CurrentPrincipal(user, validationContext); _validationHelper = new ValidateMedSim(_currentUser); _contextProvider.BeforeSaveEntitiesDelegate += BeforeSaveEntities; _contextProvider.AfterSaveEntitiesDelegate += _validationHelper.AfterSave; _user = user; }
public CurrentPrincipal(IPrincipal principal, MedSimDbContext context = null) { _context = context; _contextOwner = context == null; if (principal.Identity.IsAuthenticated) { AdminLevel = GetLevel(principal); PrincipalName = principal.Identity.Name; OtherRoles = GetOtherRoles(principal); } }
public CurrentPrincipal(IPrincipal principal, MedSimDbContext context = null) { _context = context; _contextOwner = context == null; if (principal.Identity.IsAuthenticated) { AdminLevel = GetLevel(principal); PrincipalName = principal.Identity.Name; IsSiteAdmin = principal.IsInRole(RoleConstants.SiteAdmin); } }
public void TestCourseInvite() { Course course; using (var context = new MedSimDbContext()) { var courseQueryable = CoursePlanningController.GetCourseIncludes(context); course = courseQueryable.AsNoTracking().First(c => c.CourseParticipants.Any(cp=>cp.IsFaculty) && c.CourseParticipants.Any(cp => !cp.IsFaculty)); } WriteMail(new CourseInvite { CourseParticipant = course.CourseParticipants.First() }); }
public void TestComplexDtoTreeMapping() { //var test = MapperConfig.GetLambda<Participant, ParticipantDto>(new[] { "Department", "Department.Institution", "Department.Manikins", "Department.Manikins.CourseSlotScenarios", "ProfessionalRole.CourseParticipants" }); //Console.WriteLine(test); var test2 = MapperConfig.GetToDtoLambda <Course, CourseDto>(CurrentUser, new[] { "CourseParticipants", "CourseFormat.CourseSlots.Activity.ActivityChoices", "CourseSlotActivities", "CourseSlotPresenters", "CourseScenarioFacultyRoles", "CourseFormat.CourseType.Scenarios" }); Console.WriteLine(test2); using (MedSimDbContext db = new MedSimDbContext()) { var c = db.Courses.Select(test2).First(); /* * var c = db.Courses.Select(m => new CourseDto() * { * CourseParticipants = m.CourseParticipants.Select(cp => new CourseParticipantDto() * { * ParticipantId = cp.ParticipantId, * }).ToList(), * CourseFormat = new CourseFormatDto() * { * Id = m.CourseFormat.Id, * CourseSlots = m.CourseFormat.CourseSlots.Select(cs => new CourseSlotDto() * { * Id = cs.Id, * MinutesDuration = cs.MinutesDuration, * Day = cs.Day, * Activity = cs.Activity==null * ?null * :new CourseActivityDto() * { * Id = cs.Activity.Id, * ActivityChoices = cs.Activity.ActivityChoices.Select(at => new ActivityDto() * { * Id = m.Id, * }).ToList() * } * }).ToList() * } * }).First(); */ Console.Write(Newtonsoft.Json.JsonConvert.SerializeObject(c, Newtonsoft.Json.Formatting.Indented)); } }
public static void DeleteOrphans() { using (var db = new MedSimDbContext()) { var threeWeeksPrior = DateTime.UtcNow.AddDays(-21); var dpts = db.Departments.Include("Participants").Where(d => !d.AdminApproved && d.CreatedUtc < threeWeeksPrior && !d.Participants.Any()).ToList(); db.Departments.RemoveRange(dpts); db.SaveChanges(); var insts = db.Institutions.Where(i => !i.AdminApproved && i.CreatedUtc < threeWeeksPrior && !i.Departments.Any()); db.Institutions.RemoveRange(insts); db.SaveChanges(); } }
public void TestCourseInvite() { Course course; using (var context = new MedSimDbContext()) { var courseQueryable = MailExtensions.GetCourseIncludes(context); course = courseQueryable.AsNoTracking().First(c => c.CourseParticipants.Any(cp => cp.IsFaculty) && c.CourseParticipants.Any(cp => !cp.IsFaculty)); } WriteMail(new CourseInvite { CourseParticipant = course.CourseParticipants.First() }); }
public static void RescheduleReadings(Course course, MedSimDbContext context) { var existingJobs = context.CourseHangfireJobs.Where(ch => ch.CourseId == course.Id).ToList(); foreach (var ej in existingJobs) { BackgroundJob.Delete(ej.HangfireId); context.CourseHangfireJobs.Remove(ej); } context.SaveChanges(); context.CourseHangfireJobs.AddRange(EnqueReading(course)); context.SaveChanges(); }
public void MyTestInitialize() { Guid userId; IEnumerable<string> roles; using (var db = new MedSimDbContext()) { userId = (from u in db.Users where u.Email == "*****@*****.**" select u.Id).First(); roles = (from r in db.Roles where r.Users.Any(u => u.UserId == userId) select r.Name).ToList(); } _repo = new MedSimDtoRepository(new MockIPrincipal()); }
internal static void Create(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("CreateAdmin.Create should not be being used in a production environment - security changes required"); #endif if (!context.Roles.Any()) { var roleStore = new RoleStore<AspNetRole,Guid,AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole,Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessAllData }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessInstitution }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.SiteAdmin }; roleManager.Create(role); var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); foreach(var user in context.Users.Where(u=>u.Department.Institution.Name== "Starship").ToList()) { var result = userManager.AddPassword(userId: user.Id, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.AccessAllData); } else { throw new DbSeedException(result.Errors); } } } }
public void MyTestInitialize() { Guid userId; IEnumerable <string> roles; using (var db = new MedSimDbContext()) { userId = (from u in db.Users where u.Email == "*****@*****.**" select u.Id).First(); roles = (from r in db.Roles where r.Users.Any(u => u.UserId == userId) select r.Name).ToList(); } _repo = new MedSimDtoRepository(new MockIPrincipal()); }
public void TestNestedWhere() { using (MedSimDbContext db = new MedSimDbContext()) { Expression <Func <Institution, InstitutionDto> > i = u => new InstitutionDto { Id = u.Id, Departments = u.Departments.Where(d => d.Abbreviation == "ced").Select(d => new DepartmentDto { Id = d.Id, Abbreviation = d.Abbreviation }).ToList() }; var insts = db.Institutions.Select(i); //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(insts, Newtonsoft.Json.Formatting.Indented)); Console.WriteLine(i); //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(i, Newtonsoft.Json.Formatting.Indented)); } }
internal static void Create(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("CreateAdmin.Create should not be being used in a production environment - security changes required"); #endif if (!context.Roles.Any()) { var roleStore = new RoleStore <AspNetRole, Guid, AspNetUserRole>(context); var roleManager = new RoleManager <AspNetRole, Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessAllData }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessInstitution }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.SiteAdmin }; roleManager.Create(role); var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); foreach (var user in context.Users.Where(u => u.Department.Institution.Name == "Starship").ToList()) { var result = userManager.AddPassword(userId: user.Id, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.AccessAllData); } else { throw new DbSeedException(result.Errors); } } } }
public void TestEntityMappingNavProperty() { const string propName = "Department"; using (MedSimDbContext db = new MedSimDbContext()) { var mapNavEx = MapperConfig.GetToDtoLambda <Participant, ParticipantDto>(CurrentUser, new[] { propName }); Console.WriteLine(mapNavEx.ToString()); var part = db.Users.Include(propName).AsNoTracking().First(p => p.UserName == testUserName); var partVm = db.Users.Select(mapNavEx).First(p => p.Email == part.Email); Assert.AreEqual(part.FullName, partVm.FullName); Assert.AreEqual(part.Department.Id, partVm.Department.Id); Assert.AreEqual(part.Department.InstitutionId, partVm.Department.InstitutionId); } }
public void TestCreateTimetableDocx() { const string templ = @"C:\Users\OEM\Documents\Visual Studio 2015\Projects\SimPlanner\SP.Web\App_Data\CourseTimeTableTemplate.docx"; Course course; using (var db = new MedSimDbContext()) { var testId = Guid.Parse("f1afbbbb-b72f-43f4-8b36-7837fe8d1b80"); course = CreateDocxTimetable.GetCourseIncludes(db).First(c=>c.Id == testId); using (var stream = CreateDocxTimetable.CreateTimetableDocx(course, templ)) { using (var fileStream = new FileStream("testCourseTimetable.docx", FileMode.Create)) { stream.WriteTo(fileStream); } } } }
public void TestEntityMappingCollection() { const string collectionPropName = "CourseParticipants"; using (MedSimDbContext db = new MedSimDbContext()) { var mapNavEx = MapperConfig.GetToDtoLambda <Participant, ParticipantDto>(CurrentUser, new[] { collectionPropName }); Console.WriteLine(mapNavEx.ToString()); var part = db.Users.Include(collectionPropName).AsNoTracking().First(p => p.UserName == testUserName); var partVm = db.Users.Select(mapNavEx).First(p => p.Email == part.Email); Assert.AreEqual(part.FullName, partVm.FullName); var cp = part.CourseParticipants.First(); var cpvm = partVm.CourseParticipants.First(); Assert.AreEqual(cp.ParticipantId, cpvm.ParticipantId); Assert.AreEqual(cp.CourseId, cpvm.CourseId); } }
public static ParticipantSummary GetParticipantSummary(MedSimDbContext context, Guid userId, DateTime?after = null) { var returnVar = new ParticipantSummary(); if (!after.HasValue) { after = SqlDateTime.MinValue.Value; } returnVar.CourseSummary = (from cp in context.CourseParticipants let course = cp.Course where cp.ParticipantId == userId && !course.Cancelled && course.StartFacultyUtc >= after group cp by course.CourseFormat into cf select new ParticipantCourseSummary { CourseName = cf.Key.CourseType.Abbreviation + " " + cf.Key.Description, FacultyCount = cf.Count(c => c.IsFaculty), AtendeeCount = cf.Count(c => !c.IsFaculty) }).ToList(); returnVar.PresentationSummary = (from csp in context.CourseSlotPresenters let course = csp.Course where csp.ParticipantId == userId && !course.Cancelled && course.StartFacultyUtc >= after && csp.CourseSlot.Activity != null group csp by csp.CourseSlot.Activity into a select new FacultyPresentationRoleSummary { Description = a.Key.CourseType.Abbreviation + "-" + a.Key.Name, Count = a.Count() }).ToList(); returnVar.SimRoleSummary = (from csfr in context.CourseScenarioFacultyRoles let course = csfr.Course where csfr.ParticipantId == userId && !course.Cancelled && course.StartFacultyUtc >= after group csfr by csfr.FacultyScenarioRole into fsr select new FacultySimRoleSummary { RoleName = fsr.Key.Description, Count = fsr.Count() }).ToList(); return(returnVar); }
public static PriorExposures GetExposures(MedSimDbContext context, Guid courseId, Guid userId) { //to do - check authorization var course = (from c in context.Courses.Include(co => co.CourseParticipants).Include(co => co.CourseFormat) where c.Id == courseId select c).First(); //only interested in faculty var participantIds = (from cp in course.CourseParticipants where !cp.IsFaculty select cp.ParticipantId).ToList(); //however, if they have been faculty for a scenario or activity, we want to know that var otherCourses = (from c in context.Courses.Include(co => co.CourseSlotActivities).Include(co => co.CourseParticipants) where c.Id != courseId && c.CourseFormat.CourseTypeId == course.CourseFormat.CourseTypeId && !c.Cancelled && c.CourseParticipants.Any(cp => participantIds.Contains(cp.ParticipantId)) select c).ToList(); var returnVar = new PriorExposures { ScenarioParticipants = new Dictionary<Guid, HashSet<Guid>>(), ActivityParticipants = new Dictionary<Guid, HashSet<Guid>>(), BookedManikins = GetBookedManikins(context, course) }; foreach (var oc in otherCourses) { var participants = (from cp in oc.CourseParticipants select cp.ParticipantId).Intersect(participantIds).ToList(); foreach (var csa in oc.CourseSlotActivities) { if (csa.ActivityId.HasValue) { returnVar.ActivityParticipants.AddRangeOrCreate(csa.ActivityId.Value, participants); } else { returnVar.ScenarioParticipants.AddRangeOrCreate(csa.ScenarioId.Value, participants); } } } return returnVar; }
public static PriorExposures GetExposures(MedSimDbContext context, Guid courseId) { //to do - check authorization var course = (from c in context.Courses.Include(co => co.CourseParticipants).Include(co => co.CourseFormat) where c.Id == courseId select c).First(); //only interested in faculty var participantIds = (from cp in course.CourseParticipants where !cp.IsFaculty select cp.ParticipantId).ToList(); //however, if they have been faculty for a scenario or activity, we want to know that var otherCourses = (from c in context.Courses.Include(co => co.CourseSlotActivities).Include(co => co.CourseParticipants) where c.Id != courseId && c.CourseFormat.CourseTypeId == course.CourseFormat.CourseTypeId && !c.Cancelled && c.CourseParticipants.Any(cp => participantIds.Contains(cp.ParticipantId)) select c).ToList(); var returnVar = new PriorExposures { ScenarioParticipants = new Dictionary <Guid, HashSet <Guid> >(), ActivityParticipants = new Dictionary <Guid, HashSet <Guid> >(), }; foreach (var oc in otherCourses) { var participants = (from cp in oc.CourseParticipants select cp.ParticipantId).Intersect(participantIds).ToList(); foreach (var csa in oc.CourseSlotActivities) { if (csa.ActivityId.HasValue) { returnVar.ActivityParticipants.AddRangeOrCreate(csa.ActivityId.Value, participants); } else { returnVar.ScenarioParticipants.AddRangeOrCreate(csa.ScenarioId.Value, participants); } } } return(returnVar); }
public void TestCreateDatabase() { MedSimDbContext db = null; try { db = new MedSimDbContext(); Assert.IsTrue(db.Cultures.Any(), "MedSimDbContext accessed, but no cultures seeded"); } catch(DataException e) { var inner = e.InnerException as DbEntityValidationException; if (inner!=null) { Debug.Write(string.Join("\r\n", inner.EntityValidationErrors.Select(i=>string.Join(";",i.ValidationErrors.Select(v=>v.ErrorMessage))))); } throw; } finally { if (db!=null) db.Dispose(); } }
public static ParticipantSummary GetParticipantSummary(MedSimDbContext context, Guid userId, DateTime? after = null) { var returnVar = new ParticipantSummary(); if (!after.HasValue) { after = SqlDateTime.MinValue.Value; } returnVar.CourseSummary = (from cp in context.CourseParticipants let course = cp.Course where cp.ParticipantId == userId && !course.Cancelled && course.StartUtc >= after group cp by course.CourseFormat into cf select new ParticipantCourseSummary { CourseName = cf.Key.CourseType.Abbreviation + " " + cf.Key.Description, FacultyCount = cf.Count(c => c.IsFaculty), AtendeeCount = cf.Count(c => !c.IsFaculty) }).ToList(); returnVar.PresentationSummary = (from csp in context.CourseSlotPresenters let course = csp.Course where csp.ParticipantId == userId && !course.Cancelled && course.StartUtc >= after && csp.CourseSlot.Activity != null group csp by csp.CourseSlot.Activity into a select new FacultyPresentationRoleSummary { Description = a.Key.CourseType.Abbreviation + "-" + a.Key.Name, Count = a.Count() }).ToList(); returnVar.SimRoleSummary = (from csfr in context.CourseScenarioFacultyRoles let course = csfr.Course where csfr.ParticipantId == userId && !course.Cancelled && course.StartUtc >= after group csfr by csfr.FacultyScenarioRole into fsr select new FacultySimRoleSummary { RoleName = fsr.Key.Description, Count = fsr.Count() }).ToList(); return returnVar; }
public void TestEntityMappingNavProperty() { const string propName = "Department"; using (MedSimDbContext db = new MedSimDbContext()) { var mapNavEx = MapperConfig.GetToDtoLambda<Participant, ParticipantDto>(CurrentUser, new[] { propName }); Console.WriteLine(mapNavEx.ToString()); var part = db.Users.Include(propName).AsNoTracking().First(p => p.UserName == testUserName); var partVm = db.Users.Select(mapNavEx).First(p => p.Email == part.Email); Assert.AreEqual(part.FullName, partVm.FullName); Assert.AreEqual(part.Department.Id, partVm.Department.Id); Assert.AreEqual(part.Department.InstitutionId, partVm.Department.InstitutionId); } }
public void TestComplexDtoTreeMapping() { //var test = MapperConfig.GetLambda<Participant, ParticipantDto>(new[] { "Department", "Department.Institution", "Department.Manikins", "Department.Manikins.CourseSlotScenarios", "ProfessionalRole.CourseParticipants" }); //Console.WriteLine(test); var test2 = MapperConfig.GetToDtoLambda<Course, CourseDto>(CurrentUser, new[] { "CourseParticipants", "CourseFormat.CourseSlots.Activity.ActivityChoices", "CourseSlotActivities", "CourseSlotPresenters", "CourseScenarioFacultyRoles", "CourseFormat.CourseType.Scenarios"}); Console.WriteLine(test2); using (MedSimDbContext db = new MedSimDbContext()) { var c = db.Courses.Select(test2).First(); /* var c = db.Courses.Select(m => new CourseDto() { CourseParticipants = m.CourseParticipants.Select(cp => new CourseParticipantDto() { ParticipantId = cp.ParticipantId, }).ToList(), CourseFormat = new CourseFormatDto() { Id = m.CourseFormat.Id, CourseSlots = m.CourseFormat.CourseSlots.Select(cs => new CourseSlotDto() { Id = cs.Id, MinutesDuration = cs.MinutesDuration, Day = cs.Day, Activity = cs.Activity==null ?null :new CourseActivityDto() { Id = cs.Activity.Id, ActivityChoices = cs.Activity.ActivityChoices.Select(at => new ActivityDto() { Id = m.Id, }).ToList() } }).ToList() } }).First(); */ Console.Write(Newtonsoft.Json.JsonConvert.SerializeObject(c, Newtonsoft.Json.Formatting.Indented)); } }
public void TestNestedWhere() { using (MedSimDbContext db = new MedSimDbContext()) { Expression<Func<Institution, InstitutionDto>> i = u => new InstitutionDto { Id = u.Id, Departments = u.Departments.Where(d => d.Abbreviation == "ced").Select(d => new DepartmentDto { Id = d.Id, Abbreviation = d.Abbreviation }).ToList() }; var insts = db.Institutions.Select(i); //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(insts, Newtonsoft.Json.Formatting.Indented)); Console.WriteLine(i); //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(i, Newtonsoft.Json.Formatting.Indented)); } }
public void TestEntityMappingCollection() { const string collectionPropName = "CourseParticipants"; using (MedSimDbContext db = new MedSimDbContext()) { var mapNavEx = MapperConfig.GetToDtoLambda<Participant, ParticipantDto>(CurrentUser, new[] { collectionPropName }); Console.WriteLine(mapNavEx.ToString()); var part = db.Users.Include(collectionPropName).AsNoTracking().First(p => p.UserName == testUserName); var partVm = db.Users.Select(mapNavEx).First(p => p.Email == part.Email); Assert.AreEqual(part.FullName, partVm.FullName); var cp = part.CourseParticipants.First(); var cpvm = partVm.CourseParticipants.First(); Assert.AreEqual(cp.ParticipantId, cpvm.ParticipantId); Assert.AreEqual(cp.CourseId, cpvm.CourseId); } }
public void TestTreeTopMapping() { using (MedSimDbContext db = new MedSimDbContext()) { var u = db.Scenarios.ProjectToDto<Scenario, ScenarioDto>(CurrentUser).ToList(); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(u,Newtonsoft.Json.Formatting.Indented)); } }
public SummaryDataController(MedSimDbContext context) { _context = context; }
public static void Seed(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("this should not be being used in a production environment - security changes required"); #endif try { if (!context.Roles.Any()) { //not in production //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, // "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate"); // var roleStore = new RoleStore<AspNetRole, Guid, AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole, Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.Admin }; roleManager.Create(role); } if (!context.Users.Any()) { var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); var user = new AspNetUser { Email = "*****@*****.**", UserName = "******" }; var result = userManager.Create(user, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.Admin); } else { throw new DbSeedException(result.Errors); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }
public static DbQuery<Course> GetCourseIncludes(MedSimDbContext repo) { return CreateDocxTimetable.GetCourseIncludes(repo) .Include("CourseParticipants.Department.Institution.Culture").Include("Room").Include("FacultyMeetingRoom"); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(() => MedSimDbContext.Create());//CreateAdmin.Create(newDb); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "SimPlanner"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(90.0), // In production mode set AllowInsecureHttp = false AllowInsecureHttp = false }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); /* * below allows access token in url * app.UseOAuthAuthorizationServer(OAuthOptions); // Added this line * * // Enable the application to retrieve tokens from query string to authenticate users * app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() * { * Provider = new HeaderOrQueryStringOAuthBearerProvider() * }); */ // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); /*app.UseTwitterAuthentication( * consumerKey: "", * consumerSecret: "");*/ /*app.UseLinkedInAuthentication( * clientId: "", * clientSecret: "");*/ app.UseFacebookAuthentication( new FacebookAuthenticationOptions { AppId = "1715030692085751", AppSecret = "1a27773a799393e3571dec634b3a0487", Scope = { "email" }, Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); return(Task.FromResult(true)); } /*, OnApplyRedirect = context => * { * context.Response.Redirect(context.RedirectUri); * }, OnReturnEndpoint = context => * { * return Task.FromResult(true); * } */ } }); app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = "425898604892-b2rt4ta4lu0n2d8mi084jsigdgdjd016.apps.googleusercontent.com ", ClientSecret = "DQDWtwQgEAjVLyTrFHT0EBUC" }); }
public static async Task <EmailResult <CourseFacultyInvite> > SendMultiInvites(ICollection <Guid> courseIds, ICollection <Guid> participantIds, IPrincipal currentPrincipal, MedSimDbContext repo) { var existing = await repo.CourseFacultyInvites.Where(cfi => courseIds.Contains(cfi.CourseId) && participantIds.Contains(cfi.ParticipantId)) .ToHashSetAsync(cfi => Tuple.Create(cfi.CourseId, cfi.ParticipantId)); existing.UnionWith((await repo.CourseParticipants .Where(cp => courseIds.Contains(cp.CourseId) && participantIds.Contains(cp.ParticipantId)).ToListAsync()) .Select(cfi => Tuple.Create(cfi.CourseId, cfi.ParticipantId))); var allInvites = new List <CourseFacultyInvite>(courseIds.Count * participantIds.Count - existing.Count); foreach (var c in courseIds) { foreach (var p in participantIds) { if (!existing.Contains(Tuple.Create(c, p))) { allInvites.Add(new CourseFacultyInvite { CourseId = c, ParticipantId = p }); } } } var success = new ConcurrentBag <CourseFacultyInvite>(); var fail = new ConcurrentBag <CourseFacultyInvite>(); var allCourseIds = allInvites.ToHashSet(i => i.CourseId); var courses = await repo.Courses.Include("CourseFormat.CourseType").Where(c => allCourseIds.Contains(c.Id)).ToDictionaryAsync(u => u.Id); var allInvitees = allInvites.ToLookup(i => i.ParticipantId); var allInviteeIds = allInvitees.Select(i => i.Key); var userRepo = (DbSet <Participant>)repo.Users; var users = await userRepo.Include("Department.Institution.Culture").Where(p => allInviteeIds.Contains(p.Id)).ToDictionaryAsync(u => u.Id); var currentUser = await userRepo.Include("Department").Include("ProfessionalRole") .SingleAsync(u => u.UserName == currentPrincipal.Identity.Name); using (var parallelEmails = new ParallelSmtpEmails()) { foreach (var g in allInvitees) { var mail = new MailMessage(); var recipient = users[g.Key]; mail.To.AddParticipants(recipient); var requestEmail = new MultiCourseInvite { PersonRequesting = currentUser, Courses = g.Select(c => courses[c.CourseId]), Recipient = recipient }; mail.CreateHtmlBody(requestEmail); parallelEmails.Send(mail, s => { if (s == null) { foreach (var ci in g) { success.Add(ci); } } else { foreach (var ci in g) { fail.Add(ci); } } }); } await parallelEmails.SendingComplete(); } return(new EmailResult <CourseFacultyInvite> { SuccessRecipients = success.ToArray(), FailRecipients = fail.ToArray() }); }
public static Dictionary<Guid, DateTime> GetManikinsInForRepair(MedSimDbContext context, string userName) { return (from m in context.ManikinServices select new { m.ManikinId, m.Sent }).ToDictionary(k => k.ManikinId, v => v.Sent); }
public static IEnumerable<KeyValuePair<Guid, string>> GetBookedManikins(MedSimDbContext context, Course course) { var refStart = course.StartUtc; var refFinish = course.FinishCourseUtc(); return (from csm in context.CourseSlotManikins let c = csm.Course let lastDay = c.CourseDays.FirstOrDefault(cd => cd.Day == c.CourseFormat.DaysDuration) let cFinish = lastDay == null ? DbFunctions.AddMinutes(c.StartUtc, c.DurationMins) : DbFunctions.AddMinutes(lastDay.StartUtc, lastDay.DurationMins) where c.Id != course.Id && c.StartUtc < refFinish && refStart < cFinish select new { csm.ManikinId, c.CourseFormat.Description, c.Department.Abbreviation }) .ToKeyValuePairList(a => a.ManikinId, a => a.Abbreviation + '-' + a.Description); }
public CustomUserStore(MedSimDbContext context) : base(context) { }
public static void Seed(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("this should not be being used in a production environment - security changes required"); #endif try { if (!context.Roles.Any()) { //not in production //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, // "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate"); // var roleStore = new RoleStore <AspNetRole, Guid, AspNetUserRole>(context); var roleManager = new RoleManager <AspNetRole, Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.Admin }; roleManager.Create(role); } if (!context.Users.Any()) { var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); var user = new AspNetUser { Email = "*****@*****.**", UserName = "******" }; var result = userManager.Create(user, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.Admin); } else { throw new DbSeedException(result.Errors); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }
public static async Task SendNewCourseParticipantNotificationsAsync(IEnumerable <CourseParticipant> courseParticipants, MedSimDbContext repo, IPrincipal principal) { //logic: //get all courses hapening after now where the currentUser is not an organiser, and group by each organiser var currentUser = repo.Users.Include("Department").Include("ProfessionalRole").Single(u => u.UserName == principal.Identity.Name); var courseIds = courseParticipants.ToHashSet(cp => cp.CourseId); var organisers = repo.CourseParticipants.Include("Course.CourseFormat.CourseType") .Include("Participant.Department.Institution") .Include("Course.Department.Institution.Culture") .Where(cp => courseIds.Contains(cp.CourseId) && cp.IsOrganiser && !cp.Course.CourseParticipants.Any(ap => ap.IsOrganiser && ap.ParticipantId == currentUser.Id)) .ToLookup(cp => cp.Participant); using (var client = new ParallelSmtpEmails()) { foreach (var o in organisers) { var n = new MultiCourseInviteResonse { Courses = o.Select(cp => cp.Course), PersonResponding = currentUser }; var mail = new MailMessage(); mail.To.AddParticipants(o.Key); mail.CreateHtmlBody(n); client.Send(mail); } await client.SendingComplete(); } }