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); }
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); var cw = new ClassWriter(table, new CodeWriterSettings()); //act var txt = cw.Write(); //assert var hasName = txt.Contains("public class Category"); var hasCategoryId = txt.Contains("public virtual int CategoryId { get; set; }"); var hasCategoryName = txt.Contains("public virtual string CategoryName { get; set; }"); Assert.IsTrue(hasName); Assert.IsTrue(hasCategoryId); Assert.IsTrue(hasCategoryName); }
public void ClassWriter() { ClassWriter writer = new ClassWriter(); writer.Write(new ClassTemplate((NamespaceTemplate)null, "test"), this.output); Assert.AreEqual("public partial class test\r\n{\r\n}", this.output.ToString()); }
void WriteType(FrameworkVersion version, TypeWrapper type) { var writer = new ClassWriter(this, version, type); writer.Write(); foreach (var item in type.GetConstructors().Where(x => x.IsPublic)) { var itemWriter = new ConstructorWriter(this, version, item); itemWriter.Write(); } foreach (var item in type.GetMethodsToDocument()) { // If a method is in another namespace, it is inherited and should not be overwritten if (item.DeclaringType.Namespace == type.Namespace) { var itemWriter = new MethodWriter(this, version, item); itemWriter.Write(); } } foreach (var item in type.GetEvents()) { // If an event is in another namespace, it is inherited and should not be overwritten if (item.DeclaringType.Namespace == type.Namespace) { var itemWriter = new EventWriter(this, version, item); itemWriter.Write(); } } }
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 WriteSharedPrimaryKeyTest() { //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 cw = new ClassWriter(table, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst }); //act var txt = cw.Write(); //assert var hasScalarKey = txt.Contains("public string Regnum { get; set; }"); var hasForeignKey = txt.Contains("public virtual Vehicle Vehicle { get; set; }"); Assert.IsTrue(hasScalarKey); Assert.IsTrue(hasForeignKey); }
public void CreateWindsorContainerBuilderInjection() { var apperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var classesToCreate = new List <string>(); for (var i = 0; i < apperCase.Length; i++) { for (var j = 0; j < firstInt; j++) { for (var k = 0; k < secondInt; k++) { var className = $"{apperCase[i]}{j}{k}"; classesToCreate.Add($"{className}Inject"); } } } var nameSpace = "WindsorIoc"; var folderPath = $"/Users/yoavhagashi/Project/IOCTest/{nameSpace}"; var builder = new ClassBuilder(); var writer = new ClassWriter(); var windsorContainerBuilder = new WindsorContainerBuilder(); var constractorParams = new Dictionary <string, string>(); foreach (var className in classesToCreate) { var newClass = builder.Build("WindsorIoc", className, true, constractorParams); var path = Path.Join(folderPath, "Classes", $"{className}.cs"); writer.Write(path, newClass); constractorParams.Add($"I{className}", className); windsorContainerBuilder.AddRegisteration($"I{className}", className); // windsorContainerBuilder.AddResolve($"I{className}"); if (constractorParams.Count >= maxConstructor) { constractorParams.Clear(); } } // windsorContainerBuilder.WithTimer(); var containerTestMethod = windsorContainerBuilder.Build(); var windsorContainerTestnewClass = builder.Build(nameSpace, "WindsorContainerTestInjection", true, null, new Dictionary <string, string> { { "TestContainer", containerTestMethod } }, windsorContainerBuilder.GetUsingSection()); var pathWindsorContainerTest = Path.Join(folderPath, $"WindsorContainerTestInjection.cs"); writer.Write(pathWindsorContainerTest, windsorContainerTestnewClass); }
public void ClassOneProperty() { ClassTemplate template = new ClassTemplate((NamespaceTemplate)null, "test"); template.AddProperty("Prop1", Code.Type("string")); ClassWriter writer = new ClassWriter(); writer.Write(template, this.output); Assert.AreEqual("public partial class test\r\n{\r\n public string Prop1 { get; set; }\r\n}", this.output.ToString()); }
public void ClassWithComment() { ClassTemplate template = new ClassTemplate((NamespaceTemplate)null, "test"); template.Comment = Code.Comment("test comment"); ClassWriter writer = new ClassWriter(); writer.Write(template, this.output); Assert.AreEqual("// test comment\r\npublic partial class test\r\n{\r\n}", this.output.ToString()); }
public void ClassOnePropertyWithAttributeAndOneNormalProperty() { ClassTemplate template = new ClassTemplate((NamespaceTemplate)null, "test"); template.AddProperty("Prop1", Code.Type("string")).WithAttribute("attr"); template.AddProperty("Prop2", Code.Type("string")); ClassWriter writer = new ClassWriter(this.options); writer.Write(template, this.output); Assert.AreEqual("public partial class test\r\n{\r\n [attr]\r\n public string Prop1 { get; set; }\r\n\r\n public string Prop2 { get; set; }\r\n}", this.output.ToString()); }
public void ClassOneFieldAndOneConstructor() { ClassTemplate template = new ClassTemplate((NamespaceTemplate)null, "test"); template.AddField("field1", Code.Type("string")); template.AddConstructor(); ClassWriter writer = new ClassWriter(this.options); writer.Write(template, this.output); Assert.AreEqual("export class test {\r\n private field1: string;\r\n\r\n public constructor() {\r\n }\r\n}", this.output.ToString()); }
public void BuildClass(DatabaseTable databaseTable) { try { var cw = new ClassWriter(databaseTable, new CodeWriterSettings()); var txt = cw.Write(); Clipboard.SetText(txt, TextDataFormat.UnicodeText); } catch (Exception exception) { Debug.WriteLine(exception.Message); } }
public string BuildClass(DatabaseTable databaseTable) { StringBuilder sb = new StringBuilder(); try { var cw = new ClassWriter(databaseTable, new CodeWriterSettings()); sb.Append(cw.Write()); } catch (Exception exception) { Debug.WriteLine(exception.Message); } return(sb.ToString()); }
public void WriteForeignKeyInverseTest() { //arrange var schema = ArrangeSchema(); var categoryTable = schema.FindTableByName("Categories"); var cw = new ClassWriter(categoryTable, new CodeWriterSettings()); //act var txt = cw.Write(); //assert var hasProducts = txt.Contains("public virtual IList<Product> ProductCollection { get; private set; }"); Assert.IsTrue(hasProducts); }
public void WriteForeignKeyTest() { //arrange var schema = ArrangeSchema(); var productsTable = schema.FindTableByName("Products"); var cw = new ClassWriter(productsTable, new CodeWriterSettings()); //act var txt = cw.Write(); //assert var hasCategory = txt.Contains("public virtual Category Category { get; set; }"); Assert.IsTrue(hasCategory); }
public void TestCompositeForeignKey() { //arrange var schema = Arrange(); var table = schema.FindTableByName("Products"); var cw = new ClassWriter(table, new CodeWriterSettings()); //act var txt = cw.Write(); //assert //virtual of type tableName var hasKey = txt.Contains("public virtual Origin Origin { get; set; }"); Assert.IsTrue(hasKey); }
public void TestCompositeKeyWithCodeFirst() { //arrange var schema = Arrange(); var table = schema.FindTableByName("Origin"); var cw = new ClassWriter(table, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst }); //act var txt = cw.Write(); //assert //non virtual actual properties var hasKey = txt.Contains("public string OriginKey1 { get; set; }"); Assert.IsTrue(hasKey); }
public void WriteInverseForeignKeyTest() { //arrange var schema = ArrangeSchema(); var table = schema.FindTableByName("Address"); var cw = new ClassWriter(table, new CodeWriterSettings()); //act var txt = cw.Write(); //assert var hasBillingAddress = txt.Contains("public virtual IList<Order> BillingAddressCollection { get; private set; }"); var hasDeliveryAddress = txt.Contains("public virtual IList<Order> DeliveryAddressCollection { get; private set; }"); Assert.IsTrue(hasBillingAddress); Assert.IsTrue(hasDeliveryAddress); }
public void WriteMultipleForeignKeyTest() { //arrange var schema = ArrangeSchema(); var table = schema.FindTableByName("Orders"); var cw = new ClassWriter(table, new CodeWriterSettings()); //act var txt = cw.Write(); //assert var hasBillingAddress = txt.Contains("public virtual Address BillingAddress { get; set; }"); var hasDeliveryAddress = txt.Contains("public virtual Address DeliveryAddress { get; set; }"); Assert.IsTrue(hasBillingAddress); Assert.IsTrue(hasDeliveryAddress); }
public Task Generate(List <string> files) { ExecutionDataflowBlockOptions maxreadfiles = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = options.maxReadCoount }; ExecutionDataflowBlockOptions maxprocessfiles = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = options.maxProcessCount }; ExecutionDataflowBlockOptions maxwritefiles = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = options.maxWriteCount }; var readfiles = new TransformBlock <string, string>( new Func <string, Task <string> >(ClassReader.Read), maxreadfiles); var processfiles = new TransformBlock <string, List <ClassInfo> >( new Func <string, List <ClassInfo> >(GenerateClassInfoes), maxprocessfiles); var writesfiles = new ActionBlock <List <ClassInfo> >( async(x) => await writer.Write(x), maxprocessfiles); readfiles.LinkTo(processfiles, new DataflowLinkOptions() { PropagateCompletion = true }); processfiles.LinkTo(writesfiles, new DataflowLinkOptions() { PropagateCompletion = true }); foreach (var file in files) { readfiles.Post(file); } readfiles.Complete(); return(writesfiles.Completion); }
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 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 WriteCodeFirstTest() { //arrange var schema = ArrangeSchema(); var categoryTable = schema.FindTableByName("Categories"); var cw = new ClassWriter(categoryTable, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst }); //act var txt = cw.Write(); //assert var hasCategoryId = txt.Contains("public int CategoryId { get; set; }"); var hasProducts = txt.Contains("public virtual ICollection<Product> ProductCollection { get; private set; }"); Assert.IsTrue(hasCategoryId, "Ordinary scalar properties don't need to be virtual"); Assert.IsTrue(hasProducts); }
public void Basics() { var klass = new ClassWriter { IsPublic = true, Inherits = "System.Object", IsPartial = true, Name = "MyClass", UsePriorityOrder = true }; klass.Fields.Add(new FieldWriter { IsPublic = true, Name = "my_field", Type = TypeReferenceWriter.Bool }); klass.AddInlineComment("// Test comment"); klass.Methods.Add(new MethodWriter { Name = "MyMethod", IsPublic = true, ReturnType = TypeReferenceWriter.Void }); klass.Methods [0].Parameters.Add(new MethodParameterWriter("test", TypeReferenceWriter.Bool)); var sw = new StringWriter(); var writer = new CodeWriter(sw); klass.Write(writer); var expected = @"public partial class MyClass : System.Object { public bool my_field; // Test comment public void MyMethod (bool test) { } } "; Assert.AreEqual(expected, sw.ToString()); }
public void TestIntDataTypes() { //arrange var schema = new DatabaseSchema(null, SqlType.Oracle); schema.AddTable("DEPARTMENTS") .AddColumn("DEPARTMENT_ID", "NUMBER(4,0)").AddPrimaryKey() .AddColumn("DEPARTMENT_NAME", "VARCHAR2(30)"); var depts = schema.FindTableByName("DEPARTMENTS"); var cw = new ClassWriter(depts, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst, }); //act //key line is DataTypeWriter.FindDataType(column) // calling dt.NetDataTypeCSharpName //also mapping (HasPrecision is invalid for ints) var code = cw.Write(); //assert Assert.IsTrue(code.Contains("public short DepartmentId { get; set; }"), "Type of Id should be short, not decimal"); }
public void TestAssociationTable() { //arrange var schema = Arrange(); var table = schema.FindTableByName("ProductCategories"); var cw = new ClassWriter(table, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst }); //act var txt = cw.Write(); //assert var hasCategoryId = txt.Contains("public int CategoryId { get; set; }"); var hasCategory = txt.Contains("public virtual Category Category { get; set; }"); var hasProductId = txt.Contains("public int ProductId { get; set; }"); var hasProduct = txt.Contains("public virtual Product Product { get; set; }"); Assert.IsTrue(hasCategoryId); Assert.IsTrue(hasCategory); Assert.IsTrue(hasProductId); Assert.IsTrue(hasProduct); }
void WriteType(FrameworkVersion version, TypeWrapper type) { var writer = new ClassWriter(this, version, type); writer.Write(); foreach (var item in type.GetConstructors().Where(x => x.IsPublic)) { var itemWriter = new ConstructorWriter(this, version, item); itemWriter.Write(); } foreach (var item in type.GetMethodsToDocument()) { var itemWriter = new MethodWriter(this, version, item); itemWriter.Write(); } foreach (var item in type.GetEvents()) { var itemWriter = new EventWriter(this, version, item); itemWriter.Write(); } }
public void TestCompositeForeignKeyCodeFirst() { //arrange var schema = Arrange(); var table = schema.FindTableByName("Products"); var cw = new ClassWriter(table, new CodeWriterSettings { CodeTarget = CodeTarget.PocoEntityCodeFirst, UseForeignKeyIdProperties = true }); //act var txt = cw.Write(); //assert //virtual of type tableName+Key named Key var hasKeyId1 = txt.Contains("public string OriginKey1 { get; set; }"); var hasKeyId2 = txt.Contains("public string OriginKey2 { get; set; }"); var hasForeignKey = txt.Contains("public virtual Origin Origin { get; set; }"); Assert.IsTrue(hasKeyId1); Assert.IsTrue(hasKeyId2); Assert.IsTrue(hasForeignKey); }
public static string Generate(RocketPackDefinition definition, IEnumerable <RocketPackDefinition> externalDefinitions) { var w = new CodeWriter(); // usingの宣言を行う。 { var hashSet = new HashSet <string>(); // ロードされた*.rpfファイルの名前空間をusingする hashSet.UnionWith(externalDefinitions.SelectMany(n => n.Options.Where(m => m.Name == "csharp_namespace").Select(m => m.Value.Trim()))); var sortedList = hashSet.ToList(); sortedList.Sort(); foreach (var name in sortedList) { w.WriteLine($"using {name};"); } } w.WriteLine(); w.WriteLine("#nullable enable"); w.WriteLine(); // namespaceの宣言を行う。 { var option = definition.Options.First(n => n.Name == "csharp_namespace"); w.WriteLine($"namespace {option.Value}"); } w.WriteLine("{"); w.PushIndent(); var enumWriter = new EnumWriter(definition); var classWriter = new ClassWriter(definition, externalDefinitions); var structWriter = new StructWriter(definition, externalDefinitions); foreach (var enumInfo in definition.Enums) { // Enum enumWriter.Write(w, enumInfo); w.WriteLine(); } foreach (var messageInfo in definition.Messages) { if (messageInfo.FormatType == MessageFormatType.Medium) { // Class classWriter.Write(w, messageInfo); } else if (messageInfo.FormatType == MessageFormatType.Small) { // Struct structWriter.Write(w, messageInfo); } w.WriteLine(); } w.PopIndent(); w.WriteLine("}"); return(w.ToString()); }
private static void Main(string[] args) { var inlineAttribute = new Sharpie.Attribute("System.Runtime.CompilerServices.MethodImpl", new string[] { "System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining" }); Class c = new Class("Test") .WithUsing("System") .WithUsing("System.IO") .WithBaseClass("Object") .SetNamespace("SharpieTEst") .WithField(Accessibility.Private, true, false, "object", "_obj") .WithField(Accessibility.Public, false, false, "object", "Obj") .WithField <int>(Accessibility.Public, "n") .WithField <StreamWriter>(Accessibility.Protected, "_writer") .WithConstructor() .WithConstructor( Accessibility.Public, new List <Parameter>() { new Parameter("object", "obj"), new Parameter("object", "obj2") }, "_obj = obj;" + Environment.NewLine + "Obj = obj2;") .WithConstructor( Accessibility.Public, new List <Parameter>() { new Parameter("object", "obj"), new Parameter("object", "obj2"), new Parameter("int", "n"), }, new List <string>() { "obj", "obj2" }, "this.n = n;") .WithProperty <string>(Accessibility.Public, "TestPropString") .WithField <string>(Accessibility.Private, "_fullPropTest") .WithProperty(new Property(Accessibility.Public, "string", "FullPropTest", null, "return _fullPropTest;", null, "_fullPropTest = value;", null)) .WithProperty(new Property(Accessibility.Public, "int", "GetterOnlyTest", null, "return n;", null, null, null)) .WithProperty(new Property( Accessibility.Public, "string", "FullPropTestWithAccess", null, "return _fullPropTest;", Accessibility.Protected, "_fullPropTest = value;", null)) .WithMethod(Accessibility.Public, "string", "Get5", "return \"5\";") .WithMethod(new Method(Accessibility.Public, "string", "Switch5", new Parameter[] { new Parameter("int", "n", "5") }, (bodyWriter) => { bodyWriter.WriteSwitchCaseStatement(new SwitchCaseStatement("n", new CaseStatement[] { new CaseStatement("0", "return \"0\";"), new CaseStatement("1", "return \"1\";"), new CaseStatement("2", "return \"2\";"), new CaseStatement("3", "return \"3\";"), new CaseStatement("4", "return \"4\";"), new CaseStatement("5", "return \"5\";"), }, "throw new ArgumentOutOfRangeException();")); })) .WithMethod(new Method(Accessibility.Public, "string", "SwitchExpression5", new Parameter[] { new Parameter("int", "n", "5") }, (bodyWriter) => { bodyWriter.WriteReturnSwitchExpression(new SwitchCaseExpression("n", new CaseExpression[] { new CaseExpression("0", "\"0\""), new CaseExpression("1", "\"1\""), new CaseExpression("2", "\"2\""), new CaseExpression("3", "\"3\""), new CaseExpression("4", "\"4\""), new CaseExpression("5", "\"5\""), }, "throw new ArgumentOutOfRangeException()")); bodyWriter.WriteReturn().WriteObjectInitializer("Test", new Dictionary <string, string>() { ["FullPropTest"] = "\"abc\"", ["FullPropTestWithAccess"] = "\"def\"" }).EndStatement(); }).WithAttribute(inlineAttribute)); using (var fs = new FileStream("test.cs", FileMode.Create, FileAccess.ReadWrite)) { ClassWriter.Write(c, fs); } }