Exemple #1
0
 protected void SetUpDatabaseTypes()
 {
     ImplementationManager.Load(
         typeof(MicrosoftSQLImplementation).Assembly,
         typeof(MySqlImplementation).Assembly,
         typeof(OracleImplementation).Assembly);
 }
        public void SyntaxHelperTest_GetRuntimeName_MultipleCalls(DatabaseType dbType, string runtime, string wrapped)
        {
            // NOTE: Oracle does not support such shenanigans https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements008.htm
            // "neither quoted nor nonquoted identifiers can contain double quotation marks or the null character (\0)."

            ImplementationManager.Load(new DirectoryInfo(TestContext.CurrentContext.TestDirectory));

            var syntaxHelper = ImplementationManager.GetImplementation(dbType).GetQuerySyntaxHelper();

            var currentName = runtime;

            for (int i = 0; i < 10; i++)
            {
                if (i % 2 == 0)
                {
                    Assert.AreEqual(runtime, currentName);
                    currentName = syntaxHelper.EnsureWrapped(currentName);
                    currentName = syntaxHelper.EnsureWrapped(currentName);
                    currentName = syntaxHelper.EnsureWrapped(currentName);
                }
                else
                {
                    Assert.AreEqual(wrapped, currentName);
                    currentName = syntaxHelper.GetRuntimeName(currentName);
                    currentName = syntaxHelper.GetRuntimeName(currentName);
                    currentName = syntaxHelper.GetRuntimeName(currentName);
                }
            }
        }
Exemple #3
0
        /// <summary>
        ///     Scrubs a user, removes everything from points to posts and topics.
        /// </summary>
        /// <param name="user"></param>
        public async Task <IPipelineProcess <MembershipUser> > ScrubUsers(MembershipUser user)
        {
            // Get the pipelines
            var pipes = ForumConfiguration.Instance.PipelinesUserScrub;

            // The model to process
            var piplineModel = new PipelineProcess <MembershipUser>(user);

            // Get instance of the pipeline to use
            var pipeline = new Pipeline <IPipelineProcess <MembershipUser>, MembershipUser>(_context);

            // Register the pipes
            var allMembershipUserPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <MembershipUser> > >();

            // Loop through the pipes and add the ones we want
            foreach (var pipe in pipes)
            {
                if (allMembershipUserPipes.ContainsKey(pipe))
                {
                    pipeline.Register(allMembershipUserPipes[pipe]);
                }
            }

            // Process the pipeline
            return(await pipeline.Process(piplineModel));
        }
Exemple #4
0
 public void Setup()
 {
     ImplementationManager.Load(
         typeof(MicrosoftSQLImplementation).Assembly,
         typeof(MySqlImplementation).Assembly,
         typeof(OracleImplementation).Assembly);
 }
Exemple #5
0
 public virtual void OneTimeSetUp()
 {
     ImplementationManager.Load(
         typeof(MicrosoftSQLImplementation).Assembly,
         typeof(MySqlImplementation).Assembly,
         typeof(OracleImplementation).Assembly);
 }
 public void Test_LoadAssemblies_FromDirectory()
 {
     ImplementationManager.Clear();
     Assert.IsNull(ImplementationManager.GetImplementations());
     ImplementationManager.Load(new DirectoryInfo(TestContext.CurrentContext.TestDirectory));
     Assert.GreaterOrEqual(ImplementationManager.GetImplementations().Count, 3);
 }
Exemple #7
0
        public void ServerHelper_ChangeDatabase_AdHoc(DatabaseType type, bool useApiFirst)
        {
            //create initial server reference
            var helper = ImplementationManager.GetImplementation(type).GetServerHelper();
            var server = new DiscoveredServer(helper.GetConnectionStringBuilder("loco", "bob", "franko", "wacky"));

            Assert.AreEqual("loco", server.Name);
            Assert.AreEqual("bob", server.GetCurrentDatabase().GetRuntimeName());

            //Use API to change databases
            if (useApiFirst)
            {
                server.ChangeDatabase("omgggg");
                Assert.AreEqual("loco", server.Name);
                Assert.AreEqual("omgggg", server.GetCurrentDatabase().GetRuntimeName());
            }

            //adhoc changes to builder
            server.Builder["Database"] = "Fisss";
            Assert.AreEqual("loco", server.Name);
            Assert.AreEqual("Fisss", server.GetCurrentDatabase().GetRuntimeName());

            server.Builder["Server"] = "Amagad";
            Assert.AreEqual("Amagad", server.Name);
            Assert.AreEqual("Fisss", server.GetCurrentDatabase().GetRuntimeName());
        }
        public void TestGetDataTable()
        {
            //create an Fo-Dicom dataset
            var ds = new DicomDataset(new List <DicomItem>()
            {
                new DicomShortString(DicomTag.PatientName, "Frank"),
                new DicomAgeString(DicomTag.PatientAge, "032Y"),
                new DicomDate(DicomTag.PatientBirthDate, new DateTime(2001, 1, 1))
            });

            var dt  = new DataTable();
            var row = ds.ToRow(dt);

            Assert.AreEqual("Frank", row["PatientName"]);
            Assert.AreEqual("032Y", row["PatientAge"]);
            Assert.AreEqual(new DateTime(2001, 1, 1), row["PatientBirthDate"]);

            //load the MySql implementation of FAnsi
            ImplementationManager.Load <MySqlImplementation>();

            //pick the location of the destination table (must exist, see ExampleTableCreation for how to create)
            var server = new DiscoveredServer(new MySqlConnectionStringBuilder("Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"));
            var table  = server.ExpectDatabase("MyDb").ExpectTable("MyCoolTable");

            //using (IBulkCopy bulkInsert = table.BeginBulkInsert())
            //{
            //    bulkInsert.Upload(dt);
            //}
        }
Exemple #9
0
        /// <summary>
        /// Executes the given SQL against the database + sends GO delimited statements as separate batches
        /// </summary>
        /// <param name="sql">Collection of SQL queries which can be separated by the use of "GO" on a line (works for all DBMS)</param>
        /// <param name="conn"></param>
        /// <param name="transaction"></param>
        /// <param name="performanceFigures">Line number the batch started at and the time it took to complete it</param>
        /// <param name="timeout">Timeout in seconds to run each batch in the <paramref name="sql"/></param>
        public void ExecuteBatchNonQuery(string sql, DbConnection conn, DbTransaction transaction, out Dictionary <int, Stopwatch> performanceFigures, int timeout = 30)
        {
            performanceFigures = new Dictionary <int, Stopwatch>();

            string sqlBatch = string.Empty;

            var helper = ImplementationManager.GetImplementation(conn).GetServerHelper();

            DbCommand cmd       = helper.GetCommand(string.Empty, conn, transaction);
            bool      hadToOpen = false;

            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
                hadToOpen = true;
            }

            int lineNumber = 1;

            sql += "\nGO";   // make sure last batch is executed.
            try
            {
                foreach (string line in sql.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    lineNumber++;

                    if (line.ToUpperInvariant().Trim() == "GO")
                    {
                        if (string.IsNullOrWhiteSpace(sqlBatch))
                        {
                            continue;
                        }

                        if (!performanceFigures.ContainsKey(lineNumber))
                        {
                            performanceFigures.Add(lineNumber, new Stopwatch());
                        }
                        performanceFigures[lineNumber].Start();

                        cmd.CommandText    = sqlBatch;
                        cmd.CommandTimeout = timeout;
                        cmd.ExecuteNonQuery();

                        performanceFigures[lineNumber].Stop();
                        sqlBatch = string.Empty;
                    }
                    else
                    {
                        sqlBatch += line + "\n";
                    }
                }
            }
            finally
            {
                if (hadToOpen)
                {
                    conn.Close();
                }
            }
        }
Exemple #10
0
 public static void Load()
 {
     ImplementationManager.Load <MicrosoftSQLImplementation>();
     ImplementationManager.Load <MySqlImplementation>();
     ImplementationManager.Load <PostgreSqlImplementation>();
     ImplementationManager.Load <OracleImplementation>();
 }
        /// <summary>
        /// <para>Creates a new server pointed at the <paramref name="builder"/> server. </para>
        ///
        /// <para><see cref="ImplementationManager"/> must have a loaded implementation for the DBMS type</para>
        /// </summary>
        /// <param name="builder">Determines the connection string and <see cref="DatabaseType"/> e.g. MySqlConnectionStringBuilder = DatabaseType.MySql</param>
        /// <exception cref="ImplementationNotFoundException"></exception>
        public DiscoveredServer(DbConnectionStringBuilder builder)
        {
            Helper = ImplementationManager.GetImplementation(builder).GetServerHelper();;

            //give helper a chance to mutilate the builder if he wants (also gives us a new copy of the builder incase anyone external modifies the old reference)
            Builder = Helper.GetConnectionStringBuilder(builder.ConnectionString);
        }
Exemple #12
0
        /// <summary>
        ///     Delete a category
        /// </summary>
        /// <param name="category"></param>
        public async Task <IPipelineProcess <Category> > Delete(Category category)
        {
            // Get the pipelines
            var categoryPipes = ForumConfiguration.Instance.PipelinesCategoryDelete;

            // The model to process
            var piplineModel = new PipelineProcess <Category>(category);

            // Get instance of the pipeline to use
            var pipeline = new Pipeline <IPipelineProcess <Category>, Category>(_context);

            // Register the pipes
            var allCategoryPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <Category> > >();

            // Loop through the pipes and add the ones we want
            foreach (var pipe in categoryPipes)
            {
                if (allCategoryPipes.ContainsKey(pipe))
                {
                    pipeline.Register(allCategoryPipes[pipe]);
                }
            }

            return(await pipeline.Process(piplineModel));
        }
        public void SyntaxHelperTest_GetRuntimeName(DatabaseType t, bool expectUpper)
        {
            ImplementationManager.Load(new DirectoryInfo(TestContext.CurrentContext.TestDirectory));

            var syntaxHelper = ImplementationManager.GetImplementation(t).GetQuerySyntaxHelper();

            Assert.AreEqual(expectUpper?"CHI":"chi", syntaxHelper.GetRuntimeName("\"TEST_ScratchArea\".public.\"Biochemistry\".\"chi\""));

            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("count(*) as Frank"));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("count(cast(1 as int)) as Frank"));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("[mydb].[mytbl].[mycol] as Frank"));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("[mydb].[mytbl].[mycol] as [Frank]"));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("\"Mydb\".\"mytbl\".\"mycol\" as \"Frank\""));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("[mydb].[mytbl].[mycol] as `Frank`"));
            Assert.AreEqual(expectUpper?"MYCOL":"mycol", syntaxHelper.GetRuntimeName("[mydb].[mytbl].[mycol]"));
            Assert.AreEqual(expectUpper?"ZOMBIE":"zombie", syntaxHelper.GetRuntimeName("dbo.GetMyCoolThing(\"Magic Fun Times\") as zombie"));

            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("`mydb`.`mytbl`.`mycol` as `Frank`"));

            Assert.AreEqual(expectUpper?"FRANK":"Frank", syntaxHelper.GetRuntimeName("\"mydb\".\"mytbl\".\"mycol\" as \"Frank\""));


            Assert.IsTrue(syntaxHelper.TryGetRuntimeName("\"mydb\".\"mytbl\".\"mycol\" as \"Frank\"", out string name));
            Assert.AreEqual(expectUpper?"FRANK":"Frank", name);
        }
Exemple #14
0
        /// <summary>
        /// Delete a post
        /// </summary>
        /// <param name="post"></param>
        /// <param name="ignoreLastPost"></param>
        /// <returns>Returns true if can delete</returns>
        public async Task <IPipelineProcess <Post> > Delete(Post post, bool ignoreLastPost)
        {
            // Get the pipelines
            var postPipes = ForumConfiguration.Instance.PipelinesPostDelete;

            // The model to process
            var piplineModel = new PipelineProcess <Post>(post);

            // Add extended data
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.IgnoreLastPost, ignoreLastPost);
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Username, HttpContext.Current.User.Identity.Name);

            // Get instance of the pipeline to use
            var pipeline = new Pipeline <IPipelineProcess <Post>, Post>(_context);

            // Register the pipes
            var allPostPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <Post> > >();

            // Loop through the pipes and add the ones we want
            foreach (var pipe in postPipes)
            {
                if (allPostPipes.ContainsKey(pipe))
                {
                    pipeline.Register(allPostPipes[pipe]);
                }
            }

            return(await pipeline.Process(piplineModel));
        }
Exemple #15
0
        public void TestGetValueString()
        {
            var date = new DateTime(2004, 1, 1);

            Assert.AreEqual("\"2004-01-01\"", CommandLineHelper.GetValueString(date));


            var fi = new FileInfo(TestContext.CurrentContext.TestDirectory);

            Assert.AreEqual($@"""{TestContext.CurrentContext.TestDirectory}""", CommandLineHelper.GetValueString(fi));

            const string db = "db-name";

            Assert.AreEqual(db, CommandLineHelper.GetValueString(db));

            ImplementationManager.Load <MicrosoftSQLImplementation>();

            //notice how server and db don't actually exist, thats cool they implement IMightNotExist
            var dbInfo = new DiscoveredServer(new SqlConnectionStringBuilder()
            {
                DataSource = "server"
            }).ExpectDatabase("db");

            Assert.AreEqual("--database-name=db --database-server=server", CommandLineHelper.CreateArgString("DbInfo", dbInfo));
        }
Exemple #16
0
        public void Server_Constructors(DatabaseType dbType)
        {
            var helper = ImplementationManager.GetImplementation(dbType).GetServerHelper();
            var server = new DiscoveredServer(helper.GetConnectionStringBuilder("localhost", null, "franko", "wacky").ConnectionString, dbType);

            Assert.AreEqual("localhost", server.Name);
        }
Exemple #17
0
 protected virtual void OneTimeSetUp()
 {
     ImplementationManager.Load <MicrosoftSQLImplementation>();
     ImplementationManager.Load <MySqlImplementation>();
     ImplementationManager.Load <OracleImplementation>();
     ImplementationManager.Load <PostgreSqlImplementation>();
 }
Exemple #18
0
        public void ServerHelper_ChangeDatabase_AdHoc(DatabaseType type, bool useApiFirst)
        {
            if (type == DatabaseType.Oracle)
            {
                Assert.Inconclusive("FAnsiSql understanding of Database cannot be encoded in DbConnectionStringBuilder sadly so we can end up with DiscoveredServer with no GetCurrentDatabase");
            }

            //create initial server reference
            var helper = ImplementationManager.GetImplementation(type).GetServerHelper();
            var server = new DiscoveredServer(helper.GetConnectionStringBuilder("loco", "bob", "franko", "wacky"));

            Assert.AreEqual("loco", server.Name);
            Assert.AreEqual("bob", server.GetCurrentDatabase().GetRuntimeName());

            //Use API to change databases
            if (useApiFirst)
            {
                server.ChangeDatabase("omgggg");
                Assert.AreEqual("loco", server.Name);
                Assert.AreEqual("omgggg", server.GetCurrentDatabase().GetRuntimeName());
            }

            //adhoc changes to builder
            server.Builder["Database"] = "Fisss";
            Assert.AreEqual("loco", server.Name);
            Assert.AreEqual("Fisss", server.GetCurrentDatabase().GetRuntimeName());

            server.Builder["Server"] = "Amagad";
            Assert.AreEqual("Amagad", server.Name);
            Assert.AreEqual("Fisss", server.GetCurrentDatabase().GetRuntimeName());
        }
Exemple #19
0
        public void EqualityTest_DiscoveredServer_AreEqual(string constr1, DatabaseType type1, string constr2, DatabaseType type2)
        {
            ImplementationManager.Load(
                typeof(MicrosoftSQLImplementation).Assembly,
                typeof(OracleImplementation).Assembly,
                typeof(MySqlImplementation).Assembly
                );

            var s1 = new DiscoveredServer(constr1, type1);
            var s2 = new DiscoveredServer(constr2, type2);

            Assert.AreEqual(s1, s2);
            Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode());

            Assert.AreEqual(s1.ExpectDatabase("MyDb"), s2.ExpectDatabase("MyDb"));
            Assert.AreEqual(s1.ExpectDatabase("MyDb").GetHashCode(), s2.ExpectDatabase("MyDb").GetHashCode());

            Assert.AreEqual(s1.ExpectDatabase("Mydb"), s2.ExpectDatabase("MyDb"));
            Assert.AreEqual(s1.ExpectDatabase("Mydb").GetHashCode(), s2.ExpectDatabase("MyDb").GetHashCode());

            Assert.AreNotEqual(s1.ExpectDatabase("MyDb"), s2.ExpectDatabase("MyDb2"));

            //This does not affect things since we are expecting a specific database anyway
            s1.ChangeDatabase("Dave");
            Assert.AreNotEqual(s1, s2);
            Assert.AreEqual(s1.ExpectDatabase("MyDb"), s2.ExpectDatabase("MyDb"));
            Assert.AreEqual(s1.ExpectDatabase("MyDb").GetHashCode(), s2.ExpectDatabase("MyDb").GetHashCode());
        }
Exemple #20
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Post> > Edit(Post post, HttpPostedFileBase[] files, bool isTopicStarter, string postedTopicName, string postedContent)
        {
            // Get the pipelines
            var postCreatePipes = ForumConfiguration.Instance.PipelinesPostUpdate;

            // Set the post to topic starter
            post.IsTopicStarter = isTopicStarter;

            // The model to process
            var piplineModel = new PipelineProcess <Post>(post);

            // Add the files for the post
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.PostedFiles, files);
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Name, postedTopicName);
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Content, postedContent);
            piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Username, HttpContext.Current.User.Identity.Name);

            // Get instance of the pipeline to use
            var pipeline = new Pipeline <IPipelineProcess <Post>, Post>(_context);

            // Register the pipes
            var allPostPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <Post> > >();

            // Loop through the pipes and add the ones we want
            foreach (var pipe in postCreatePipes)
            {
                if (allPostPipes.ContainsKey(pipe))
                {
                    pipeline.Register(allPostPipes[pipe]);
                }
            }

            // Process the pipeline
            return(await pipeline.Process(piplineModel));
        }
        public void Test_GetFullyQualifiedName(DatabaseType dbType)
        {
            ImplementationManager.Load(new DirectoryInfo(TestContext.CurrentContext.TestDirectory));
            var syntaxHelper = ImplementationManager.GetImplementation(dbType).GetQuerySyntaxHelper();

            var name = syntaxHelper.EnsureFullyQualified("mydb", null, "Troll", ",,,");

            Assert.AreEqual(",,,", syntaxHelper.GetRuntimeName(name));

            switch (dbType)
            {
            case DatabaseType.MicrosoftSQLServer:
                Assert.AreEqual("[mydb]..[Troll].[,,,]", name);
                break;

            case DatabaseType.MySql:
                Assert.AreEqual("`mydb`.`Troll`.`,,,`", name);
                break;

            case DatabaseType.Oracle:
                Assert.AreEqual("\"MYDB\".\"TROLL\".\",,,\"", name);
                break;

            case DatabaseType.PostgreSql:
                Assert.AreEqual("\"mydb\".public.\"Troll\".\",,,\"", name);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(dbType), dbType, null);
            }
        }
Exemple #22
0
        public void CheckFiles()
        {
            ImplementationManager.Load(
                typeof(MicrosoftSQLServerHelper).Assembly,
                typeof(OracleServerHelper).Assembly,
                typeof(MySqlServerHelper).Assembly);

            var file = Path.Combine(TestContext.CurrentContext.TestDirectory, TestFilename);

            Assert.IsTrue(File.Exists(file), "Could not find " + TestFilename);

            var doc = XDocument.Load(file);

            var root = doc.Element("TestDatabases");

            if (root == null)
            {
                throw new Exception("Missing element 'TestDatabases' in " + TestFilename);
            }

            var settings = root.Element("Settings");

            if (settings == null)
            {
                throw new Exception("Missing element 'Settings' in " + TestFilename);
            }

            var e = settings.Element("AllowDatabaseCreation");

            if (e == null)
            {
                throw new Exception("Missing element 'AllowDatabaseCreation' in " + TestFilename);
            }

            AllowDatabaseCreation = Convert.ToBoolean(e.Value);

            e = settings.Element("TestScratchDatabase");
            if (e == null)
            {
                throw new Exception("Missing element 'TestScratchDatabase' in " + TestFilename);
            }

            _testScratchDatabase = e.Value;

            foreach (XElement element in root.Elements("TestDatabase"))
            {
                var          type = element.Element("DatabaseType").Value;
                DatabaseType databaseType;

                if (!DatabaseType.TryParse(type, out databaseType))
                {
                    throw new Exception("Could not parse DatabaseType " + type);
                }

                var constr = element.Element("ConnectionString").Value;

                TestConnectionStrings.Add(databaseType, constr);
            }
        }
        public void SyntaxHelperTest_GetRuntimeName(DatabaseType dbType, string expected, string forInput)
        {
            ImplementationManager.Load(new DirectoryInfo(TestContext.CurrentContext.TestDirectory));

            var syntaxHelper = ImplementationManager.GetImplementation(dbType).GetQuerySyntaxHelper();

            Assert.AreEqual(expected, syntaxHelper.GetRuntimeName(forInput));
        }
        //[TestCase(DatabaseType.Oracle)]
        public void CreateParameter(DatabaseType type)
        {
            var syntax = ImplementationManager.GetImplementation(type).GetQuerySyntaxHelper();

            var declaration = syntax.GetParameterDeclaration("@bob", new DatabaseTypeRequest(typeof(string), 10));

            StringAssert.Contains("@bob", declaration);
        }
Exemple #25
0
        public void Test_ExpectDatabase(DatabaseType type, bool upperCase)
        {
            var helper = ImplementationManager.GetImplementation(type).GetServerHelper();
            var server = new DiscoveredServer(helper.GetConnectionStringBuilder("loco", "db", "frank", "kangaro"));
            var db     = server.ExpectDatabase("omg");

            Assert.AreEqual(upperCase?"OMG":"omg", db.GetRuntimeName());
        }
Exemple #26
0
        public void ServerHelper_GetCurrentDatabase_WhenNoneSpecified(DatabaseType type)
        {
            var helper  = ImplementationManager.GetImplementation(type).GetServerHelper();
            var builder = helper.GetConnectionStringBuilder("");
            var server  = new DiscoveredServer(builder);

            Assert.AreEqual(null, server.Name);
            Assert.AreEqual(null, server.GetCurrentDatabase());
        }
Exemple #27
0
        /// <summary>
        /// <para>
        /// Call before running <see cref="Startup"/>.  Sets up basic assembly redirects to the execution directory
        /// (see <see cref="AssemblyResolver"/>) and FAnsiSql DBMS implementations.
        /// </para>
        /// <para>Note that this method can be used even if you do not then go on to use <see cref="Startup"/> e.g. if you
        /// are performing a low level operation like patching</para>
        /// </summary>
        public static void PreStartup()
        {
            AssemblyResolver.SetupAssemblyResolver();

            ImplementationManager.Load <MicrosoftSQLImplementation>();
            ImplementationManager.Load <MySqlImplementation>();
            ImplementationManager.Load <OracleImplementation>();
            ImplementationManager.Load <PostgreSqlImplementation>();
        }
        public void WorkedExampleTest()
        {
            //pick some tags that we are interested in (determines the table schema created)
            var toCreate = new ImageTableTemplate()
            {
                Columns = new[] {
                    new ImageColumnTemplate(DicomTag.SOPInstanceUID),
                    new ImageColumnTemplate(DicomTag.Modality)
                    {
                        AllowNulls = true
                    },
                    new ImageColumnTemplate(DicomTag.PatientID)
                    {
                        AllowNulls = true
                    }
                }
            };

            //load the Sql Server implementation of FAnsi
            ImplementationManager.Load <MicrosoftSQLImplementation>();

            //decide where you want to create the table
            var server = new DiscoveredServer(@"Server=localhost\sqlexpress;Database=mydb;Integrated Security=true;", FAnsi.DatabaseType.MicrosoftSQLServer);
            var db     = server.ExpectDatabase("test");

            //create the table
            var tbl = db.CreateTable("MyCoolTable", toCreate.GetColumns(FAnsi.DatabaseType.MicrosoftSQLServer));

            //add a column for where the image is on disk
            tbl.AddColumn("FileLocation", new DatabaseTypeRequest(typeof(string), 500), true, 500);

            //Create a DataTable in memory for the data we read from disk
            DataTable dt = new DataTable();

            dt.Columns.Add("SOPInstanceUID");
            dt.Columns.Add("Modality");
            dt.Columns.Add("PatientID");
            dt.Columns.Add("FileLocation");

            //Load some dicom files and copy tag data into DataTable (where tag exists)
            foreach (string file in Directory.EnumerateFiles(@"C:\temp\TestDicomFiles", "*.dcm", SearchOption.AllDirectories))
            {
                var dcm = DicomFile.Open(file);
                var ds  = dcm.Dataset;

                dt.Rows.Add(

                    DicomTypeTranslaterReader.GetCSharpValue(dcm.Dataset, DicomTag.SOPInstanceUID),
                    ds.Contains(DicomTag.Modality) ? DicomTypeTranslaterReader.GetCSharpValue(dcm.Dataset, DicomTag.Modality) : DBNull.Value,
                    ds.Contains(DicomTag.PatientID) ? DicomTypeTranslaterReader.GetCSharpValue(dcm.Dataset, DicomTag.PatientID) : DBNull.Value,
                    file);
            }

            //put the DataTable into the database
            using (var insert = tbl.BeginBulkInsert())
                insert.Upload(dt);
        }
        public void Test_IsSupportedType(DatabaseType dbType, string sqlDbType, bool expectedOutcome)
        {
            ImplementationManager.Load <OracleImplementation>();
            ImplementationManager.Load <MicrosoftSQLImplementation>();
            ImplementationManager.Load <MySqlImplementation>();

            var tt = ImplementationManager.GetImplementation(dbType).GetQuerySyntaxHelper().TypeTranslater;

            Assert.AreEqual(expectedOutcome, tt.IsSupportedSQLDBType(sqlDbType), $"Unexpected result for IsSupportedSQLDBType with {dbType}.  Input was '{sqlDbType}' expected {expectedOutcome}");
        }
Exemple #30
0
        private static void PreStartup()
        {
            AssemblyResolver.SetupAssemblyResolver();

            ImplementationManager.Load(
                typeof(MicrosoftSQLImplementation).Assembly,
                typeof(MySqlImplementation).Assembly,
                typeof(OracleImplementation).Assembly
                );
        }