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 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);
        }
Exemple #3
0
        public static string GetMethodName(IEnumerable <Parameter> methodParameters, CodeWriterSettings codeWriterSettings, bool singular, string baseMethodName)
        {
            var partialMethodName = ConvertParametersToMethodNameByPart(methodParameters, codeWriterSettings);
            var methodName        = singular ? baseMethodName : $"{baseMethodName}List";

            return(!string.IsNullOrEmpty(partialMethodName) ? $"{methodName}By{partialMethodName}" : methodName);
        }
Exemple #4
0
        public static string GetGetListMethodSignature(DatabaseTable table, CodeWriterSettings codeWriterSettings, IEnumerable <Parameter> methodParameters)
        {
            //return $"IEnumerable<{table.NetName}> GetList({PrintParametersForSignature(methodParameters)})";
            var methodName = GetMethodName(methodParameters, codeWriterSettings, false, BaseMethodNameGet);

            return($"IEnumerable<{table.NetName}> {methodName}({PrintParametersForSignature(methodParameters)})");
        }
        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);
        }
        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 UnitTestWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _schema = schema;
     _cb = new ClassBuilder();
         
 }
        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 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 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CodeWriter"/> class.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="codeWriterSettings">The code writer settings.</param>
        public CodeWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }
            if (codeWriterSettings == null)
            {
                throw new ArgumentNullException("codeWriterSettings");
            }

            _schema             = schema;
            _codeWriterSettings = codeWriterSettings;

            var vs2010 = _codeWriterSettings.WriteProjectFile;
            var vs2015 = _codeWriterSettings.WriteProjectFileNet46;

            _projectVersion = vs2015 ? ProjectVersion.Vs2015 : vs2010 ? ProjectVersion.Vs2010 : ProjectVersion.Vs2008;
            //cannot be .net 3.5
            if (IsCodeFirst() && _projectVersion == ProjectVersion.Vs2008)
            {
                _projectVersion = ProjectVersion.Vs2015;
            }

            PrepareSchemaNames.Prepare(schema, codeWriterSettings.Namer);
        }
        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);
        }
        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);
        }
        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 #14
0
 public EntityWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     this.schema             = schema;
     this.codeWriterSettings = codeWriterSettings;
     PrepareSchemaNames.Prepare(schema, this.codeWriterSettings.Namer);
     dataAnnotationWriter = new DataAnnotationWriter(false, codeWriterSettings);
     mappingNamer         = new MappingNamer();
 }
        //private CodeInserter _codeInserter;

        /// <summary>
        /// Initializes a new instance of the <see cref="ClassWriter"/> class.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <param name="codeWriterSettings">The code writer settings.</param>
        public ClassWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings)
        {
            _codeWriterSettings = codeWriterSettings;
            _table = table;
            _cb    = new ClassBuilder();
            //_codeInserter = codeWriterSettings.CodeInserter;
            //if (_codeInserter == null) _codeInserter = new CodeInserter();
        }
 //private CodeInserter _codeInserter;
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassWriter"/> class.
 /// </summary>
 /// <param name="table">The table.</param>
 /// <param name="codeWriterSettings">The code writer settings.</param>
 public ClassWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _table = table;
     _cb = new ClassBuilder();
     //_codeInserter = codeWriterSettings.CodeInserter;
     //if (_codeInserter == null) _codeInserter = new CodeInserter();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CodeWriter"/> class.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="codeWriterSettings">The code writer settings.</param>
        public CodeWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
        {
            if (schema == null) throw new ArgumentNullException("schema");
            if (codeWriterSettings == null) throw new ArgumentNullException("codeWriterSettings");

            _schema = schema;
            _codeWriterSettings = codeWriterSettings;

            PrepareSchemaNames.Prepare(schema, codeWriterSettings.Namer);
        }
Exemple #18
0
        private static Parameter GetCustomerParameter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
        {
            var orgUnitTable     = schema.FindTableByName(CustomerAssetOrganizationTableName);
            var methodParameters = GetMethodParametersForColumns(new List <DatabaseColumn>
            {
                orgUnitTable.FindColumn(CustomerIDColumnName)
            }, codeWriterSettings);

            return(methodParameters.Single());
        }
Exemple #19
0
        public static void BeginNestNamespace(ClassBuilder classBuilder, CodeWriterSettings codeWriterSettings)
        {
            if (!string.IsNullOrEmpty(codeWriterSettings.Namespace))
            {
                classBuilder.BeginNest("namespace " + codeWriterSettings.Namespace);
                return;
            }

            throw new ArgumentNullException("codeWriterSettings.Namespace");
        }
        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 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);
        }
Exemple #22
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);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CodeWriter"/> class.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="codeWriterSettings">The code writer settings.</param>
        public CodeWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }
            if (codeWriterSettings == null)
            {
                throw new ArgumentNullException("codeWriterSettings");
            }

            _schema             = schema;
            _codeWriterSettings = codeWriterSettings;

            PrepareSchemaNames.Prepare(schema, codeWriterSettings.Namer);
        }
        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);
        }
Exemple #25
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;
        }
        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);
        }
        public void TestTablePerTypeSubClass()
        {
            //arrange
            var schema = Arrange();
            //var schema = Arrange();
            var table = schema.FindTableByName("Cars");
            var codeWriterSettings = new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst };

            var classWriter = new ClassWriter(table, codeWriterSettings);

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

            //assert
            Assert.IsTrue(txt.Contains("public class Car : Vehicle"), "Subclass inherits from parent class");
            Assert.IsFalse(txt.Contains("public int VehicleId { get; set; }"), "The primary key is marked on the parent class");
        }
        public void ExecuteTest()
        {
            //arrange
            var schema = PrepareModel();
            var settings = new CodeWriterSettings { CodeTarget = CodeTarget.PocoEfCore};
            var target = new CodeFirstContextWriter(settings);

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

            //assert
            var hasDbSet = result.Contains("public DbSet<Product> ProductCollection");
            var hasOnModelCreating = result.Contains("protected override void OnModelCreating(ModelBuilder modelBuilder)");
            var hasMapping = result.Contains("modelBuilder.Entity<Product>(ProductMapping.Map);");
            Assert.IsTrue(hasDbSet);
            Assert.IsTrue(hasOnModelCreating);
            Assert.IsTrue(hasMapping);
        }
        public void WriteForeignKeyInverseTestForNHibernate()
        {
            //arrange
            var schema = ArrangeSchema();
            var categoryTable = schema.FindTableByName("Categories");

            var codeWriterSettings = new CodeWriterSettings();
            codeWriterSettings.CodeTarget = CodeTarget.PocoNHibernateHbm;
            var cw = new ClassWriter(categoryTable, codeWriterSettings);

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

            //assert
            var hasProducts = txt.Contains("public virtual IList<Product> ProductCollection { get; protected set; }");

            Assert.IsTrue(hasProducts, "NHibernate 3.2 requires *all* setters to be protected or public");
        }
        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 WriteCodeFirstMappingInverseForeignKeyTest()
        {
            //arrange
            var schema = ArrangeSchema();
            var table = schema.FindTableByName("Orders");

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

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

            //assert
            var hasBillingAddress = txt.Contains("HasRequired(x => x.BillingAddress).WithMany(c => c.BillingAddressCollection).Map(m => m.MapKey(\"BillingAddress\"));");
            var hasDeliveryAddress = txt.Contains("HasRequired(x => x.DeliveryAddress).WithMany(c => c.DeliveryAddressCollection).Map(m => m.MapKey(\"DeliveryAddress\"));");

            Assert.IsTrue(hasBillingAddress);
            Assert.IsTrue(hasDeliveryAddress);
        }
        public void WriteCodeFirstMappingForeignKeyTest()
        {
            //arrange
            var schema = ArrangeSchema();
            var table = schema.FindTableByName("Address");

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

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

            //assert
            var hasBillingAddress = txt.Contains("HasMany(x => x.BillingAddressCollection);");
            var hasDeliveryAddress = txt.Contains("HasMany(x => x.DeliveryAddressCollection);");

            Assert.IsTrue(hasBillingAddress);
            Assert.IsTrue(hasDeliveryAddress);
        }
        public void ExecuteTest()
        {
            //arrange
            DatabaseSchema schema = PrepareModel();
            var settings = new CodeWriterSettings();
            settings.IncludeViews = true;
            var target = new CodeFirstContextWriter(settings);
            var list = new List<DatabaseTable>(schema.Tables);
            list.AddRange(schema.Views.OfType<DatabaseTable>());

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

            //assert
            var hasDbSet = result.Contains("public IDbSet<AlphabeticCategory> AlphabeticCategoryCollection");
            var hasMapping = result.Contains("modelBuilder.Configurations.Add(new AlphabeticCategoryMapping());");
            Assert.IsTrue(hasDbSet);
            Assert.IsTrue(hasMapping);
        }
        public void TestRequiredWithErrorMessageFormat()
        {
            //arrange
            var settings = new CodeWriterSettings();
            settings.RequiredErrorMessage = "{0} is mandatory";
            var classBuilder = new ClassBuilder();
            var column = new DatabaseColumn();
            column.Name = column.NetName = "Important";
            column.DataType = new DataType("NVARCHAR2", "System.String");
            column.Nullable = false;

            var target = new DataAnnotationWriter(true, settings);

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

            //assert
            Assert.AreEqual("[Required(ErrorMessage=\"Important is mandatory\")]", result);
        }
        public void TestIndex()
        {
            //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>("Name").AddNullable().AddIndex("IX_NAME");

            var target = new DataAnnotationWriter(true, settings);

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

            //assert
            Assert.AreEqual("[Index(\"IX_NAME\")]", result);
        }
 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 ExecuteTest()
        {
            //arrange
            DatabaseSchema schema = PrepareModel();
            var products = schema.FindTableByName("Products");
            var codeWriterSettings = new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst };
            var target = new CodeFirstMappingWriter(products, codeWriterSettings, new MappingNamer());

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

            //assert
            var hasMappingClass = result.Contains("public class ProductMapping : EntityTypeConfiguration<Product>");
            //we don't have the UseForeignKeyIdProperties=true, so map back to the instance property
            var hasForeignKey =
                result.Contains("HasRequired(x => x.SupplierKey).WithMany(c => c.ProductCollection).Map(m => m.MapKey(\"SupplierKey\"))");
            var hasManyToMany = result.Contains("HasMany(x => x.CategoryCollection).WithMany(z => z.ProductCollection)");

            Assert.IsTrue(hasMappingClass);
            Assert.IsTrue(hasForeignKey);
            Assert.IsTrue(hasManyToMany);
        }
        public void TestDecimalRangeWithErrorMessage()
        {
            //arrange
            var settings = new CodeWriterSettings();
            settings.RangeErrorMessage = "{1} must be less than {0}";
            var classBuilder = new ClassBuilder();
            var column = new DatabaseColumn();
            column.Name = column.NetName = "Name";
            column.DataType = new DataType("NUMBER", "System.Decimal");
            column.Nullable = true;
            column.Precision = 5;
            column.Scale = 1;

            var target = new DataAnnotationWriter(true, settings);

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

            //assert
            Assert.AreEqual("[Range(typeof(decimal), \"0\", \"9999\", ErrorMessage=\"Name must be less than 9999\")]", result);
        }
Exemple #39
0
        public static List <Parameter> GetMethodParametersForColumns(IEnumerable <DatabaseColumn> columns, CodeWriterSettings codeWriterSettings)
        {
            var methodParameters = new List <Parameter>();

            foreach (var column in columns.ToList().OrderBy(item => item.Name))
            {
                var ta        = codeWriterSettings.Namer.NameToAcronym(column.TableName);
                var pn        = codeWriterSettings.Namer.NameToAcronym(GetPropertyNameForDatabaseColumn(column));
                var dt        = FindDataType(column);
                var cn        = GetPropertyNameForDatabaseColumn(column);
                var fn        = Regex.Replace(GetPropertyNameForDatabaseColumn(column), "([A-Z]+|[0-9]+)", " $1", RegexOptions.Compiled).Trim();
                var fields    = fn.Split(' ').ToList();
                var firstChar = fields[0].ToLower()[0];
                if (firstChar == 'a' || firstChar == 'e' || firstChar == 'i' || firstChar == 'o' || firstChar == 'u')
                {
                    fields.Insert(0, "An");
                }
                else
                {
                    fields.Insert(0, "A");
                }

                for (var i = 1; i < fields.Count; i++)
                {
                    var f = fields[i];
                    if (f.ToLower() == "id")
                    {
                        fields[i] = "ID";
                        continue;
                    }

                    fields[i] = fields[i].ToLower();
                }

                var summary = string.Join(" ", fields) + ".";

                methodParameters.Add(new Parameter()
                {
                    Name = pn, DataType = dt, ColumnNameToQueryBy = cn, Summary = summary, TableAlias = ta
                });
            }

            DeduplicateMethodParameterNames(methodParameters);
            return(methodParameters);
        }
Exemple #40
0
        public static IEnumerable <Parameter> GetMethodParametersForPrimaryKeys(DatabaseTable table, CodeWriterSettings codeWriterSettings, bool byCustomer)
        {
            var columns          = table.Columns.Where(c => c.IsPrimaryKey).ToList().OrderBy(item => item.Name).ToList();
            var methodParameters = GetMethodParametersForColumns(columns, codeWriterSettings);

            if (byCustomer)
            {
                var hasCustomer = columns.Any(c => c.Name == CustomerIDColumnName);
                if (hasCustomer)
                {
                    return(new List <Parameter>());
                }

                if (TableHasOrgUnitForeignKey(table))
                {
                    methodParameters.Add(GetCustomerParameter(table.DatabaseSchema, codeWriterSettings));
                }
                else
                {
                    return(new List <Parameter>());
                }
            }

            return(methodParameters);
        }
Exemple #41
0
 public UnitTestWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _schema             = schema;
     _cb = new ClassBuilder();
 }
 public RepositoryImplementationWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings, IEnumerable <string> logicalDeleteColumns)
 {
     this.codeWriterSettings   = codeWriterSettings;
     this.schema               = schema;
     this.logicalDeleteColumns = logicalDeleteColumns;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassWriter"/> class.
 /// </summary>
 /// <param name="table">The table.</param>
 /// <param name="codeWriterSettings">The code writer settings.</param>
 public ClassWriter(DatabaseTable table, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _table = table;
     _cb    = new ClassBuilder();
 }
Exemple #44
0
 public ServiceCollectionExtensionsWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     this.codeWriterSettings = codeWriterSettings;
     this.schema             = schema;
     classBuilder            = new ClassBuilder();
 }
Exemple #45
0
 public static IEnumerable <Parameter> GetGetListByMethodParameters(IEnumerable <DatabaseColumn> columns, CodeWriterSettings codeWriterSettings)
 {
     return(GetMethodParametersForColumns(columns, codeWriterSettings));
 }
Exemple #46
0
        public static string GetGetMethodName(IEnumerable <DatabaseColumn> columns, CodeWriterSettings codeWriterSettings, bool singular)
        {
            var methodParameters = GetGetListByMethodParameters(columns, codeWriterSettings);

            return(GetMethodName(methodParameters, codeWriterSettings, singular, BaseMethodNameGet));
        }
Exemple #47
0
        public static string ConvertParametersToMethodNameByPart(IEnumerable <Parameter> methodParameters, CodeWriterSettings codeWriterSettings)
        {
            var s = new List <string>();

            foreach (var p in methodParameters)
            {
                if (!string.IsNullOrEmpty(p.ColumnNameToQueryBy))
                {
                    var properName = codeWriterSettings.Namer.NameColumnAsMethodTitle(p.ColumnNameToQueryBy);
                    s.Add(properName);
                }
            }

            return(s.Any() ? string.Join("And", s) : string.Empty);
        }
Exemple #48
0
        public static string GetGetListByMethodSignature(DatabaseTable table, IEnumerable <DatabaseColumn> columns, CodeWriterSettings codeWriterSettings, IEnumerable <Parameter> methodParameters)
        {
            //return $"IEnumerable<{table.NetName}> {GetGetMethodName(columns, codeWriterSettings)}({PrintParametersForSignature(methodParameters)})";
            var methodName = GetGetMethodName(columns, codeWriterSettings, false);

            return($"IEnumerable<{table.NetName}> {methodName}({PrintParametersForSignature(methodParameters)})");
        }
Exemple #49
0
        public static IEnumerable <Parameter> GetGetListMethodParameters(DatabaseTable table, CodeWriterSettings codeWriterSettings, bool byCustomer)
        {
            var columns = new List <DatabaseColumn>();

            if (byCustomer)
            {
                var hasCustomer = table.Columns.Any(c => c.Name == CustomerIDColumnName);
                if (hasCustomer)
                {
                    return(new List <Parameter>());
                }

                if (TableHasOrgUnitForeignKey(table))
                {
                    var orgUnitTable = table.DatabaseSchema.FindTableByName(CustomerAssetOrganizationTableName);
                    columns.Add(orgUnitTable.FindColumn(CustomerIDColumnName));
                }
                else
                {
                    return(new List <Parameter>());
                }

                return(GetMethodParametersForColumns(columns, codeWriterSettings));
            }

            return(new List <Parameter>());
        }
 public EnumeratedDataTypeWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     this.codeWriterSettings = codeWriterSettings;
     this.schema             = schema;
 }
Exemple #51
0
        public static string GetWithMethodSignature(DatabaseTable table, DatabaseConstraint foreignKey, CodeWriterSettings codeWriterSettings)
        {
            var propertyName = codeWriterSettings.Namer.ForeignKeyName(table, foreignKey);

            return($"{table.NetName} With{propertyName}()");
        }
Exemple #52
0
 public RepositoryInterfaceWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     this.codeWriterSettings = codeWriterSettings;
     this.schema             = schema;
 }
Exemple #53
0
        public static string GetWithMethodSignature(DatabaseTable table, DatabaseTable foreignKeyChild, DatabaseConstraint foreignForeignKey, CodeWriterSettings codeWriterSettings)
        {
            string propertyName = null;

            if (table.IsSharedPrimaryKey(foreignKeyChild))
            {
                propertyName = foreignKeyChild.Name;
            }
            else
            {
                propertyName = codeWriterSettings.Namer.ForeignKeyCollectionName(table.Name, foreignKeyChild, foreignForeignKey);
            }

            return($"{table.NetName} With{propertyName}()");
        }
 public NpgsqlDbContextHelperWriter(DatabaseSchema schema, CodeWriterSettings codeWriterSettings)
 {
     this.codeWriterSettings = codeWriterSettings;
     this.schema             = schema;
     classBuilder            = new ClassBuilder();
 }
Exemple #55
0
        public static string GetDeleteMethodSignature(DatabaseTable table, CodeWriterSettings codeWriterSettings, IEnumerable <Parameter> methodParameters)
        {
            var methodName = GetMethodName(methodParameters, codeWriterSettings, true, BaseMethodNameDelete);

            return($"{table.NetName} {methodName}({PrintParametersForSignature(methodParameters)})");
        }
Exemple #56
0
 public DataAnnotationWriter(bool isNet4, CodeWriterSettings codeWriterSettings)
 {
     _codeWriterSettings = codeWriterSettings;
     _isNet4             = isNet4;
 }
Exemple #57
0
        public static IEnumerable <Parameter> GetDeleteMethodParameters(DatabaseTable table, CodeWriterSettings codeWriterSettings, bool byCustomer, bool forUniqueConstraint)
        {
            if (!forUniqueConstraint)
            {
                return(GetMethodParametersForPrimaryKeys(table, codeWriterSettings, byCustomer));
            }

            return(GetMethodParametersForUniqueConstraint(table, codeWriterSettings, byCustomer));
        }