Exemple #1
0
        public void TestNaturalKey()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

            var diagrams = schema.AddTable("Diagrams")
                           .AddColumn("diagram_id", DbType.Int32).AddPrimaryKey()
                           .AddColumn <string>("name").AddLength(10).AddUniqueKey()
                           .AddColumn <int>("principal_id")
                           .Table;

            diagrams.UniqueKeys.Single().AddColumn(diagrams.FindColumn("principal_id"));

            DatabaseSchemaFixer.UpdateReferences(schema);

            var settings = new CodeWriterSettings {
                Namespace = "MyTest", CodeTarget = CodeTarget.PocoNHibernateHbm
            };

            PrepareSchemaNames.Prepare(schema, settings.Namer);

            //act
            var target = new MappingWriter(diagrams, settings);
            var txt    = target.Write();

            //assert
            var errors = Validate(txt);

            Assert.IsFalse(errors);
        }
Exemple #2
0
        public void TestSimpleMapping()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

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

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

            DatabaseSchemaFixer.UpdateReferences(schema);

            var settings = new CodeWriterSettings {
                Namespace = "MyTest", CodeTarget = CodeTarget.PocoNHibernateHbm
            };

            PrepareSchemaNames.Prepare(schema, settings.Namer);

            //act
            var target = new MappingWriter(products, settings);
            var txt    = target.Write();

            //assert
            var errors = Validate(txt);

            Assert.IsFalse(errors);
        }
Exemple #3
0
        public void TestCompositeKey()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

            var orderDetail = schema.AddTable("OrderDetails")
                              .AddColumn("OrderID", DbType.Int32).AddPrimaryKey()
                              .AddColumn("ProductID", DbType.Int32)
                              .AddColumn <int>("UnitPrice")
                              .Table;

            orderDetail.PrimaryKey.AddColumn(orderDetail.FindColumn("ProductID"));

            DatabaseSchemaFixer.UpdateReferences(schema);

            var settings = new CodeWriterSettings {
                Namespace = "MyTest", CodeTarget = CodeTarget.PocoNHibernateHbm
            };

            PrepareSchemaNames.Prepare(schema, settings.Namer);

            //act
            var target = new MappingWriter(orderDetail, settings);
            var txt    = target.Write();

            //assert
            var errors = Validate(txt);

            Assert.IsFalse(errors);
        }
        public void JoinTableCreated()
        {
            //arrange
            var products           = _schema.FindTableByName("CategoryProducts");
            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEfCore
            };
            var target = new CodeFirstMappingWriter(products, codeWriterSettings, new MappingNamer());

            //act
            var result = target.Write();

            //assert
            //        public static void Map(EntityTypeBuilder<CategoryProduct> b)
            //        {
            //            //table
            //            b.ToTable("CategoryProducts");
            //            // Primary key (composite)
            //            b.HasKey(x => new { x.CategoryId, x.ProductId });
            //            // Properties
            //            b.HasOne(x => x.Category).WithOne();
            //            b.HasOne(x => x.Product).WithOne();


            var hasKey =
                result.Contains("b.HasKey(x => new { x.CategoryId, x.ProductId });");
            //we have to create a many to many table for this
            var hasCategory = result.Contains("b.HasOne(x => x.Category).WithOne(");
            var hasProduct  = result.Contains("b.HasOne(x => x.Product).WithOne(");

            Assert.IsTrue(hasKey);
            Assert.IsTrue(hasCategory);
            Assert.IsTrue(hasProduct);
        }
Exemple #5
0
        public void ExecuteTest()
        {
            DatabaseSchema schema = PrepareModel();

            var          directory  = 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 WriteTest()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);
            var table  = schema.AddTable("Categories")
                         .AddColumn("CategoryId", "INT").AddPrimaryKey().AddIdentity()
                         .AddColumn("CategoryName", "NVARCHAR").Table;

            //we need datatypes
            schema.DataTypes.Add(new DataType("INT", "System.Int32"));
            schema.DataTypes.Add(new DataType("NVARCHAR", "System.String"));
            DatabaseSchemaFixer.UpdateDataTypes(schema);
            //make sure .Net names are assigned
            PrepareSchemaNames.Prepare(schema, new Namer());

            //inject the custom code inserter
            var codeWriterSettings = new CodeWriterSettings {
                CodeInserter = new CustomCodeInserter()
            };
            var cw = new ClassWriter(table, codeWriterSettings);

            //act
            var txt = cw.Write();

            //assert
            Assert.IsTrue(txt.Contains("using System.ComponentModel.DataAnnotations.Schema"));
            Assert.IsTrue(txt.Contains("[Table(\"Categories\")]"));
            Assert.IsTrue(txt.Contains("[Column(\"CategoryId\")]"));
        }
        public void TestIndexNotNeededForPrimaryKey()
        {
            //arrange
            var settings = new CodeWriterSettings();

            settings.CodeTarget = CodeTarget.PocoEntityCodeFirst;
            settings.WriteCodeFirstIndexAttribute = true;

            var classBuilder = new ClassBuilder();
            var table        = new DatabaseTable {
                Name = "Test"
            };

            table.AddColumn <int>("Id").AddPrimaryKey().AddIndex("PK_TEST")
            .AddColumn <string>("Category").AddNullable()
            .AddColumn <string>("Name").AddNullable().AddIndex("IX_NAME")
            ;
            var idColumn = table.PrimaryKeyColumn;

            var target = new DataAnnotationWriter(true, settings);

            //act
            target.Write(classBuilder, idColumn);
            var result = classBuilder.ToString().Trim(); //ignore lines

            //assert
            Assert.IsTrue(result.IndexOf("[Index", StringComparison.OrdinalIgnoreCase) == -1, "Should be just[Key]");
        }
        public void TestCompositeKey()
        {
            //based on Github issue #21
            //arrange
            //this schema model has a primary key which is also in 2 different foreign keys
            //AND one of the foreign keys is not in the model (exclusions)
            //this confused the code writer...
            var dept = Arrange();

            var settings = new CodeWriterSettings
            {
                CodeTarget = CodeTarget.PocoEntityCodeFirst,
                Namer      = new PluralizingNamer()
            };
            var cw = new ClassWriter(dept, settings);

            //act
            var txt = cw.Write();

            //assert
            //what should this return?
            Console.WriteLine(txt);
            Assert.IsTrue(txt.IndexOf("public int BusinessUnitId { get; set; }", StringComparison.Ordinal) > 0,
                          "Should have xId scalar key");
            Assert.IsTrue(txt.IndexOf("public virtual BusinessUnit BusinessUnit { get; set; }", StringComparison.Ordinal) > 0,
                          "Should have x reference property");
        }
Exemple #9
0
        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<>");
        }
Exemple #10
0
        public void IsMaxLengthTest()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);
            var table  = schema.AddTable("Products")
                         .AddColumn("ProductId", DbType.Int32).AddPrimaryKey().AddIdentity()
                         .AddColumn("ProductName", DbType.String).AddLength(-1)
                         .Table;

            //we need datatypes
            schema.DataTypes.Add(new DataType("INT", "System.Int32"));
            schema.DataTypes.Add(new DataType("NVARCHAR", "System.String"));
            //make sure it's all tied up
            DatabaseSchemaFixer.UpdateReferences(schema);

            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEntityCodeFirst
            };
            var target = new CodeFirstMappingWriter(table, codeWriterSettings, new MappingNamer());

            //act
            var result = target.Write();

            //assert
            var hasMaxLength = result.Contains("Property(x => x.ProductName).IsMaxLength()");

            Assert.IsTrue(hasMaxLength);
        }
        public void MappingSharedPrimaryKeyTest()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

            schema
            .AddTable("vehicle")
            .AddColumn <string>("regnum").AddPrimaryKey().AddLength(25)
            .AddColumn <string>("model").AddLength(32)
            .AddTable("car")
            .AddColumn <string>("regnum").AddLength(25).AddPrimaryKey().AddForeignKey("fk", "vehicle")
            .AddColumn <int>("doors");
            //make sure it's all tied up
            DatabaseSchemaFixer.UpdateReferences(schema);
            //make sure .Net names are assigned
            PrepareSchemaNames.Prepare(schema, new Namer());
            var table = schema.FindTableByName("car");

            var mappingNamer       = new MappingNamer();
            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEntityCodeFirst
            };
            var target = new CodeFirstMappingWriter(table, codeWriterSettings, mappingNamer);

            //act
            var txt = target.Write();

            //assert
            var hasScalarKey  = txt.Contains("HasKey(x => x.Regnum);");
            var hasForeignKey = txt.Contains("HasRequired(x => x.Vehicle);");

            Assert.IsTrue(hasScalarKey);
            Assert.IsTrue(hasForeignKey);
        }
Exemple #12
0
        public void ForeignKeyIdTest()
        {
            //arrange
            DatabaseSchema schema             = PrepareModel();
            var            products           = schema.FindTableByName("Products");
            var            codeWriterSettings = new CodeWriterSettings
            {
                CodeTarget = CodeTarget.PocoEntityCodeFirst,
                UseForeignKeyIdProperties = true
            };
            var target = new CodeFirstMappingWriter(products, codeWriterSettings, new MappingNamer());

            //act
            var result = target.Write();

            //assert
            var hasMappingClass         = result.Contains("public class ProductMapping : EntityTypeConfiguration<Product>");
            var hasForeignKeyIdProperty =
                result.Contains("Property(x => x.SupplierKeyId).HasColumnName(\"SupplierKey\")");
            var hasForeignKey = result.Contains("HasRequired(x => x.SupplierKey).WithMany(c => c.ProductCollection).HasForeignKey(c => c.SupplierKeyId);");

            Assert.IsTrue(hasMappingClass);
            Assert.IsTrue(hasForeignKeyIdProperty);
            Assert.IsTrue(hasForeignKey);
        }
Exemple #13
0
        public void MappingNameTest()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);
            var table  = schema.AddTable("Products")
                         .AddColumn("ProductId", DbType.Int32).AddPrimaryKey().AddIdentity()
                         .Table;

            table.NetName = "Product";
            //we need datatypes
            schema.DataTypes.Add(new DataType("INT", "System.Int32"));
            //make sure it's all tied up
            DatabaseSchemaFixer.UpdateReferences(schema);

            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEntityCodeFirst
            };
            var target = new CodeFirstMappingWriter(table, codeWriterSettings, new MappingNamer());

            //act
            target.Write();
            //now the name is assigned
            var className = target.MappingClassName;

            //assert
            Assert.AreEqual("ProductMapping", className);
        }
Exemple #14
0
        public void IsImageTest()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);
            var table  = schema.AddTable("Products")
                         .AddColumn("ProductId", DbType.Int32).AddPrimaryKey().AddIdentity()
                         .AddColumn("Picture", "image")
                         .Table;

            //we need datatypes
            schema.DataTypes.Add(new DataType("INT", "System.Int32"));
            schema.DataTypes.Add(new DataType("image", "System.Byte[]"));
            //make sure it's all tied up
            DatabaseSchemaFixer.UpdateReferences(schema);

            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEntityCodeFirst
            };
            var target = new CodeFirstMappingWriter(table, codeWriterSettings, new MappingNamer());

            //act
            var result = target.Write();

            //assert
            //EF CF will default to varbinary so we must specify
            var hasImageType = result.Contains("Property(x => x.Picture).HasColumnType(\"image\")");

            Assert.IsTrue(hasImageType);
        }
        public void TestIndexMultiColumnUnique()
        {
            //arrange
            var settings = new CodeWriterSettings();

            settings.CodeTarget = CodeTarget.PocoEntityCodeFirst;
            settings.WriteCodeFirstIndexAttribute = true;

            var classBuilder = new ClassBuilder();
            var table        = new DatabaseTable {
                Name = "Test"
            };
            var nameColumn = table.AddColumn <int>("Id").AddPrimaryKey()
                             .AddColumn <string>("Category").AddNullable().AddIndex("IX_NAME")
                             .AddColumn <string>("Name").AddNullable().AddIndex("IX_NAME")
            ;

            table.Indexes.First().IsUnique = true;

            var target = new DataAnnotationWriter(true, settings);

            //act
            target.Write(classBuilder, nameColumn);
            var result = classBuilder.ToString().Trim(); //ignore lines

            //assert
            Assert.AreEqual("[Index(\"IX_NAME\", 2, IsUnique = true)]", result);
        }
Exemple #16
0
        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 = 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");
        }
Exemple #17
0
        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 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");
        }
Exemple #19
0
        public MappingWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings)
        {
            _codeWriterSettings = codeWriterSettings;
            var ns = codeWriterSettings.Namespace;

            _table = table;
            _doc   = XDocument.Parse(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<hibernate-mapping xmlns=""urn:nhibernate-mapping-2.2"" namespace=""" + ns + @""" assembly=""" + ns + @""">
</hibernate-mapping>");
            var hibmap = _doc.Descendants(_xmlns + "hibernate-mapping").First();

            //add the class element
            _classElement = new XElement(_xmlns + "class",
                                         new XAttribute("name", _table.NetName),
                                         new XAttribute("table", SqlSafe(_table.Name)),
                                         _table.SchemaOwner != null ? new XAttribute("schema", SqlSafe(_table.SchemaOwner)) : null,
                                         //consider this
                                         new XAttribute("dynamic-update", "true"),
                                         new XAttribute("optimistic-lock", "dirty"));
            if (_table is DatabaseView)
            {
                _classElement.Add(new XAttribute("mutable", "false"));
            }
            hibmap.Add(_classElement);
        }
Exemple #20
0
        public void WriteViewTest()
        {
            //arrange
            var view = new DatabaseView();

            view.Name = "AlphabeticNames";
            view.AddColumn("FirstName", typeof(string)).AddNullable()
            .AddColumn("LastName", typeof(string)).AddNullable();

            var schema = new DatabaseSchema(null, null);

            schema.Views.Add(view);
            PrepareSchemaNames.Prepare(schema);

            var codeWriterSettings = new CodeWriterSettings
            {
                CodeTarget   = CodeTarget.PocoNHibernateHbm,
                IncludeViews = true
            };
            var cw = new ClassWriter(view, codeWriterSettings);

            //act
            var txt = cw.Write();

            //assert
            var hasFirstName = txt.Contains("public virtual string FirstName");
            var hasLastName  = txt.Contains("public virtual string LastName");
            var hasEquals    = txt.Contains("public override bool Equals(object obj)");

            Assert.IsTrue(hasFirstName);
            Assert.IsTrue(hasLastName);
            Assert.IsTrue(hasEquals);
        }
Exemple #21
0
        public DemoClass()
        {
            var s = new CodeWriterSettings(CodeWriterSettings.CSharpDefault);

            s.NewLineBeforeBlockBegin = false;
            s.TranslationMapping["`"] = "\"";

            var w = new CodeWriter(s);

            using (w.B("class Test"))
            {
                using (w.B("public int Sum(int a, int b)"))
                {
                    w._("var r = a + b;",
                        "return r;");
                }

                using (w.B("public int Mul(int a, int b)"))
                {
                    w._("var r = `a * b`;",
                        "return r;");
                }
            }
            w.HeadLines = new List <string>
            {
                "// COMMENT1",
                "// COMMENT2",
                "",
                "using System;",
                "",
            };

            Debug.Log(w.ToString());
        }
Exemple #22
0
        private CodeWriter CreateTestWriter()
        {
            var settings = new CodeWriterSettings(CodeWriterSettings.CSharpDefault);

            settings.Indent = "  ";
            settings.NewLineBeforeBlockBegin = false;
            return(new CodeWriter(settings));
        }
        public FluentMappingWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings, MappingNamer mappingNamer)
        {
            if (table == null) throw new ArgumentNullException("table");
            if (mappingNamer == null) throw new ArgumentNullException("mappingNamer");

            _codeWriterSettings = codeWriterSettings;
            _mappingNamer = mappingNamer;
            _table = table;
            _cb = new ClassBuilder();
        }
        public EntryCodeGenerator(Options options)
        {
            Options = options;

            var settings = new CodeWriterSettings(CodeWriterSettings.CSharpDefault);
            settings.TranslationMapping["`"] = "\"";
            CodeWriter = new CodeWriter.CodeWriter(settings);

            GenerateHead();
        }
Exemple #25
0
        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");
        }
Exemple #26
0
        public EntryCodeGenerator(Options options)
        {
            Options = options;

            var settings = new CodeWriterSettings(CodeWriterSettings.CSharpDefault);

            settings.TranslationMapping["`"] = "\"";
            CodeWriter = new CodeWriter.CodeWriter(settings);

            GenerateHead();
        }
Exemple #27
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 TestOneToOneTable()
        {
            //arrange
            var schema             = Arrange();
            var table              = schema.FindTableByName("Products");
            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEntityCodeFirst
            };
            var target = new CodeFirstMappingWriter(table, codeWriterSettings, new MappingNamer());

            //act
            var txt = target.Write();

            //assert
            Assert.IsTrue(txt.Contains("HasOptional(x => x.ProductDetail);"));
        }
        public CodeFirstMappingWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings, MappingNamer mappingNamer)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (mappingNamer == null)
            {
                throw new ArgumentNullException("mappingNamer");
            }

            _codeWriterSettings = codeWriterSettings;
            _mappingNamer       = mappingNamer;
            _table = table;
            _cb    = new ClassBuilder();
        }
        public void ExecuteTest()
        {
            //arrange
            DatabaseSchema schema   = PrepareModel();
            var            settings = new CodeWriterSettings();
            var            target   = new CodeFirstContextWriter(settings);

            //act
            var result = target.Write(schema.Tables);

            //assert
            var hasDbSet   = result.Contains("public IDbSet<Product> ProductCollection");
            var hasMapping = result.Contains("modelBuilder.Configurations.Add(new ProductMapping());");

            Assert.IsTrue(hasDbSet);
            Assert.IsTrue(hasMapping);
        }
        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 TableLinksToJoinTable()
        {
            //arrange
            var products           = _schema.FindTableByName("Categories");
            var codeWriterSettings = new CodeWriterSettings {
                CodeTarget = CodeTarget.PocoEfCore
            };
            var target = new CodeFirstMappingWriter(products, codeWriterSettings, new MappingNamer());

            //act
            var result = target.Write();

            //assert
            var hasCategory = result.Contains("b.HasMany(x => x.CategoryProductCollection).WithOne(");

            Assert.IsTrue(hasCategory);
        }
 public MappingWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     var ns = codeWriterSettings.Namespace;
     _table = table;
     _doc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
     <hibernate-mapping xmlns=""urn:nhibernate-mapping-2.2"" namespace=""" + ns + @""" assembly=""" + ns + @""">
     </hibernate-mapping>");
     var hibmap = _doc.Descendants(_xmlns + "hibernate-mapping").First();
     //add the class element
     _classElement = new XElement(_xmlns + "class",
                                  new XAttribute("name", _table.NetName),
                                  new XAttribute("table", SqlSafe(_table.Name)),
                                  _table.SchemaOwner != null ? new XAttribute("schema", SqlSafe(_table.SchemaOwner)) : null,
         //consider this
                                  new XAttribute("dynamic-update", "true"),
                                  new XAttribute("optimistic-lock", "dirty"));
     if (_table is DatabaseView)
     {
         _classElement.Add(new XAttribute("mutable", "false"));
     }
     hibmap.Add(_classElement);
 }
Exemple #34
0
        private static int Process(Options options)
        {
            try
            {
                Console.WriteLine("Start Process!");

                // Resolve options

                var basePath = Path.GetFullPath(options.Path ?? ".");
                var sources =
                    options.Sources.Where(p => string.IsNullOrWhiteSpace(p) == false &&
                                               p.ToLower().IndexOf(".codegen.cs") == -1)
                           .Select(p => MakeFullPath(p, basePath))
                           .ToArray();
                var references =
                    options.References.Where(p => string.IsNullOrWhiteSpace(p) == false)
                           .Select(p => MakeFullPath(p, basePath))
                           .ToArray();
                var targetDefaultPath = @".\Properties\TrackableData.CodeGen.cs";
                var targetPath = MakeFullPath(options.TargetFile ?? targetDefaultPath, basePath);

                // Parse sources and extract interfaces

                Console.WriteLine("- Parse sources");

                var syntaxTrees = sources.Select(
                    file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), path: file)).ToArray();
                var interfaceDeclarations = syntaxTrees.SelectMany(
                    st => st.GetRoot().DescendantNodes().OfType<InterfaceDeclarationSyntax>()).ToArray();

                // Generate code

                Console.WriteLine("- Generate code");

                var settings = new CodeWriterSettings(CodeWriterSettings.CSharpDefault);
                settings.TranslationMapping["`"] = "\"";

                var w = new CodeWriter.CodeWriter(settings);
                var relatedSourceTrees = new HashSet<SyntaxNode>();

                w.HeadLines = new List<string>
                {
                    "// ------------------------------------------------------------------------------",
                    "// <auto-generated>",
                    "//     This code was generated by TrackableData.CodeGenerator.",
                    "//",
                    "//     Changes to this file may cause incorrect behavior and will be lost if",
                    "//     the code is regenerated.",
                    "// </auto-generated>",
                    "// ------------------------------------------------------------------------------",
                    "",
                    "using System;",
                    "using System.Collections.Generic;",
                    "using System.Reflection;",
                    "using System.Runtime.Serialization;",
                    "using System.Linq;",
                    "using System.Text;",
                    "using TrackableData;",
                    ""
                };

                // TrackablePoco

                var pocoCodeGen = new TrackablePocoCodeGenerator() { Options = options };
                foreach (var idecl in interfaceDeclarations)
                {
                    var baseType = idecl.GetGenericBase("TrackableData.ITrackablePoco");
                    if (baseType != null)
                    {
                        var pocoType = baseType.TypeArgumentList.Arguments[0].ToString();
                        if (CodeAnalaysisExtensions.CompareTypeName(idecl.Identifier.ToString(), pocoType) == false)
                        {
                            throw new Exception($"Invalid base type of ITrackablePoco<{pocoType}>");
                        }

                        pocoCodeGen.GenerateCode(idecl, w);
                        relatedSourceTrees.Add(idecl.GetRootNode());
                    }
                }

                // TrackableContainer

                var containerCodeGen = new TrackableContainerCodeGenerator() { Options = options };
                foreach (var idecl in interfaceDeclarations)
                {
                    var baseType = idecl.GetGenericBase("TrackableData.ITrackableContainer");
                    if (baseType != null)
                    {
                        var containerType = baseType.TypeArgumentList.Arguments[0].ToString();
                        if (CodeAnalaysisExtensions.CompareTypeName(idecl.Identifier.ToString(), containerType) == false)
                        {
                            throw new Exception($"Invalid base type of ITrackableContainer<{containerType}>");
                        }

                        containerCodeGen.GenerateCode(idecl, w);
                        relatedSourceTrees.Add(idecl.GetRootNode());
                    }
                }

                // Resolve referenced using

                var usingDirectives = new HashSet<string>(relatedSourceTrees.SelectMany(
                    st => st.DescendantNodes().OfType<UsingDirectiveSyntax>()).Select(x => x.Name.ToString()));
                foreach (var usingDirective in usingDirectives)
                    EnsureUsing(w, usingDirective);

                // Save generated code

                Console.WriteLine("- Save code");

                if (w.WriteAllText(targetPath, true) == false)
                    Console.WriteLine("Nothing changed. Skip writing.");

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception in processing:\n" + e);
                return 1;
            }
        }
 public CodeFirstContextWriter(CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _cb = new ClassBuilder();
     _contextName = CreateContextName();
 }