public void AdventureWorksTest()
        {
            const string providername = "System.Data.SqlClient";
            const string connectionString = @"Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=AdventureWorks";
            ProviderChecker.Check(providername, connectionString);

            var dbReader = new DatabaseReader(connectionString, providername);
            DatabaseSchema schema = null;
            try
            {
                schema = dbReader.ReadAll();
            }
            catch (SqlException exception)
            {
                Assert.Inconclusive("Cannot access database " + exception.Message);
            }
            var directory = TestHelper.CreateDirectory("AdventureWorks");
            const string @namespace = "AdventureWorks.Domain";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.Poco, WriteStoredProcedures = true };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            var procedures = directory.GetDirectories("Procedures").FirstOrDefault();
            if (procedures == null)
                Assert.Fail("Could not find Procedures subdirectory for stored procedures");
            var files = procedures.GetFiles("*.cs");

            var category = files.First(f => f.Name == "uspLogError.cs");
            var cs = File.ReadAllText(category.FullName);

            var ok = cs.Contains("public virtual DbCommand CreateCommand(int? errorLogId)");
            Assert.IsTrue(ok, "Should contain the uspLogError stored procedure (in standard AdventureWorks db)");
        }
        public void BuildGeneratedCodeTest()
        {
            //arrange
            var dbReader = TestHelper.GetNorthwindReader();
            var schema = dbReader.ReadAll();

            var directory = TestHelper.CreateDirectory("NorthwindCodeGen");
            const string @namespace = "Northwind.Domain";
            var settings = new CodeWriterSettings
                               {
                                   Namespace = @namespace,
                                   CodeTarget = CodeTarget.PocoNHibernateHbm,
                                   Namer = new PluralizingNamer(),
                                   WriteProjectFile = true
                               };

            var codeWriter = new CodeWriter(schema, settings);

            //act
            codeWriter.Execute(directory);

            //assert
            var csproj = Path.Combine(directory.FullName, "Northwind.Domain.csproj");
            Assert.IsTrue(File.Exists(csproj));

            //can we build it?
            var projectIsBuilt = BuildProject(csproj);
            Assert.IsTrue(projectIsBuilt); //yes we can
        }
        public void NHibernateFluentTest()
        {
            var schema = PrepareModel();

            var directory = TestHelper.CreateDirectory("MyTest");
            const string @namespace = "MyTest";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.PocoNHibernateFluent };

            var target = new CodeWriter(schema, settings);
            target.Execute(directory);

            var mapping = directory.GetDirectories("mapping").FirstOrDefault();
            if (mapping == null)
                Assert.Fail("Could not find Mapping subdirectory");
            var files = mapping.GetFiles("*.cs");
            var products = files.FirstOrDefault(f => f.Name == "ProductMapping.cs");
            Assert.IsNotNull(products, "Should have written Product class to map [Products] table");

            var category = files.FirstOrDefault(f => f.Name == "CategoryMapping.cs");
            Assert.IsNotNull(category, "Should have written Category class to map [Categories] table");

            var cs = File.ReadAllText(category.FullName);

            var ok = cs.Contains("public class CategoryMapping : ClassMap<Category>");
            Assert.IsTrue(ok, "Should contain the ClassMap<>");
        }
Beispiel #4
0
        public static void MakeHbm()
        {
            var dbReader = new DatabaseReader(connectionString, providername);
            var schema = dbReader.ReadAll();

            var directory = new DirectoryInfo("C:\\Temp\\Models.NorthwindIB.NH");
            var settings = new CodeWriterSettings
            {
                // or CodeTarget.PocoNHibernateFluent or CodeTarget.PocoEntityCodeFirst
                CodeTarget = CodeTarget.PocoNHibernateHbm,
                Namespace = "Models.NorthwindIB.NH"
            };
            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);
        }
        public void NorthwindViewTest()
        {
            var dbReader = TestHelper.GetNorthwindReader();
            var schema = dbReader.ReadAll();

            var directory = TestHelper.CreateDirectory("NorthwindView");
            const string @namespace = "Northwind.Domain";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.Poco, IncludeViews = true };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            var files = directory.GetFiles("*.cs");

            var categorySalesView = files.FirstOrDefault(f => f.Name == "CategorySalesFor1997.cs");
            Assert.IsNotNull(categorySalesView);
        }
Beispiel #6
0
        private static bool WriteFluentNHibernate(DirectoryInfo directory, DatabaseSchema schema)
        {
            var sub = CreateDirectory(directory, "FluentNHib");
            var settings = new CodeWriterSettings
            {
                Namespace = "Northwind.FluentNHib",
                CodeTarget = CodeTarget.PocoNHibernateFluent,
                WriteProjectFile = true
            };

            var codeWriter = new CodeWriter(schema, settings);

            codeWriter.Execute(sub);
            Console.WriteLine("Wrote Fluent NHib project to " + sub.FullName);
            var isBuilt = BuildProject(Path.Combine(sub.FullName, settings.Namespace + ".csproj"));
            return isBuilt;
        }
Beispiel #7
0
        public void TestRunnerWithNorthwind()
        {
            //smoke test - does this run without any exceptions
            var dbReader = TestHelper.GetNorthwindReader();
            var schema = dbReader.ReadAll();

            var runner = new ResultSetReader(schema);
            runner.Execute();

            var directory = TestHelper.CreateDirectory("NorthwindSproc");
            const string @namespace = "Northwind.Domain";
            var settings = new CodeWriterSettings { Namespace = @namespace };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            Debug.WriteLine("Check project in " + directory.FullName);
        }
 public void RunCodeWriter()
 {
     if (_readProcedures)
     {
         var sprocRunner = new DatabaseSchemaReader.Procedures.ResultSetReader(_databaseSchema);
         sprocRunner.Execute();
     }
     var settings = new CodeWriterSettings { Namespace = _ns, CodeTarget = CodeTarget };
     //these have no UI, but the user can edit the config.
     settings.UseForeignKeyIdProperties = Properties.Settings.Default.CodeGenUseForeignKeyIdProperties;
     if (Properties.Settings.Default.CodeGenUsePluralizingNamer)
     {
         settings.Namer = new PluralizingNamer();
     }
     //if poco, write the sprocs - or if read the sprocs, we can generate
     settings.WriteStoredProcedures = (_readProcedures || CodeTarget == CodeTarget.Poco);
     settings.WriteUnitTest = Properties.Settings.Default.CodeGenWriteUnitTest;
     settings.WriteProjectFile = Properties.Settings.Default.CodeGenWriteProjectFile;
     settings.IncludeViews = Properties.Settings.Default.CodeGenIncludeViews;
     settings.WriteCodeFirstIndexAttribute = Properties.Settings.Default.CodeGenWriteIndexAttribute;
     var cw = new CodeWriter(_databaseSchema, settings);
     try
     {
         cw.Execute(_directory);
         Message = @"Wrote to " + _directory.FullName;
         Result = true;
         return;
     }
     catch (IOException exception)
     {
         Message =
             @"An IO error occurred while opening the file.\n" + exception.Message;
     }
     catch (UnauthorizedAccessException exception)
     {
         Message =
             @"The caller does not have the required permission or path is readonly.\n" + exception.Message;
     }
     Result = false;
 }
        public void NorthwindTest()
        {
            var dbReader = TestHelper.GetNorthwindReader();
            var schema = dbReader.ReadAll();

            var directory = TestHelper.CreateDirectory("Northwind");
            const string @namespace = "Northwind.Domain";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.Poco };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            var files = directory.GetFiles("*.cs");

            var category = files.First(f => f.Name == "Category.cs");
            var cs = File.ReadAllText(category.FullName);

            var ok = cs.Contains("public virtual IList<Product> ProductCollection { get; private set; }");
            Assert.IsTrue(ok, "Should contain the collection of products");

            /*
             * When generated, create a startup project-
             *  Reference NHibernate and Castle
             *  Add App.Config with NHibernate configuration
             *  Run the NH config in app startup - for test projects use something like this...
        private static ISession Initialize()
        {
            var configuration = new Configuration();
            configuration.Configure(); //configure from the app.config
            //reference one of your domain classes here
            configuration.AddAssembly(typeof(Category).Assembly);
            var sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory.OpenSession();
        }
             *
             */
        }
        public void PocoTest()
        {
            DatabaseSchema schema = PrepareModel();

            var directory = TestHelper.CreateDirectory("MyTest");
            const string @namespace = "MyTest";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.Poco };

            var target = new CodeWriter(schema, settings);
            target.Execute(directory);

            var files = directory.GetFiles("*.cs");
            var products = files.FirstOrDefault(f => f.Name == "Product.cs");
            Assert.IsNotNull(products, "Should have written Product class to represent [Products] table");

            var category = files.FirstOrDefault(f => f.Name == "Category.cs");
            Assert.IsNotNull(category, "Should have written Category class to represent [Categories] table");

            var cs = File.ReadAllText(category.FullName);

            var ok = cs.Contains("public virtual IList<Product> ProductCollection { get; private set; }");
            Assert.IsTrue(ok, "Should contain the collection of products");
        }
        public void TestRiaServices()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

            schema.AddTable("Categories")
                .AddColumn("CategoryId", DbType.Int32).AddPrimaryKey()
                .AddColumn("CategoryName", DbType.String);

            schema.AddTable("Products")
                .AddColumn("ProductId", DbType.Int32).AddPrimaryKey()
                .AddColumn("ProductName", DbType.String)
                .AddColumn("CategoryId", DbType.Int32).AddForeignKey("fk", "Categories");

            DatabaseSchemaFixer.UpdateReferences(schema);

            var directory = TestHelper.CreateDirectory("TestRiaServices");
            const string @namespace = "MyTest";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.PocoRiaServices };

            //act
            var target = new CodeWriter(schema, settings);
            target.Execute(directory);

            //assert
            var files = directory.GetFiles("*.cs");
            var products = files.FirstOrDefault(f => f.Name == "Product.cs");
            Assert.IsNotNull(products, "Should have written Product class to represent [Products] table");

            var category = files.FirstOrDefault(f => f.Name == "Category.cs");
            Assert.IsNotNull(category, "Should have written Category class to represent [Categories] table");

            var cs = File.ReadAllText(category.FullName);

            var ok = cs.Contains("[MetadataType(typeof(Category.CategoryMetadata))]");
            Assert.IsTrue(ok, "Should contain nested metadata class");
        }
        public void ExecuteTest()
        {
            DatabaseSchema schema = PrepareModel();
            const string @namespace = "MyTest";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.PocoEntityCodeFirst };
            var target = new CodeWriter(schema, settings);

            var directory = TestHelper.CreateDirectory("MyTest");

            target.Execute(directory);

            //assert
            var mapping = directory.GetDirectories("mapping").FirstOrDefault();
            Assert.IsNotNull(mapping);

            var files = mapping.GetFiles("*.cs");
            var products = files.FirstOrDefault(f => f.Name == "ProductMapping.cs");
            Assert.IsNotNull(products, "Should have written Product Mapping class");

            var cs = File.ReadAllText(products.FullName);

            var ok = cs.Contains("EntityTypeConfiguration<Product>");
            Assert.IsTrue(ok, "Should contain an EntityTypeConfiguration class mapper");
        }
        public void MySqlProcedureTest()
        {
            const string providername = "MySql.Data.MySqlClient";
            var connectionString = ConnectionStrings.MySql;
            ProviderChecker.Check(providername, connectionString);

            var dbReader = new DatabaseReader(connectionString, providername);
            var schema = dbReader.ReadAll();

            var procedure = schema.StoredProcedures
                .Find(x => string.Equals(x.Name, "film_not_in_stock", StringComparison.OrdinalIgnoreCase));
            if (procedure == null)
            {
                Assert.Inconclusive("No sproc film_not_in_stock in Sakila");
            }

            //getting the procedure resultsets is a special call
            var runner = new ResultSetReader(schema);
            runner.Execute();

            var directory = TestHelper.CreateDirectory("MySqlSproc");
            const string @namespace = "MySqlSproc.Domain";
            var settings = new CodeWriterSettings
            {
                Namespace = @namespace,
                CodeTarget = CodeTarget.Poco,
                WriteStoredProcedures = true
            };

            //act
            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            //assert
            //This procedure produces a table of inventory ID numbers for the copies of the film not in stock,
            //and returns (in the p_film_count parameter) a count that indicates the number of rows in that table.

            //using (var connection = new MySqlConnection("Server=...;Database=sakila;Allow User Variables=True;"))
            //{
            //	var sproc = new FilmNotInStock(connection);
            //	var result = sproc.Execute(2, 1);
            //	Console.WriteLine(result.PFilmCount);
            //	Console.WriteLine(string.Join(",", result.FilmNotInStockResult0.Select(x => x.InventoryId)));
            //}

            var procedures = directory.GetDirectories("Procedures").FirstOrDefault();
            if (procedures == null)
                Assert.Fail("Could not find Procedures subdirectory");
            var files = procedures.GetFiles("*.cs");

            var filmNotInStock = files.FirstOrDefault(f => f.Name == "FilmNotInStock.cs");
            Assert.IsNotNull(filmNotInStock,
                "Should have written FilmNotInStock class for film_not_in_stock procedure");

            var cs = File.ReadAllText(filmNotInStock.FullName);
            //there are 2 input parameters, an OUT parameter and a resultset.
            Assert.IsTrue(cs.Contains("public virtual FilmNotInStockResult Execute(int? pFilmId, int? pStoreId)"),
                "Generated input signature");

            var result = files.FirstOrDefault(f => f.Name == "FilmNotInStockResult.cs");
            Assert.IsNotNull(result, "Should have written FilmNotInStockResult class");

            cs = File.ReadAllText(result.FullName);
            Assert.IsTrue(cs.Contains("public virtual int? PFilmCount { get; set; }"),
                "Generated property for OUT parameter");
            Assert.IsTrue(cs.Contains("public virtual IList<FilmNotInStockResult0> FilmNotInStockResult0 { get; private set; }"),
                "Generated collection property for resultset");
        }
        public void ViewTest()
        {
            var schema = PrepareModel();

            var directory = TestHelper.CreateDirectory("MyViewTest");
            const string @namespace = "MyTest";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.Poco, IncludeViews = true };

            var target = new CodeWriter(schema, settings);
            target.Execute(directory);

            var files = directory.GetFiles("*.cs");
            var category = files.FirstOrDefault(f => f.Name == "ActiveCategory.cs");
            Assert.IsNotNull(category, "Should have written ActiveCategory class to map [ActiveCategories] view");
        }
        public void OracleHrTest()
        {
            const string providername = "System.Data.OracleClient";
            const string connectionString = ConnectionStrings.OracleHr;
            ProviderChecker.Check(providername, connectionString);

            var dbReader = new DatabaseReader(connectionString, providername);
            dbReader.Owner = "HR";
            DatabaseSchema schema = null;
            try
            {
                schema = dbReader.ReadAll();
            }
            catch (DbException exception)
            {
                Assert.Inconclusive("Cannot access database " + exception.Message);
            }
            var directory = TestHelper.CreateDirectory("Hr");
            const string @namespace = "Hr.Domain";
            var settings = new CodeWriterSettings { Namespace = @namespace, CodeTarget = CodeTarget.PocoNHibernateHbm };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            var mapping = directory.GetDirectories("mapping").FirstOrDefault();
            if (mapping == null)
                Assert.Fail("Could not find Mapping subdirectory");
            var files = mapping.GetFiles("*.xml");

            var employeeMap = files.First(f => f.Name == "Employee.hbm.xml");
            var doc = XDocument.Load(employeeMap.FullName);

            var classElement = doc.Descendants("{urn:nhibernate-mapping-2.2}class").First();
            Assert.AreEqual("Employee", (string)classElement.Attribute("name"));
            Assert.AreEqual("`EMPLOYEES`", (string)classElement.Attribute("table"));
        }
        public void NorthwindProcedureTest()
        {
            var dbReader = TestHelper.GetNorthwindReader();
            //remove the spCreateDiagram system sprocs
            dbReader.Exclusions.StoredProcedureFilter = new PrefixFilter("sp");
            var schema = dbReader.ReadAll();

            var procedure = schema.StoredProcedures
                .Find(x => string.Equals(x.Name, "Employee Sales by Country", StringComparison.OrdinalIgnoreCase));
            if (procedure == null)
            {
                Assert.Inconclusive("No Employee Sales By Country found in Northwind");
            }

            //getting the procedure resultsets is a special call
            var runner = new ResultSetReader(schema);
            runner.Execute();

            var directory = TestHelper.CreateDirectory("NorthwindSproc");
            const string @namespace = "Northwind.Domain";
            var settings = new CodeWriterSettings
            {
                Namespace = @namespace,
                CodeTarget = CodeTarget.Poco,
                WriteStoredProcedures = true
            };

            var codeWriter = new CodeWriter(schema, settings);
            codeWriter.Execute(directory);

            var procedures = directory.GetDirectories("Procedures").FirstOrDefault();
            if (procedures == null)
                Assert.Fail("Could not find Procedures subdirectory");
            var files = procedures.GetFiles("*.cs");
            var employeeSales = files.FirstOrDefault(f => f.Name == "EmployeeSalesByCountry.cs");
            Assert.IsNotNull(employeeSales,
                "Should have written EmployeeSalesByCountry class for Employee Sales By Country procedure");

            var cs = File.ReadAllText(employeeSales.FullName);
            Assert.IsTrue(cs.Contains("public virtual IEnumerable<EmployeeSalesByCountryResult> Execute(DateTime? beginningDate, DateTime? endingDate)"),
                "Generated input signature");

            var employeeSalesResult = files.FirstOrDefault(f => f.Name == "EmployeeSalesByCountryResult.cs");
            Assert.IsNotNull(employeeSalesResult,
                "Should have written EmployeeSalesByCountryResult class for Employee Sales By Country procedure");

            cs = File.ReadAllText(employeeSalesResult.FullName);
            Assert.IsTrue(cs.Contains("public virtual string Country { get; set; }"),
                "Generated property for resultSet column");
        }
Beispiel #17
0
        private static bool WriteCodeFirst(DirectoryInfo directory, DatabaseSchema schema)
        {
            var sub = CreateDirectory(directory, "CodeFirst");
            var settings = new CodeWriterSettings
            {
                Namespace = "Northwind.CodeFirst",
                CodeTarget = CodeTarget.PocoEntityCodeFirst,
                UseForeignKeyIdProperties = true,
                WriteProjectFile = true
            };

            var codeWriter = new CodeWriter(schema, settings);

            codeWriter.Execute(sub);
            Console.WriteLine("Wrote EF CodeFirst project to " + sub.FullName);
            var isBuilt = BuildProject(Path.Combine(sub.FullName, settings.Namespace + ".csproj"));
            return isBuilt;
        }
        public void ProcedureTest()
        {
            var schema = PrepareModel();

            var procedure = new DatabaseStoredProcedure { Name = "SelectCategory" };
            var argument = new DatabaseArgument
                           {
                               Name = "p1",
                               DatabaseDataType = "VARCHAR",
                               Length = 10,
                               DataType = DataTypeConverter.FindDataType("VARCHAR", schema.DataTypes, SqlType.SqlServer, null),
                               In = true,
                           };
            procedure.Arguments.Add(argument);
            var rs = new DatabaseResultSet();
            var resultColumn = new DatabaseColumn { Name = "Output", DbDataType = "VARCHAR" };
            DataTypeConverter.AddDataType(resultColumn);
            rs.Columns.Add(resultColumn);
            procedure.ResultSets.Add(rs);
            schema.StoredProcedures.Add(procedure);

            var directory = TestHelper.CreateDirectory("MySprocTest");
            const string @namespace = "MySprocTest";
            var settings = new CodeWriterSettings
            {
                Namespace = @namespace,
                CodeTarget = CodeTarget.Poco,
                WriteStoredProcedures = true
            };

            var target = new CodeWriter(schema, settings);
            target.Execute(directory);

            var procedures = directory.GetDirectories("Procedures").FirstOrDefault();
            if (procedures == null)
                Assert.Fail("Could not find Procedures subdirectory");
            var files = procedures.GetFiles("*.cs");
            var products = files.FirstOrDefault(f => f.Name == "SelectCategory.cs");
            Assert.IsNotNull(products, "Should have written SelectCategory class for SelectCategory procedure");

            var category = files.FirstOrDefault(f => f.Name == "SelectCategoryResult.cs");
            Assert.IsNotNull(category, "Should have written SelectCategoryResult class to the result of the sproc");
        }