Example #1
0
        private void AddBlankExternalCohortTable()
        {
            var newExternalCohortTable = new ExternalCohortTable(RepositoryLocator.DataExportRepository, "Blank Cohort Source " + Guid.NewGuid(), DatabaseType.MicrosoftSQLServer);

            Publish(newExternalCohortTable);
            Activate(newExternalCohortTable);
        }
Example #2
0
        public override void SetDatabaseObject(IActivateItems activator, ExternalCohortTable databaseObject)
        {
            base.SetDatabaseObject(activator, databaseObject);
            _externalCohortTable = databaseObject;

            serverDatabaseTableSelector1.DatabaseType = _externalCohortTable.DatabaseType;

            string password = null;

            try
            {
                password = _externalCohortTable.GetDecryptedPassword();
            }
            catch (Exception)
            {
                password = null;
            }

            serverDatabaseTableSelector1.SetExplicitDatabase(_externalCohortTable.Server, _externalCohortTable.Database, _externalCohortTable.Username, password);

            CommonFunctionality.AddHelp(tbTableName, "IExternalCohortTable.TableName");
            CommonFunctionality.AddHelp(tbPrivateIdentifierField, "IExternalCohortTable.PrivateIdentifierField");
            CommonFunctionality.AddHelp(tbReleaseIdentifierField, "IExternalCohortTable.ReleaseIdentifierField");
            CommonFunctionality.AddHelp(tbDefinitionTableForeignKeyField, "IExternalCohortTable.DefinitionTableForeignKeyField");

            CommonFunctionality.AddHelp(tbDefinitionTableName, "IExternalCohortTable.DefinitionTableName");

            CommonFunctionality.AddChecks(_externalCohortTable);
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            var db = serverDatabaseTableSelector1.GetDiscoveredDatabase();

            if (db == null)
            {
                MessageBox.Show("You must select a database");
                return;
            }
            if (PrivateIdentifierPrototype == null)
            {
                MessageBox.Show("You must select a private identifier datatype");
                return;
            }

            Wizard = new CreateNewCohortDatabaseWizard(db, Activator.RepositoryLocator.CatalogueRepository, Activator.RepositoryLocator.DataExportRepository, cbAllowNullReleaseIdentifiers.Checked);

            var popup = new PopupChecksUI("Creating Cohort Table", false);

            ExternalCohortTableCreatedIfAny = Wizard.CreateDatabase(PrivateIdentifierPrototype, popup);

            if (popup.GetWorst() <= CheckResult.Warning)
            {
                if (Activator.YesNo("Close Form?", "Close"))
                {
                    ParentForm.Close();
                }
            }
        }
 public ExecuteCommandCreateNewCohortFromFile(IActivateItems activator, FileInfo file, ExternalCohortTable externalCohortTable = null)
     : base(activator)
 {
     _file = file;
     ExternalCohortTable = externalCohortTable;
     UseTripleDotSuffix  = true;
 }
Example #5
0
        public ExecuteCommandCreateNewCohortFromCatalogue(IBasicActivateItems activator,

            [DemandsInitialization("Either a Catalogue with a single IsExtractionIdentifier column or a specific ExtractionInformation to query")]
            IMapsDirectlyToDatabaseTable toQuery,
            [DemandsInitialization(Desc_ExternalCohortTableParameter)]
            ExternalCohortTable ect,
            [DemandsInitialization(Desc_CohortNameParameter)]
            string cohortName,
            [DemandsInitialization(Desc_ProjectParameter)]
            Project project,
            [DemandsInitialization("Pipeline for executing the query, performing any required transforms on the output list and allocating release identifiers")]
            IPipeline pipeline) : base(activator, ect, cohortName, project, pipeline)
        {
            UseTripleDotSuffix = true;

            if (toQuery != null)
            {
                if (toQuery is Catalogue c)
                    SetExtractionIdentifierColumn(GetExtractionInformationFromCatalogue(c));
                else
                if (toQuery is ExtractionInformation ei)
                    SetExtractionIdentifierColumn(ei);
                else
                    throw new ArgumentException($"{nameof(toQuery)} must be a Catalogue or an ExtractionInformation but it was a {toQuery.GetType().Name}", nameof(toQuery));
            }

        }
Example #6
0
        public void TestExternalCohortTableProperties_SetFullValues()
        {
            var table = new ExternalCohortTable(RepositoryLocator.DataExportRepository, "ffff", DatabaseType.MicrosoftSQLServer);

            Assert.IsNull(table.Database);
            Assert.IsNull(table.Server);
            Assert.IsNull(table.TableName);
            Assert.IsNull(table.PrivateIdentifierField);
            Assert.IsNull(table.ReleaseIdentifierField);
            Assert.IsNull(table.DefinitionTableForeignKeyField);

            table.PrivateIdentifierField         = "[mydb]..[mytbl].[priv]";
            table.ReleaseIdentifierField         = "[mydb]..[mytbl].[rel]";
            table.DefinitionTableForeignKeyField = "[mydb]..[mytbl].[fk]";
            table.Database  = "mydb";
            table.Server    = "myserver";
            table.TableName = "[mydb]..[mytbl]";

            Assert.AreEqual("mydb", table.Database);
            Assert.AreEqual("myserver", table.Server);
            Assert.AreEqual("[mydb]..[mytbl]", table.TableName);
            Assert.IsNull(table.DefinitionTableName);

            Assert.AreEqual("[mydb]..[mytbl].[priv]", table.PrivateIdentifierField);
            Assert.AreEqual("[mydb]..[mytbl].[rel]", table.ReleaseIdentifierField);
            Assert.AreEqual("[mydb]..[mytbl].[fk]", table.DefinitionTableForeignKeyField);
        }
Example #7
0
        private string DescribeProblem(ExternalCohortTable externalCohortTable)
        {
            if (_exportChildProvider != null && _exportChildProvider.BlackListedSources.Contains(externalCohortTable))
            {
                return("Cohort Source database was unreachable");
            }

            return(null);
        }
Example #8
0
        public ExecuteCommandImportAlreadyExistingCohort(IBasicActivateItems activator, ExternalCohortTable externalCohortTable, IProject specificProject) : base(activator)
        {
            _externalCohortTable = externalCohortTable;
            this.specificProject = specificProject;

            if (specificProject != null && specificProject.ProjectNumber == null)
            {
                SetImpossible("Project does not have a ProjectNumber yet");
            }
        }
Example #9
0
        private void AddChildren(ExternalCohortTable externalCohortTable, DescendancyList descendancy)
        {
            var cohorts = Cohorts.Where(c => c.ExternalCohortTable_ID == externalCohortTable.ID).ToArray();

            foreach (ExtractableCohort cohort in cohorts)
            {
                cohort.InjectKnown(externalCohortTable);
            }

            AddToDictionaries(new HashSet <object>(cohorts), descendancy);
        }
Example #10
0
        private void Blacklist(ExternalCohortTable source, Exception ex)
        {
            BlackListedSources.Add(source);

            _errorsCheckNotifier.OnCheckPerformed(new CheckEventArgs("Could not reach cohort '" + source + "' (it may be slow responding or inaccessible due to user permissions)", CheckResult.Fail, ex));

            //tell them not to bother looking for the cohort data because its inaccessible
            foreach (ExtractableCohort cohort in Cohorts.Where(c => c.ExternalCohortTable_ID == source.ID).ToArray())
            {
                cohort.InjectKnown((ExternalCohortDefinitionData)null);
            }
        }
Example #11
0
        public ExternalCohortTableMenu(RDMPContextMenuStripArgs args, ExternalCohortTable externalCohortTable) : base(args, externalCohortTable)
        {
            var projectOnlyNode = args.Masquerader as CohortSourceUsedByProjectNode;

            if (projectOnlyNode != null)
            {
                Add(new ExecuteCommandShowSummaryOfCohorts(_activator, projectOnlyNode));
            }
            else
            {
                Add(new ExecuteCommandShowSummaryOfCohorts(_activator, externalCohortTable));
            }
        }
Example #12
0
        public ExecuteCommandCreateNewCohortByExecutingACohortIdentificationConfiguration(IActivateItems activator, ExternalCohortTable externalCohortTable = null) : base(activator)
        {
            _allConfigurations  = activator.CoreChildProvider.AllCohortIdentificationConfigurations;
            ExternalCohortTable = externalCohortTable;

            if (!_allConfigurations.Any())
            {
                SetImpossible("You do not have any CohortIdentificationConfigurations yet, you can create them through the 'Cohorts Identification Toolbox' accessible through Window=>Cohort Identification");
            }


            UseTripleDotSuffix = true;
        }
Example #13
0
        public virtual IAtomicCommandWithTarget SetTarget(DatabaseEntity target)
        {
            if (target is Project)
            {
                Project = (Project)target;
            }

            if (target is ExternalCohortTable)
            {
                ExternalCohortTable = (ExternalCohortTable)target;
            }

            return(this);
        }
        public SelectWhichCohortToImportUI(IActivateItems activator, ExternalCohortTable source) : base(activator)
        {
            _source = source;
            InitializeComponent();

            if (source == null)
            {
                return;
            }


            DataTable dt = ExtractableCohort.GetImportableCohortDefinitionsTable(source, out _displayMember, out _valueMember, out _versionMemberName, out _projectNumberMemberName);

            dataGridView1.DataSource = dt;
        }
Example #15
0
        protected override void SetBindings(BinderWithErrorProviderFactory rules, ExternalCohortTable databaseObject)
        {
            base.SetBindings(rules, databaseObject);

            Bind(tbID, "Text", "ID", e => e.ID);

            Bind(tbID, "Text", "ID", e => e.ID);
            Bind(tbName, "Text", "Name", e => e.Name);
            Bind(tbTableName, "Text", "TableName", e => e.TableName);
            Bind(tbPrivateIdentifierField, "Text", "PrivateIdentifierField", e => e.PrivateIdentifierField);
            Bind(tbReleaseIdentifierField, "Text", "ReleaseIdentifierField", e => e.ReleaseIdentifierField);
            Bind(tbDefinitionTableForeignKeyField, "Text", "DefinitionTableForeignKeyField", e => e.DefinitionTableForeignKeyField);

            Bind(tbDefinitionTableName, "Text", "DefinitionTableName", e => e.DefinitionTableName);
        }
Example #16
0
        public override void Execute()
        {
            base.Execute();


            //Create cohort store database
            var wizard = new CreateNewCohortDatabaseWizard(databaseToCreate, activator.RepositoryLocator.CatalogueRepository, activator.RepositoryLocator.DataExportRepository, allowNullReleaseIdentifiers);

            Created = wizard.CreateDatabase(new PrivateIdentifierPrototype(privateFieldName, privateFieldDataType), new ThrowImmediatelyCheckNotifier()
            {
                WriteToConsole = false
            });

            Publish(Created);
        }
Example #17
0
        public override CohortCreationRequest GetCohortCreationRequest(ExternalCohortTable externalCohortTable, IProject project, string cohortInitialDescription)
        {
            var ui = new CohortCreationRequestUI(this, externalCohortTable, project);

            if (!string.IsNullOrWhiteSpace(cohortInitialDescription))
            {
                ui.CohortDescription = cohortInitialDescription + " (" + Environment.UserName + " - " + DateTime.Now + ")";
            }

            if (ui.ShowDialog() != DialogResult.OK)
            {
                return(null);
            }

            return(ui.Result);
        }
Example #18
0
        private void CreateExternalCohortTableReference()
        {
            ExternalCohortTable alreadyExisting = DataExportRepository.GetAllObjects <ExternalCohortTable>()
                                                  .SingleOrDefault(external => external.Name.Equals(ExternalCohortTableNameInCatalogue));

            if (alreadyExisting != null)
            {
                //remove dependencies cohorts
                ExtractableCohort toCleanup = DataExportRepository.GetAllObjects <ExtractableCohort>().SingleOrDefault(ec => ec.OriginID == cohortIDInTestData);


                if (toCleanup != null)
                {
                    //cleanup any configs that use the cohort
                    foreach (
                        var configToCleanup in DataExportRepository.GetAllObjects <ExtractionConfiguration>()
                        .Where(config => config.Cohort_ID == toCleanup.ID))
                    {
                        configToCleanup.DeleteInDatabase();
                    }

                    toCleanup.DeleteInDatabase();
                }

                alreadyExisting.DeleteInDatabase();
            }

            var newExternal = new ExternalCohortTable(DataExportRepository, "TestExternalCohort", DatabaseType.MicrosoftSQLServer)
            {
                Database            = CohortDatabaseName,
                Server              = _cohortDatabase.Server.Name,
                DefinitionTableName = definitionTableName,
                TableName           = cohortTableName,
                Name     = ExternalCohortTableNameInCatalogue,
                Username = _cohortDatabase.Server.ExplicitUsernameIfAny,
                Password = _cohortDatabase.Server.ExplicitPasswordIfAny,
                PrivateIdentifierField         = "PrivateID",
                ReleaseIdentifierField         = "ReleaseID",
                DefinitionTableForeignKeyField = "cohortDefinition_id"
            };

            newExternal.SaveToDatabase();

            _externalCohortTable = newExternal;
        }
Example #19
0
        public void Create_ExternalCohortTable_Manually()
        {
            MemoryDataExportRepository repository = new MemoryDataExportRepository();
            var table = new ExternalCohortTable(repository, "My Cohort Database", DatabaseType.MicrosoftSQLServer);

            table.Database = "mydb";
            table.PrivateIdentifierField         = "chi";
            table.ReleaseIdentifierField         = "release";
            table.DefinitionTableForeignKeyField = "c_id";
            table.TableName           = "Cohorts";
            table.DefinitionTableName = "InventoryTable";
            table.Server = "superfastdatabaseserver\\sqlexpress";
            table.SaveToDatabase();

            var ex = Assert.Throws <Exception>(() => table.Check(new ThrowImmediatelyCheckNotifier()));

            Assert.AreEqual("Could not connect to Cohort database called 'My Cohort Database'", ex.Message);
        }
Example #20
0
        public CohortCreationRequestUI(IActivateItems activator, ExternalCohortTable target, Project project = null) : base(activator)
        {
            _target = target;

            InitializeComponent();

            if (_target == null)
            {
                return;
            }

            _repository = (DataExportRepository)_target.Repository;

            lblExternalCohortTable.Text = _target.ToString();

            SetProject(project);

            pbProject.Image      = CatalogueIcons.Project;
            pbCohortSource.Image = CatalogueIcons.ExternalCohortTable;
        }
Example #21
0
        /// <summary>
        /// Initialises common targetting parameters (where to store resulting identifiers etc)
        /// </summary>
        /// <param name="activator"></param>
        /// <param name="externalCohortTable"></param>
        /// <param name="cohortName"></param>
        /// <param name="project"></param>
        /// <param name="pipeline"></param>
        protected CohortCreationCommandExecution(IBasicActivateItems activator, ExternalCohortTable externalCohortTable, string cohortName, Project project, IPipeline pipeline) : base(activator)
        {
            var dataExport = activator.CoreChildProvider as DataExportChildProvider;

            //May be null
            _explicitCohortName = cohortName;
            ExternalCohortTable = externalCohortTable;
            Project             = project;
            Pipeline            = pipeline;

            if (dataExport == null)
            {
                SetImpossible("No data export repository available");
                return;
            }

            if (!dataExport.CohortSources.Any())
            {
                SetImpossible("There are no cohort sources configured, you must create one in the Saved Cohort tabs");
            }
        }
Example #22
0
        public ExecuteCommandCreateNewCohortFromFile(IBasicActivateItems activator,

                                                     [DemandsInitialization("A file containing private cohort identifiers")]
                                                     FileInfo file,

                                                     [DemandsInitialization(Desc_ExternalCohortTableParameter)]
                                                     ExternalCohortTable externalCohortTable,

                                                     [DemandsInitialization(Desc_CohortNameParameter)]
                                                     string cohortName,

                                                     [DemandsInitialization(Desc_ProjectParameter)]
                                                     Project project,

                                                     [DemandsInitialization("Pipeline for reading from the file and allocating release identifiers")]
                                                     IPipeline pipeline)
            : base(activator, externalCohortTable, cohortName, project, pipeline)
        {
            _file = file;
            UseTripleDotSuffix = true;
        }
Example #23
0
        private int?GetWhichCohortToImport(ExternalCohortTable ect)
        {
            // the cohorts in the database
            var available = ExtractableCohort.GetImportableCohortDefinitions(ect).Where(c => c.ID.HasValue).ToArray();

            // the ones we already know about
            var existing = new HashSet <int>(BasicActivator.RepositoryLocator.DataExportRepository.GetAllObjects <ExtractableCohort>().Select(c => c.OriginID));

            // new ones we don't know about yet
            available = available.Where(c => !existing.Contains(c.ID.Value)).ToArray();

            // if there are no new ones
            if (!available.Any())
            {
                BasicActivator.Show($"There are no new cohorts");
                return(null);
            }

            // we only care about ones associated to this project
            if (specificProject != null)
            {
                available = available.Where(a => a.ProjectNumber == specificProject.ProjectNumber).ToArray();

                if (!available.Any())
                {
                    BasicActivator.Show($"There are no new cohorts to import for ProjectNumber {specificProject.ProjectNumber}");
                    return(null);
                }
            }

            // pick which one to import
            if (BasicActivator.SelectObject("Import Cohort", available, out CohortDefinition cd))
            {
                return(cd.ID);
            }

            return(null);
        }
Example #24
0
        public ExternalCohortTableMenu(RDMPContextMenuStripArgs args, ExternalCohortTable externalCohortTable) : base(args, externalCohortTable)
        {
            _externalCohortTable = externalCohortTable;

            Items.Add(new ToolStripSeparator());
            Add(new ExecuteCommandCreateNewCohortFromFile(_activator, _externalCohortTable));
            Add(new ExecuteCommandCreateNewCohortByExecutingACohortIdentificationConfiguration(_activator, _externalCohortTable));
            Add(new ExecuteCommandCreateNewCohortFromCatalogue(_activator, externalCohortTable));
            Items.Add(new ToolStripSeparator());

            var projectOnlyNode = args.Masquerader as CohortSourceUsedByProjectNode;

            if (projectOnlyNode != null)
            {
                Add(new ExecuteCommandShowSummaryOfCohorts(_activator, projectOnlyNode));
            }
            else
            {
                Add(new ExecuteCommandShowSummaryOfCohorts(_activator, externalCohortTable));
            }

            Add(new ExecuteCommandImportAlreadyExistingCohort(_activator, _externalCohortTable));
        }
Example #25
0
        /// <inheritdoc/>
        public virtual CohortCreationRequest GetCohortCreationRequest(ExternalCohortTable externalCohortTable, IProject project, string cohortInitialDescription)
        {
            int    version;
            var    projectNumber = project?.ProjectNumber;
            string name;

            if (!this.TypeText("Name", "Enter name for cohort", 255, null, out name, false))
            {
                throw new Exception("User chose not to enter a name for the cohortand none was provided");
            }


            if (projectNumber == null)
            {
                if (this.SelectValueType("enter project number", typeof(int), 0, out object chosen))
                {
                    projectNumber = (int)chosen;
                }
                else
                {
                    throw new Exception("User chose not to enter a Project number and none was provided");
                }
            }


            if (this.SelectValueType("enter version number for cohort", typeof(int), 0, out object chosenVersion))
            {
                version = (int)chosenVersion;
            }
            else
            {
                throw new Exception("User chose not to enter a version number and none was provided");
            }


            return(new CohortCreationRequest(project, new CohortDefinition(null, name, version, projectNumber.Value, externalCohortTable), RepositoryLocator.DataExportRepository, cohortInitialDescription));
        }
Example #26
0
        public void EndToEndTest()
        {
            var cohortDatabaseNameWillBe = TestDatabaseNames.GetConsistentName("TbvCohort");

            _discoveredCohortDatabase = DiscoveredServerICanCreateRandomDatabasesAndTablesOn.ExpectDatabase(cohortDatabaseNameWillBe);

            //cleanup
            if (_discoveredCohortDatabase.Exists())
            {
                _discoveredCohortDatabase.Drop();
            }

            //create a normal catalogue
            CreateANormalCatalogue();

            //create a cohort database using wizard
            CreateNewCohortDatabaseWizard cohortDatabaseWizard = new CreateNewCohortDatabaseWizard(_discoveredCohortDatabase, CatalogueRepository, DataExportRepository, false);

            _externalCohortTable = cohortDatabaseWizard.CreateDatabase(
                new PrivateIdentifierPrototype(_nonTvfExtractionIdentifier)
                , new ThrowImmediatelyCheckNotifier());

            //create a table valued function
            CreateTvfCatalogue(cohortDatabaseNameWillBe);

            //Test 1
            TestThatQueryBuilderWithoutParametersBeingSetThrowsQueryBuildingException();

            PopulateCohortDatabaseWithRecordsFromNonTvfCatalogue();

            //Test 2
            TestWithParameterValueThatRowsAreReturned();

            //Test 3
            TestUsingTvfForAggregates();

            //Test 4
            TestAddingTvfToCIC();

            //Test 5
            TestDataExportOfTvf();

            //tear down
            DataExportRepository.GetAllObjects <ExtractableCohort>().Single().DeleteInDatabase();
            _externalCohortTable.DeleteInDatabase();

            _database.ExpectTable("NonTVFTable").Drop();
            _database.ExpectTableValuedFunction("GetTopXRandom").Drop();

            //delete global parameter
            ((AnyTableSqlParameter)_aggregate.GetAllParameters().Single()).DeleteInDatabase();
            //delete aggregate
            _aggregate.DeleteInDatabase();

            ((AnyTableSqlParameter)_cicAggregate.GetAllParameters().Single()).DeleteInDatabase();
            //delete aggregate
            _cicAggregate.DeleteInDatabase();

            //get rid of the cohort identification configuration
            _cic.DeleteInDatabase();
            _pipe.DeleteInDatabase();

            //get rid of the cohort database
            _discoveredCohortDatabase.Drop();

            _nonTvfCatalogue.DeleteInDatabase();
            _nonTvfTableInfo.DeleteInDatabase();

            _tvfCatalogue.DeleteInDatabase();
            _tvfTableInfo.DeleteInDatabase();
        }
Example #27
0
        private void GetCohortAvailability(ExternalCohortTable source)
        {
            DiscoveredServer server = null;

            Exception ex = null;

            //it obviously hasn't been initialised properly yet
            if (string.IsNullOrWhiteSpace(source.Server) || string.IsNullOrWhiteSpace(source.Database))
            {
                return;
            }

            try
            {
                server = DataAccessPortal.GetInstance().ExpectDatabase(source, DataAccessContext.DataExport).Server;
            }
            catch (Exception exception)
            {
                ex = exception;
            }

            if (server == null || !server.RespondsWithinTime(3, out ex) || !source.IsFullyPopulated())
            {
                Blacklist(source, ex);
                return;
            }

            try
            {
                using (var con = server.GetConnection())
                {
                    con.Open();

                    //Get all of the project numbers and remote origin ids etc from the source in one query
                    using (var cmd = server.GetCommand(source.GetExternalDataSql(), con))
                    {
                        cmd.CommandTimeout = 120;

                        using (var r = cmd.ExecuteReader())
                        {
                            while (r.Read())
                            {
                                //really should be only one here but still they might for some reason have 2 references to the same external cohort

                                if (_cohortsByOriginId.TryGetValue(Convert.ToInt32(r["OriginID"]), out HashSet <ExtractableCohort> result))
                                {
                                    //Tell the cohorts what their external data values are so they don't have to fetch them themselves individually
                                    foreach (ExtractableCohort c in result.Where(c => c.ExternalCohortTable_ID == source.ID))
                                    {
                                        //load external data from the result set
                                        var externalData = new ExternalCohortDefinitionData(r, source.Name);

                                        //tell the cohort about the data
                                        c.InjectKnown(externalData);

                                        lock (_oProjectNumberToCohortsDictionary)
                                        {
                                            //for performance also keep a dictionary of project number => compatible cohorts
                                            if (!ProjectNumberToCohortsDictionary.ContainsKey(externalData.ExternalProjectNumber))
                                            {
                                                ProjectNumberToCohortsDictionary.Add(externalData.ExternalProjectNumber, new List <ExtractableCohort>());
                                            }

                                            ProjectNumberToCohortsDictionary[externalData.ExternalProjectNumber].Add(c);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Blacklist(source, e);
            }
        }
Example #28
0
        private ExtractableCohort CommitCohortToNewProject(CohortIdentificationConfiguration cic, ExternalCohortTable externalCohortTable, IPipeline cohortCreationPipeline, string projectName, string cohortName, int projectNumber, out Project project)
        {
            //create a new data extraction Project
            project = new Project(_repos.DataExportRepository, projectName);
            project.ProjectNumber       = projectNumber;
            project.ExtractionDirectory = Path.GetTempPath();
            project.SaveToDatabase();

            //create a cohort
            var request = new CohortCreationRequest(project, new CohortDefinition(null, cohortName, 1, projectNumber, externalCohortTable), _repos.DataExportRepository, "Created by running cic " + cic.ID);

            request.CohortIdentificationConfiguration = cic;

            var engine = request.GetEngine(cohortCreationPipeline, new ThrowImmediatelyDataLoadEventListener());

            engine.ExecutePipeline(new GracefulCancellationToken());

            return(request.CohortCreatedIfAny);
        }
Example #29
0
 public ExecuteCommandCreateNewCohortFromCatalogue(IActivateItems activator, ExternalCohortTable externalCohortTable) : this(activator)
 {
     ExternalCohortTable = externalCohortTable;
 }
        public ExternalCohortTable CreateDatabase(PrivateIdentifierPrototype privateIdentifierPrototype, ICheckNotifier notifier)
        {
            if (!_targetDatabase.Exists())
            {
                notifier.OnCheckPerformed(new CheckEventArgs("Did not find database " + _targetDatabase + " on server so creating it", CheckResult.Success));
                _targetDatabase.Create();
            }

            try
            {
                var definitionTable = _targetDatabase.CreateTable("CohortDefinition", new[]
                {
                    new DatabaseColumnRequest("id", new DatabaseTypeRequest(typeof(int)))
                    {
                        AllowNulls = false, IsAutoIncrement = true, IsPrimaryKey = true
                    },
                    new DatabaseColumnRequest("projectNumber", new DatabaseTypeRequest(typeof(int)))
                    {
                        AllowNulls = false
                    },
                    new DatabaseColumnRequest("version", new DatabaseTypeRequest(typeof(int)))
                    {
                        AllowNulls = false
                    },
                    new DatabaseColumnRequest("description", new DatabaseTypeRequest(typeof(string), 3000))
                    {
                        AllowNulls = false
                    },
                    new DatabaseColumnRequest("dtCreated", new DatabaseTypeRequest(typeof(DateTime)))
                    {
                        AllowNulls = false, Default = MandatoryScalarFunctions.GetTodaysDate
                    }
                });


                var idColumn   = definitionTable.DiscoverColumn("id");
                var foreignKey = new DatabaseColumnRequest(_definitionTableForeignKeyField, new DatabaseTypeRequest(typeof(int)), false)
                {
                    IsPrimaryKey = true
                };


                var cohortTable = _targetDatabase.CreateTable("Cohort", new []
                {
                    new DatabaseColumnRequest(privateIdentifierPrototype.RuntimeName, privateIdentifierPrototype.DataType, false)
                    {
                        IsPrimaryKey = true
                    },
                    new DatabaseColumnRequest(_releaseIdentifierFieldName, new DatabaseTypeRequest(typeof(string), 300))
                    {
                        AllowNulls = AllowNullReleaseIdentifiers
                    },
                    foreignKey
                }
                                                              ,
                                                              //foreign key between id and cohortDefinition_id
                                                              new Dictionary <DatabaseColumnRequest, DiscoveredColumn>()
                {
                    { foreignKey, idColumn }
                }, true);


                notifier.OnCheckPerformed(new CheckEventArgs("About to create pointer to the source", CheckResult.Success));
                var pointer = new ExternalCohortTable(_dataExportRepository, "TestExternalCohort", _targetDatabase.Server.DatabaseType)
                {
                    DatabaseType                   = _targetDatabase.Server.DatabaseType,
                    Server                         = _targetDatabase.Server.Name,
                    Database                       = _targetDatabase.GetRuntimeName(),
                    Username                       = _targetDatabase.Server.ExplicitUsernameIfAny,
                    Password                       = _targetDatabase.Server.ExplicitPasswordIfAny,
                    Name                           = _targetDatabase.GetRuntimeName(),
                    TableName                      = cohortTable.GetRuntimeName(),
                    PrivateIdentifierField         = privateIdentifierPrototype.RuntimeName,
                    ReleaseIdentifierField         = _releaseIdentifierFieldName,
                    DefinitionTableForeignKeyField = _definitionTableForeignKeyField,
                    DefinitionTableName            = definitionTable.GetRuntimeName()
                };

                pointer.SaveToDatabase();

                notifier.OnCheckPerformed(new CheckEventArgs("successfully created reference to cohort source in data export manager", CheckResult.Success));

                notifier.OnCheckPerformed(new CheckEventArgs("About to run post creation checks", CheckResult.Success));
                pointer.Check(notifier);

                notifier.OnCheckPerformed(new CheckEventArgs("Finished", CheckResult.Success));

                return(pointer);
            }
            catch (Exception e)
            {
                notifier.OnCheckPerformed(
                    new CheckEventArgs("Entire setup failed with exception (double click to find out why)",
                                       CheckResult.Fail, e));
                return(null);
            }
        }