public void TestSpecificAllocationBlocks() { using (var context = new TrialDataContext()) { foreach (var part in GetMultipleParticipantCategories(new int[] { 1, 20000 })) { if (part.TrialArm != RandomisationArm.NotSet) { var nextBlock = Engine.Get1stBlockWithSpaceForSpecificAllocation(part, out RandomisationStrata strata, context); if (nextBlock == null) { Console.WriteLine("no spare allocations found for male:{0}, wt:{1}, arm:{2}", part.IsMale, part.AdmissionWeight, part.TrialArm); continue; } int parts = context.Participants.Count(p => p.AllocationBlockId == nextBlock.Id && p.TrialArm == part.TrialArm); BlockComponent b = nextBlock.GetComponents(); int allocs = b.Ratios[part.TrialArm] * b.Repeats; string outcome = string.Format("first block (Id:{0}) with space for allocation has {1} of {2} allocations taken", nextBlock.Id, parts, allocs); Assert.IsTrue(allocs > parts, outcome); Console.WriteLine(outcome); } } } }
public static bool AnyStudyCentres() { using (var t = new TrialDataContext()) { return(t.StudyCentres.Any()); } }
public void TestTrialDataSeed() { var tst = new SeedTestUtility(); using (var t = new TrialDataContext()) { tst.SeedTest(t); } }
private static IQueryable <UnsuccessfulFollowUp> NeedsRedo(TrialDataContext repo) { var sites = repo.StudyCentres.ToList(); var predicate = PredicateBuilder.New <UnsuccessfulFollowUp>(); foreach (var s in sites) { predicate = predicate.Or(p => p.ParticipantId >= s.Id && p.ParticipantId <= s.MaxIdForSite && !(p.Id >= s.Id && p.Id <= s.MaxIdForSite)); } return(repo.UnsuccessfulFollowUps.AsExpandable().Where(predicate)); }
public static void DefineNewStudyCentres(IEnumerable <StudySiteItemModel> newStudyCentres) { using (var t = new TrialDataContext()) { if (t.StudyCentres.Any()) { throw new InvalidOperationException("Study Centres cannot be modified after creation"); } foreach (StudySiteItemModel s in newStudyCentres) { t.StudyCentres.Add(ViewModel.StudySitesViewModel.MapToStudySite(s)); } t.SaveChanges(true); } }
public static void Process(TrialDataContext repo) { var needsRedo = NeedsRedo(repo); if (needsRedo.Any()) { repo.Database.ExecuteSqlCommand("ALTER TABLE [UnsuccessfulFollowUps] DROP CONSTRAINT [PK_dbo.UnsuccessfulFollowUps]"); foreach (var g in needsRedo.GroupBy(u => u.TrialParticipant.Centre)) { var ids = g.Select(u => u.Id); repo.Database.ExecuteSqlCommand($"UPDATE [UnsuccessfulFollowUps] SET [Id] = [Id] + {g.Key.Id} WHERE [Id] <= {ids.Max()} AND [Id]>= {ids.Min()}"); } repo.Database.ExecuteSqlCommand("ALTER TABLE [UnsuccessfulFollowUps] ADD CONSTRAINT [PK_dbo.UnsuccessfulFollowUps] PRIMARY KEY(Id)"); } }
static ILookup <int, List <VaccineAdministered> > VaccineDiff(string db1Filename, string db2Filename) { IEnumerable <VaccineAdministered> va1; using (var db = new TrialDataContext(db1Filename)) { va1 = db.VaccinesAdministered.AsNoTracking().ToList(); } IEnumerable <VaccineAdministered> va2; using (var db = new TrialDataContext(db2Filename)) { va2 = db.VaccinesAdministered.AsNoTracking().ToList(); } return((from va in va1.Concat(va2).ToList() group va by va.AdministeredAt.ToString() + va.VaccineId.ToString() into s select s).Select(g => g.ToList()).ToList().ToLookup(g => g.Count)); }
public void TestMappingVaccines() { Mapper.Initialize(x => { x.AddProfile <PatientProfiles>(); }); using (var context = new TrialDataContext()) { foreach (var p in context.Participants.Include("VaccinesAdministered").Take(10).ToList()) { var pb = Mapper.Map <ParticipantBaseModel>(p); Assert.IsNotNull(pb.VaccinesAdministered); var pm = Mapper.Map <ParticipantProgressModel>(p); Assert.IsNotNull(pm.VaccineModelsAdministered); Assert.IsNotNull(pm.VaccinesAdministered); } } }
void ReplaceDb() { var pw = new BlowTrial.View.PleaseWait(); pw.Show(); string currentPath = TrialDataContext.GetDbPath(); if (_repository != null) { _repository.Dispose(); _repository = null; } System.IO.File.Move(currentPath, currentPath.InsertDateStampToFileName()); TransferFile.AllowUpdate(_transferLog, fi => { fi.MoveTo(currentPath); }); pw.Close(); }
static void UpdateVA(string source, string dest) { List <VaccineAdministered> sourceVas; using (var db = new TrialDataContext(source)) { sourceVas = db.VaccinesAdministered.AsNoTracking().ToList(); } using (var db = new TrialDataContext(dest)) { var destVas = db.VaccinesAdministered.ToList(); int i = 0; while (sourceVas.Count > i && destVas.Count > i && sourceVas[i].Id == destVas[i].Id) { destVas[i].ParticipantId = sourceVas[i].ParticipantId; i++; } db.SaveChanges(); } }
static IEnumerable <DbSummary> DbInfo(string filename) { List <DbSummary> returnVar = new List <DbSummary>(); using (var db = new TrialDataContext(filename)) { foreach (var studyCentre in db.StudyCentres.ToList()) { returnVar.Add(new DbSummary { CentreName = studyCentre.Name, MostRecentDemographicUpdate = db.Participants.Where(p => p.CentreId == studyCentre.Id).Max(p => p.RecordLastModified), MostRecentEnrollment = db.Participants.Where(p => p.CentreId == studyCentre.Id).Max(p => p.RegisteredAt), MostRecentVaccineAdmin = db.VaccinesAdministered.Where(va => va.Id >= studyCentre.Id && va.Id <= studyCentre.MaxIdForSite).Max(va => va.AdministeredAt), MostRecentVaccineUpdate = db.VaccinesAdministered.Where(va => va.Id >= studyCentre.Id && va.Id <= studyCentre.MaxIdForSite).Max(va => va.RecordLastModified), Participants = db.Participants.Where(p => p.CentreId == studyCentre.Id).Count(), ParticipantsWithVaccinesAdmin = db.VaccinesAdministered.Where(va => va.Id >= studyCentre.Id && va.Id <= studyCentre.MaxIdForSite).GroupBy(va => va.ParticipantId).Count(), TotalVaccinesAdmin = db.VaccinesAdministered.Where(va => va.Id >= studyCentre.Id && va.Id <= studyCentre.MaxIdForSite).Count() }); } } return(returnVar); }
static Dictionary <bool, int[]> ParticipantDiff(string db1Filename, string db2Filename) { int[] participants1; int[] centres1; using (var db = new TrialDataContext(db1Filename)) { participants1 = db.Participants.Select(p => p.Id).ToArray(); centres1 = db.StudyCentres.Select(c => c.Id).ToArray(); } int[] participants2; using (var db = new TrialDataContext(db2Filename)) { participants2 = (from p in db.Participants where centres1.Contains(p.CentreId) select p.Id).ToArray(); } var returnVar = new Dictionary <bool, int[]> { { true, participants1.Where(p => !participants2.Contains(p)).ToArray() }, { false, participants2.Where(p => !participants1.Contains(p)).ToArray() } }; return(returnVar); }
public void TestRandomising() { var parts = new List <Participant>(GetMultipleParticipantCategories(1)); DateTime now = DateTime.Now; DateTime yesterday = now - TimeSpan.FromDays(1); int maxId; using (var db = new TrialDataContext()) { maxId = (from p in db.Participants where p.Id < 20000 select p.Id).Max(); } var ballanceDictionary = Enum.GetValues(typeof(RandomisationStrata)).Cast <RandomisationStrata>().ToDictionary(r => r, r => false); using (var repo = new Repository(typeof(TrialDataContext))) { //ratio 2:9:18-19 const int dummyPtCount = 2500; const int smallWtCount = dummyPtCount * 2 / 29; const int midWtCount = smallWtCount + dummyPtCount * 9 / 29; var rnd = new Random(); for (int i = 1; i < dummyPtCount; i++) { string dummyInfo = "dummyInfo" + i; int weight; bool isMale = i % 2 == 0; if (i < smallWtCount) { weight = rnd.Next(400, 999); } else if (i < midWtCount) { weight = rnd.Next(1001, 1499); } else { weight = rnd.Next(1501, 1999); } var p = repo.AddParticipant(dummyInfo, dummyInfo, dummyInfo, weight, 32, yesterday, "", "1111111", isMale, true, now, 1, MaternalBCGScarStatus.NoScar, null, null); Assert.AreNotEqual(RandomisationArm.NotSet, p.TrialArm); RandomisationStrata cat; if (weight < 1000) { cat = RandomisationStrata.SmallestWeightMale; } else if (weight >= 1500) { cat = RandomisationStrata.TopWeightMale; } else { cat = RandomisationStrata.MidWeightMale; } if (!isMale) { cat = (RandomisationStrata)((int)cat + 1); } Assert.AreEqual(cat, p.Block.RandomisationCategory); } } using (var context = new TrialDataContext()) { var allAllocations = (from p in context.Participants where p.CentreId == 1 group p by p.TrialArm).ToDictionary(p => p.Key, p => p.Count()); int total = allAllocations.Values.Sum(); const double tolerance = 0.015; const double thirdMin = 1.0 / 3 - tolerance; const double thirdMax = 1.0 / 3 + tolerance; foreach (var kv in allAllocations) { double ratio = (double)kv.Value / total; string msg = string.Format("{0} ratio {1}", kv.Key, ratio); Console.WriteLine(ratio); Assert.IsTrue(thirdMin <= ratio && ratio <= thirdMax, "ratio shoule be 1/3 " + msg); } foreach (var e in (from b in context.BalancedAllocations where b.StudyCentreId < 20000 select b)) { Assert.IsTrue(e.IsEqualised, "Balanced Allocations not set to true for Id:{0} (randomisationCat:{1})", e.Id, e.RandomisationCategory); } //teardown context.Database.ExecuteSqlCommand(String.Format("delete from Participants where Id > {0} and Id <20000", maxId)); } }
protected override void OnStartup(StartupEventArgs e) { _log = LogManager.GetLogger(typeof(App)); #if !DEBUG if (CurrentClickOnceVersion != null) { ThreadContext.Properties["deploymentVersion"] = CurrentClickOnceVersion; } this.DispatcherUnhandledException += Application_DispatcherUnhandledException; log4net.Config.XmlConfigurator.Configure(); #endif base.OnStartup(e); // AppDomain.CurrentDomain.SetData("DataDirectory", baseDir); //Application initialisation AutoMapperConfiguration.Configure(); /* * catch (Exception ex) * { * _log.Error("App_AutomapperConfigurationException", ex); * MessageBox.Show("An error has occured with automapper. An error has been logged, but this file will have to be attached and emailed to the application developer"); * throw; * } */ //Security CustomPrincipal customPrincipal = new CustomPrincipal(); AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal); ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown; //test if wizard needs to run #if !DEBUG try { #endif CodeBasedMigration.ApplyPendingMigrations <BlowTrial.Migrations.TrialData.TrialDataConfiguration>(TrialDataContext.GetConnectionString(), ContextCeConfiguration.ProviderInvariantName, true); CodeBasedMigration.ApplyPendingMigrations <BlowTrial.Migrations.Membership.MembershipConfiguration>(MembershipContext.GetConnectionString(), ContextCeConfiguration.ProviderInvariantName, true); #if !DEBUG } catch (Exception ex) { string usrErrMsg = null; if (ex.Message.StartsWith("Access to the database file is not allowed")) { string administratorInstructions = string.Format("User:{0}\nRequies modify permissions be allowed for folder:\n{1}\nAnd all files within", System.Security.Principal.WindowsIdentity.GetCurrent().Name, DataDirectory); usrErrMsg = "Cannot access database: \nPlease contact the systems administrator with the following message:\n" + administratorInstructions; } else { usrErrMsg = "An error has occured trying to access the database: \n" + ex.Message; } if (usrErrMsg != null) { _log.Error("App_FirstDatabaseAccessException", ex); MessageBox.Show(usrErrMsg); throw; } } #endif var backDetails = BlowTrialDataService.GetBackupDetails(); bool displayWizard = (backDetails.BackupData == null); if (!displayWizard && backDetails.BackupData.IsBackingUpToCloud) { using (var t = new TrialDataContext()) { displayWizard = !t.StudyCentres.Any(); } } if (displayWizard && !DisplayAppSettingsWizard()) { Shutdown(259); return; } // Create the ViewModel to which // the main window binds. var mainWindowVm = new MainWindowViewModel(); MainWindow window = new MainWindow(mainWindowVm); // When the ViewModel asks to be closed, // close the window. EventHandler handler = null; handler = delegate { window.Close(); if (!window.IsLoaded) //in case user cancelled { mainWindowVm.RequestClose -= handler; } }; mainWindowVm.RequestClose += handler; _log.InfoFormat("Application started {0}", DateTime.Now); window.Show(); }