/// <summary>
 /// Creates a ClassDeclaration.
 /// </summary>
 /// <param name="namespaceDeclaration">The NamespaceDeclaration instance the class is added to.</param>
 /// <param name="table">The database table the ClassDeclaration represents.</param>
 /// <returns>A reference to the ClassDeclaration instance that was created.</returns>
 protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table)
 {
     ClassDeclaration result = namespaceDeclaration.AddClass(this.NameProvider.GetClassName(table), true);
     ClassDeclaration baseType = new ClassDeclaration(this.ConfigOptions.BaseTypeName, new CodeDomTypeReference(result.FullName));
     result.InheritsFrom(baseType);
     return result;
 }
 protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table)
 {
     ClassDeclaration result = new ClassDeclaration(this.NameProvider.GetClassName(table.Name));
     result.IsPartial = true;
     namespaceDeclaration.AddClass(result);
     return result;
 }
Esempio n. 3
0
 /// <summary>
 /// Initializes a new instance of the NamespaceDeclaration class.
 /// </summary>
 /// <param name="nsdecl">The namespace being compiled.</param>
 public DomTester(NamespaceDeclaration nsdecl)
 {
     _nsdecl = nsdecl;
     _appDomain = AppDomain.CreateDomain("testdomain");
     this.Compile();
     _appDomain.Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
     _appDomain.Load(_compiled.GetName());
 }
Esempio n. 4
0
 public void CanCreateActiveRecordClass2()
 {
     NamespaceDeclaration nsdecl = new NamespaceDeclaration("My.Data").Imports("Castle.ActiveRecord");
     ClassDeclaration cdecl = nsdecl.AddClass("Customer").IsAbstract().InheritsFrom("ActiveRecordBase", "My.Data.Customer");
     using (DomTester tester = new DomTester(nsdecl))
     {
         Assert.IsTrue(tester.IsCompiled, "should have compiled");
         Assert.IsTrue(tester.ContainsType("My.Data.Customer"));
         Assert.IsTrue(tester.Type("My.Data.Customer").InheritsFrom("ActiveRecordBase`1", "Customer"));
     }
 }
 /// <summary>
 /// Creates a ClassDeclaration shell.
 /// </summary>
 /// <param name="nsdecl">NamespaceDeclaration the class is added.</param>
 /// <param name="table">Database table that the generated class will interact with.</param>
 /// <returns>The ClassDeclaration shell that was created.</returns>
 protected override ClassDeclaration CreateClass(NamespaceDeclaration nsdecl, TableSchema table)
 {
     ClassDeclaration result = nsdecl.AddClass(this.NameProvider.GetClassName(table), true);
     ClassDeclaration baseType = null;
     if (!String.IsNullOrEmpty(this.ConfigOptions.AbstractBaseName))
         baseType = new ClassDeclaration(this.ConfigOptions.AbstractBaseName, new CodeDomTypeReference(result.FullName));
     else
         baseType = new ClassDeclaration(this.ConfigOptions.BaseTypeName, new CodeDomTypeReference(result.FullName));
     result.InheritsFrom(baseType);
     return result;
 }
        /// <summary>
        /// Creates a ClassDeclaration.
        /// </summary>
        /// <param name="namespaceDeclaration">The NamespaceDeclaration instance the class is added to.</param>
        /// <param name="table">The database table the ClassDeclaration represents.</param>
        /// <returns>
        /// A reference to the ClassDeclaration instance that was created.
        /// </returns>
        protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table)
        {
            var result = namespaceDeclaration.AddClass(this.NameProvider.GetClassName(table), true);

            string baseTypeName = String.IsNullOrEmpty(ConfigOptions.AbstractBaseName)
                ? ConfigOptions.BaseTypeName
                : ConfigOptions.AbstractBaseName;

            var baseType = new ClassDeclaration(baseTypeName, new CodeDomTypeReference(result.FullName));
            result.InheritsFrom(baseType);
            return result;
        }
 public void Can_generate_associations()
 {
     string connString = "integrated security=SSPI;server=(local);database=Lars";
     var dbprovider = new SqlServerProvider(new DbHelper(connString));
     var configOptions = new DefaultConfigurationOptions();
     var generator = new AwishModelGenerator(); //new ConfigurableActiveRecordGenerator(configOptions);
     generator.ConfigOptions = configOptions;
     //foreach (var tbl in dbprovider.GetTableSchemas().Where(tbl => { return tbl.PrimaryKey != null; }))
     //{
     var tbl = dbprovider.GetTableSchema("LeasePaymentDescriptorLease");
     //var fkrefs = tbl.PrimaryKey.ForeignKeyReferences;
     //foreach (var fkref in fkrefs)
     //{
     //
     //}
     var theNs = new NamespaceDeclaration("Awish.Lars.Data");
     var cdecl = generator.Generate(theNs, tbl);
     new CodeBuilder().GenerateCode(Console.Out, "Awish.Lars.Data", cdecl);
     //}
 }
        public void VerifyAddAttribute()
        {
            NamespaceDeclaration nsdecl = new NamespaceDeclaration("Test");
            ClassDeclaration cdecl = nsdecl.AddClass("Customer");
            cdecl.AddAttribute(typeof(SerializableAttribute));

            ClassDeclaration attrib1 = nsdecl.AddClass("SuperAttribute").InheritsFrom("System.Attribute");
            cdecl.AddAttribute(new CodeDomTypeReference("Test.SuperAttribute"));

            ClassDeclaration attrib2 = nsdecl.AddClass("Crattribute").InheritsFrom("System.Attribute");
            cdecl.AddAttribute("Test.Crattribute");

            using (DomTester dom = new DomTester(nsdecl))
            {
                Assert.IsTrue(dom.Type("Customer").HasAttribute("System.SerializableAttribute"));
                Assert.IsTrue(dom.Type("Customer").HasAttribute("Test.SuperAttribute"));
                Assert.IsTrue(dom.Type("Customer").HasAttribute("Test.Crattribute"));
            }
            new CodeBuilder().GenerateCode(Console.Out, nsdecl);
        }
Esempio n. 9
0
        public void CanCreateActiveRecordClass()
        {
            NamespaceDeclaration nsdecl = new NamespaceDeclaration("My.Data").Imports("Castle.ActiveRecord");
            ClassDeclaration cdecl = nsdecl.AddClass("Customer").IsAbstract().InheritsFrom("ActiveRecordBase", "My.Data.Customer");

            //compile to assembly
            CodeBuilder builder = new CodeBuilder();
            CodeCompileUnit compunit = builder.CreateCodeCompileUnit(nsdecl);
            CodeDomProvider compiler = new CSharpCodeProvider();
            CompilerParameters options = new CompilerParameters();
            options.GenerateInMemory = true;
            options.WarningLevel = 4;
            options.TreatWarningsAsErrors = true;
            options.IncludeDebugInformation = true;
            options.ReferencedAssemblies.Add(@"C:\lib\Castle\bin\Castle.ActiveRecord.dll");
            CompilerResults results = compiler.CompileAssemblyFromDom(options, compunit);

                foreach (CompilerError error in results.Errors)
                {
                    Console.WriteLine(error.ErrorText);
                }

            Assembly compiled = results.CompiledAssembly;

            //load assembly in it's own app domain
            AppDomain testdomain = AppDomain.CreateDomain("testdomain");
            testdomain.Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            testdomain.Load(compiled.GetName());

            //test the assembly
            Type testtype = compiled.GetType("My.Data.Customer");
            Assert.IsNotNull(testtype);
            Assert.AreEqual("ActiveRecordBase`1", testtype.BaseType.Name);
            Assert.AreEqual("Customer", testtype.BaseType.GetGenericArguments()[0].Name);

            AppDomain.Unload(testdomain);
        }
 public void AddProperties()
 {
     NamespaceDeclaration nsdecl = new NamespaceDeclaration("Test");
     ClassDeclaration cdecl = nsdecl.AddClass("Customer");
     FieldDeclaration lastName = new FieldDeclaration("_lastName", "System.String");
     PropertyDeclaration propdecl = new PropertyDeclaration("LastName", lastName, typeof(string));
     cdecl.AddProperty(propdecl);
     PropertyDeclaration firstName = cdecl.AddProperty("FirstName", "_firstName", typeof(string));
     PropertyDeclaration duplicateFirstName = cdecl.AddProperty("FirstName", "_firstName", typeof(string));
     Assert.AreEqual(firstName, duplicateFirstName);
     cdecl.AddProperty("DateOfBirth", "_dateOfBirth", typeof(DateTime), true);
     cdecl.AddProperty("Age", "_age", new CodeDomTypeReference(typeof(int)));
     cdecl.AddProperty("Items", "_items", "System.Collections.Generic.List", "System.String");
     using (DomTester dom = new DomTester(nsdecl))
     {
         Assert.IsTrue(dom.ContainsType("Test.Customer"));
         Assert.IsTrue(dom.ContainsProperty("Test.Customer", "FirstName"));
         Assert.IsTrue(dom.ContainsProperty("Test.Customer", "LastName"));
         Assert.IsTrue(dom.ContainsProperty("Test.Customer", "DateOfBirth"));
         Assert.IsTrue(dom.ContainsProperty("Test.Customer", "Age"));
         Assert.IsTrue(dom.ContainsProperty("Test.Customer", "Items"));
     }
     new CodeBuilder().GenerateCode(Console.Out, nsdecl);
 }
 /// <summary>
 /// Creates a ClassDeclaration.
 /// </summary>
 /// <param name="namespaceDeclaration">The NamespaceDeclaration instance the class is added to.</param>
 /// <param name="table">The database table the ClassDeclaration represents.</param>
 /// <returns>A reference to the ClassDeclaration instance that was created.</returns>
 protected abstract ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table);
Esempio n. 12
0
 /// <summary>
 /// Creates a CodeCompileUnit from a NamespaceDeclaration.
 /// </summary>
 /// <param name="nsdecl"></param>
 /// <returns></returns>
 public CodeCompileUnit CreateCodeCompileUnit(NamespaceDeclaration nsdecl)
 {
     CodeCompileUnit result = new CodeCompileUnit();
     result.Namespaces.Add(nsdecl.ToCodeDom());
     return result;
 }
        public void VerifyInheritsFrom()
        {
            NamespaceDeclaration nsdecl =
                new NamespaceDeclaration("TestContainer");

            nsdecl.AddClass("Manager")
                .InheritsFrom(nsdecl.AddClass("Employee"));

            using (DomTester dom = new DomTester(nsdecl))
            {
                Assert.IsTrue(dom.Type("Manager").InheritsFrom("Employee"));
            }

            //new CodeBuilder().GenerateCode(Console.Out, nsdecl);
        }
Esempio n. 14
0
 /// <summary>
 /// Generates code from a codeTypeDeclaration.
 /// </summary>
 /// <param name="writer">The textwriter the code is written to.</param>
 /// <param name="namespaceName">The namespace that will contain the class.</param>
 /// <param name="codeTypeDeclaration">The CodeDom definition to generate.</param>
 public void GenerateCode(TextWriter writer, string namespaceName, ICodeDom<System.CodeDom.CodeTypeDeclaration> codeTypeDeclaration)
 {
     NamespaceDeclaration nsdecl = new NamespaceDeclaration(namespaceName);
     nsdecl.AddClass(codeTypeDeclaration);
     this.GenerateCode(writer, nsdecl);
 }
Esempio n. 15
0
 /// <summary>
 /// Generates code from a NamespaceDeclaration instance.
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="nsdecl"></param>
 public void GenerateCode(TextWriter writer, NamespaceDeclaration nsdecl)
 {
     CodeCompileUnit compunit = new CodeCompileUnit();
     compunit.Namespaces.Add(nsdecl.ToCodeDom());
     CodeGeneratorOptions options = new CodeGeneratorOptions();
     this.DomProvider.GenerateCodeFromCompileUnit(compunit, writer, options);
 }
Esempio n. 16
0
        private void GenerateTables()
        {
            TableSchemaList tableSchemas = GetTableSchemas();
            foreach (var tableSchema in tableSchemas.OrderBy(tbl => { return tbl.Name; }))
            {
                if (tableSchema.PrimaryKey == null)
                {
                    WriteLine("Skipping table {0} because it does not have a primary key.", tableSchema.Name);
                    continue;
                }
                if (_options.SkipTablesWithPrefix.Count > 0 && _options.SkipTablesWithPrefix.Contains(tableSchema.Name))
                {
                    WriteLine("Skipping table {0} because it's in the skiptableswithprefix list.", tableSchema.Name);
                    continue;
                }
                if (_options.SkipTables.Count > 0 && _options.SkipTables.Contains(tableSchema.Name))
                {
                    WriteLine("Skipping table {0} because it's in the skiptables list.", tableSchema.Name);
                    continue;
                }
                var ns = new NamespaceDeclaration(_options.Namespace);
                var classDecl = _codeRunnerConfig.Generator.Generate(ns, tableSchema);
                string outputFileName = Path.Combine(_options.OutputPath, _codeRunnerConfig.NameProvider.GetClassName(tableSchema) + ".cs");
                using (TextWriter writer = _codeRunnerConfig.Writer(outputFileName))
                {
                    Write("Generating {0} ... ", tableSchema.Name);
                    if (_codeRunnerConfig.Options.UseMicrosoftsHeader)
                    {
                        new CodeBuilder().GenerateCode(writer, ns);
                    }
                    else
                    {
                        writer.Write(UseHyperActiveHeader(ns));

                    }
                    WriteLine("Done");
                }
            }
        }
Esempio n. 17
0
        private string UseHyperActiveHeader(NamespaceDeclaration ns)
        {
            string source = "";

            // Generate source to a string for post parsing.
            string tempSource = String.Empty;
            using (StringWriter tempWriter = new StringWriter())
            {
                new CodeBuilder().GenerateCode(tempWriter, ns);
                tempSource = tempWriter.ToString();
            }

            // Now while walking through each line of the file, intercept where
            // there is Microsoft header s***e and put in HyperActive header s***e.
            using (StringReader reader = new StringReader(tempSource))
            using (StringWriter tempWriter = new StringWriter())
            {
                bool insideHeader = false;
                bool hyperActiveMessageWritten = false;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line == "// </auto-generated>")
                    {
                        insideHeader = false;
                    }
                    if (!insideHeader)
                    {
                        tempWriter.WriteLine(line);
                    }
                    else if (!hyperActiveMessageWritten)
                    {
                        tempWriter.WriteLine("// HyperActive {0} generated this file.", Assembly.GetExecutingAssembly().GetName().Version.ToString());
                        hyperActiveMessageWritten = true;
                    }
                    if (line.Trim() == "// <auto-generated>")
                    {
                        insideHeader = true;
                    }
                }
                source = tempWriter.ToString();
            }
            return source;
        }
Esempio n. 18
0
        private void GenerateEnums()
        {
            if (_options.Enums == null || _options.Enums.Count() == 0)
            {
                return;
            }

            var generator = new EnumGenerator(_codeRunnerConfig.DbProvider, _codeRunnerConfig.Options, _codeRunnerConfig.NameProvider);
            foreach (var enumDescriptor in _options.Enums)
            {
                Write("Generating enum {0} ... ", enumDescriptor.TableName);
                var @enum = generator.Generate(enumDescriptor.TableName, enumDescriptor.NameField, enumDescriptor.ValueField);
                if (@enum == null)
                {
                    WriteLine("Failed.  Make sure {0} is spelled correctly and exists in the database.", enumDescriptor.TableName);
                    continue;
                }
                var ns = new NamespaceDeclaration(_options.EnumNamespace);
                ns.AddClass(@enum);

                string fileName = Inflector.Pluralize(_codeRunnerConfig.NameProvider.GetClassName(enumDescriptor.TableName)) + ".cs";
                string outputFilePath = Path.Combine(_options.EnumOutputPath, fileName);
                using (TextWriter writer = _codeRunnerConfig.Writer(outputFilePath))
                {
                    if (_options.UseMicrosoftsHeader)
                    {
                        new CodeBuilder().GenerateCode(writer, ns);
                    }
                    else
                    {
                        writer.Write(UseHyperActiveHeader(ns));
                    }
                }
                WriteLine("Done.");
            }
        }
        public void VerifyAddClassTypeParameters()
        {
            NamespaceDeclaration nsdecl =
                new NamespaceDeclaration("Test");

            nsdecl.AddClass("Customer");
            nsdecl.AddClass("CustomerList")
                .InheritsFrom("System.Collections.Generic.List", "Test.Customer");

            using (DomTester dom = new DomTester(nsdecl))
            {
                Assert.IsTrue(dom.Type("CustomerList")
                    .InheritsFrom("List`1", "Customer"));
            }
            //new CodeBuilder().GenerateCode(Console.Out, nsdecl);
        }
        /// <summary>
        /// Generates the specified namespace declaration.
        /// </summary>
        /// <param name="namespaceDeclaration">The namespace declaration.</param>
        /// <param name="table">The table.</param>
        /// <returns></returns>
        public ClassDeclaration Generate(NamespaceDeclaration namespaceDeclaration, TableSchema table)
        {
            ClassDeclaration classDecl = this.CreateClass(namespaceDeclaration, table);
            this.AddClassAttributes(classDecl, table);
            this.CreatePrimaryKeyProperty(classDecl, table);

            foreach (ForeignKeyColumnSchema fk in table.ForeignKeys)
            {
                this.CreateForeignKey(classDecl, fk);
            }
            if (table.PrimaryKey != null && table.PrimaryKey.ForeignKeyReferences != null)
            {
                foreach (ForeignKeyColumnSchema foreignkey in table.PrimaryKey.ForeignKeyReferences)
                {
                    this.CreateForeignKeyReference(classDecl, foreignkey);
                }
            }
            if (table.NonKeyColumns != null)
            {
                foreach (ColumnSchema column in table.NonKeyColumns)
                {
                    this.CreateNonKeyProperty(classDecl, column);
                }
            }
            if (_configOptions.GenerateColumnList)
            {
                CreateColumnList(table, classDecl);
            }
            this.CreateConstructors(classDecl, table);
            this.CreateAssociationProperties(classDecl, table);
            this.AddMethods(classDecl, table);
            return classDecl;
        }
        /// <summary>
        /// Generates the test class for a table.
        /// </summary>
        /// <param name="writer">The writer to which the code is written.</param>
        /// <param name="namespaceName">The namespace containing the test class.</param>
        /// <param name="table">The table being tested.</param>
        public void Generate(TextWriter writer, string namespaceName, TableSchema table)
        {
            if (table == null)
                throw new ArgumentNullException("table");

            NamespaceDeclaration nstest = new NamespaceDeclaration(namespaceName + ".Tests");

            //declare the test class
            string typeName = this.NameProvider.GetClassName(table.Name);
            ClassDeclaration testclass = nstest.AddClass(typeName + "Tests", true);
            string targetTypeName = namespaceName + "." + typeName;
            testclass.InheritsFrom(new ClassDeclaration("ActiveRecordBaseTest", new CodeDomTypeReference(targetTypeName)));

            //create the test method
            MethodDeclaration testmeth = testclass.AddMethod(String.Format("Verify{0}", typeName)).Public();
            testmeth.AddAttribute("NUnit.Framework.TestAttribute");
            string fullName = namespaceName + "." + typeName;

            string fieldName = this.NameProvider.GetClassName(table.Name).Substring(0, 1).ToLower() + this.NameProvider.GetClassName(table.Name).Substring(1);
            testmeth.Declare(fieldName).New(new CodeDomTypeReference(fullName));//generates: Customer customer = new Customer();
            foreach (ColumnSchema column in table.NonKeyColumns)
            {
                string propertyName = this.NameProvider.GetPropertyName(column);
                string propertyValue = this.ValueProvider.GetValue(column);
                testmeth.Assign(fieldName).Property(propertyName).To(propertyValue);
            }
            testmeth.Call(fieldName, "Save");
            nstest.Imports("System");
            CodeBuilder builder = new CodeBuilder();
            builder.GenerateCode(writer, nstest);
        }
Esempio n. 22
0
        public void CanCreateClass()
        {
            //create dom
            NamespaceDeclaration nsdecl = new NamespaceDeclaration("My.Data");
            ClassDeclaration cdecl = nsdecl.AddClass("Customer");
            cdecl.AddProperty("ID", "_id", "System.Int32");

            //compile to assembly
            CodeBuilder builder = new CodeBuilder();
            CodeCompileUnit compunit = builder.CreateCodeCompileUnit(nsdecl);
            CodeDomProvider compiler = new CSharpCodeProvider();
            CompilerParameters options = new CompilerParameters();
            options.GenerateInMemory = true;
            options.WarningLevel = 4;
            options.TreatWarningsAsErrors = true;
            options.IncludeDebugInformation = true;
            CompilerResults results = compiler.CompileAssemblyFromDom(options, compunit);
            Assembly compiled = results.CompiledAssembly;

            //load assembly in it's own app domain
            AppDomain testdomain = AppDomain.CreateDomain("testdomain");
            testdomain.Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            testdomain.Load(compiled.GetName());

            //test the assembly
            Type testtype = compiled.GetType("My.Data.Customer");
            Assert.IsNotNull(testtype);
            PropertyInfo id = testtype.GetProperty("ID");
            Assert.AreEqual(typeof(int), id.PropertyType);
            AppDomain.Unload(testdomain);
        }