private readonly String LambdaClassName; // Generated name for the generated class "X$$Lambda$1" /// <summary> /// General meta-factory constructor, supporting both standard cases and /// allowing for uncommon options such as serialization or bridging. /// </summary> /// <param name="caller"> Stacked automatically by VM; represents a lookup context /// with the accessibility privileges of the caller. </param> /// <param name="invokedType"> Stacked automatically by VM; the signature of the /// invoked method, which includes the expected static /// type of the returned lambda object, and the static /// types of the captured arguments for the lambda. In /// the event that the implementation method is an /// instance method, the first argument in the invocation /// signature will correspond to the receiver. </param> /// <param name="samMethodName"> Name of the method in the functional interface to /// which the lambda or method reference is being /// converted, represented as a String. </param> /// <param name="samMethodType"> Type of the method in the functional interface to /// which the lambda or method reference is being /// converted, represented as a MethodType. </param> /// <param name="implMethod"> The implementation method which should be called (with /// suitable adaptation of argument types, return types, /// and adjustment for captured arguments) when methods of /// the resulting functional interface instance are invoked. </param> /// <param name="instantiatedMethodType"> The signature of the primary functional /// interface method after type variables are /// substituted with their instantiation from /// the capture site </param> /// <param name="isSerializable"> Should the lambda be made serializable? If set, /// either the target type or one of the additional SAM /// types must extend {@code Serializable}. </param> /// <param name="markerInterfaces"> Additional interfaces which the lambda object /// should implement. </param> /// <param name="additionalBridges"> Method types for additional signatures to be /// bridged to the implementation method </param> /// <exception cref="LambdaConversionException"> If any of the meta-factory protocol /// invariants are violated </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public InnerClassLambdaMetafactory(MethodHandles.Lookup caller, MethodType invokedType, String samMethodName, MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType, boolean isSerializable, Class[] markerInterfaces, MethodType[] additionalBridges) throws LambdaConversionException public InnerClassLambdaMetafactory(MethodHandles.Lookup caller, MethodType invokedType, String samMethodName, MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType, bool isSerializable, Class[] markerInterfaces, MethodType[] additionalBridges) : base(caller, invokedType, samMethodName, samMethodType, implMethod, instantiatedMethodType, isSerializable, markerInterfaces, additionalBridges) { ImplMethodClassName = ImplDefiningClass.Name.Replace('.', '/'); ImplMethodName = ImplInfo.Name; ImplMethodDesc = ImplMethodType.ToMethodDescriptorString(); ImplMethodReturnClass = (ImplKind == MethodHandleInfo.REF_newInvokeSpecial) ? ImplDefiningClass : ImplMethodType.ReturnType(); ConstructorType = invokedType.ChangeReturnType(Void.TYPE); LambdaClassName = TargetClass.Name.Replace('.', '/') + "$$Lambda$" + Counter.IncrementAndGet(); Cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); int parameterCount = invokedType.ParameterCount(); if (parameterCount > 0) { ArgNames = new String[parameterCount]; ArgDescs = new String[parameterCount]; for (int i = 0; i < parameterCount; i++) { ArgNames[i] = "arg$" + (i + 1); ArgDescs[i] = BytecodeDescriptor.unparse(invokedType.ParameterType(i)); } } else { ArgNames = ArgDescs = EMPTY_STRING_ARRAY; } }
private static void writeMap(ClassWriter writer, int capacity, Dictionary <int, List <String> > countryCodeToRegionCodeMap) { writer.addToBody(MAP_COMMENT); writer.addToImports("System"); writer.addToImports("System.Collections.Generic"); writer.addToBody(" internal static Dictionary<int, List<String>> getCountryCodeToRegionCodeMap() {\n"); writer.formatToBody(CAPACITY_COMMENT, capacity, countryCodeToRegionCodeMap.Count); writer.addToBody(" Dictionary<int, List<String>> countryCodeToRegionCodeMap =\n"); writer.addToBody(" new Dictionary<int, List<String>>(" + capacity + ");\n"); writer.addToBody("\n"); writer.addToBody(" List<String> listWithRegionCode;\n"); writer.addToBody("\n"); foreach (var entry in countryCodeToRegionCodeMap) { int countryCallingCode = entry.Key; List <String> regionCodes = entry.Value; writer.addToBody(" listWithRegionCode = new List<String>(" + regionCodes.Count + ");\n"); foreach (String regionCode in regionCodes) { writer.addToBody(" listWithRegionCode.Add(\"" + regionCode + "\");\n"); } writer.addToBody(" countryCodeToRegionCodeMap.Add(" + countryCallingCode + ", listWithRegionCode);\n"); writer.addToBody("\n"); } writer.addToBody(" return countryCodeToRegionCodeMap;\n"); writer.addToBody(" }\n"); }
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); 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()); }
public void CreateClass() { var classesToCreate = new List <string> { "Yoav1", "Yoav2" }; var folderPath = "/Users/yoavhagashi/Project/IOCTest/WindsorIoc"; var builder = new ClassBuilder(); var writer = new ClassWriter(); var windsorContainerFactory = new WindsorContainerFactory(); var constractorParams = new Dictionary <string, string>(); foreach (var className in classesToCreate) { var newClass = builder.Build("WindsorIoc", className, true, constractorParams); var path = Path.Join(folderPath, $"{className}.cs"); writer.Write(path, newClass); constractorParams.Add($"I{className}", className); } var containerTestMethod = windsorContainerFactory.Build("container", constractorParams); var windsorContainerTestnewClass = builder.Build("WindsorIoc", "WindsorContainer", true, null, new Dictionary <string, string> { { "TestContainer", containerTestMethod } }); var pathWindsorContainerTest = Path.Join(folderPath, $"WindsorContainerTest.cs"); writer.Write(pathWindsorContainerTest, windsorContainerTestnewClass); }
protected internal override ByteVector Write(ClassWriter classWriter, byte[] code , int codeLength, int maxStack, int maxLocals) { var byteVector = new ByteVector(); byteVector.PutShort(classWriter.NewUTF8(algorithm)); if (modules == null) { byteVector.PutShort(0); } else { var numModules = modules.Count; byteVector.PutShort(numModules); for (var i = 0; i < numModules; ++i) { var module = modules[i]; var hash = hashes[i]; byteVector.PutShort(classWriter.NewModule(module)).PutShort(hash.Length).PutByteArray (hash, 0, hash.Length); } } return(byteVector); }
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 CreateRepos() { foreach (var table in TableList.Where(x => x.Selected)) { ClassWriter.CreateClassForDbTable(table.Name); } }
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() { //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"); }
public static void Main (string[] args) { OrmLiteConfig.DialectProvider = new FirebirdOrmLiteDialectProvider(); using (IDbConnection db = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;".OpenDbConnection()) using ( IDbCommand dbConn = db.CreateCommand()) { Schema fbd= new Schema(){ Connection = db }; ClassWriter cw = new ClassWriter(){ Schema=fbd, GenerateMetadata=true, //SpaceName= "your.app.namespace", //OutputDirectory="outputpath" //Usings="Using System;\nUsing System.Data\n" }; foreach(var t in fbd.Tables){ Console.Write("Generating POCO Class for table:'{0}'...", t.Name); cw.WriteClass( t); Console.WriteLine(" Done."); } Console.WriteLine("---------------------------------"); Console.WriteLine("See classes in: '{0}'", cw.OutputDirectory); } Console.WriteLine ("This is The End my friend!"); }
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); }
protected internal override ByteVector Write(ClassWriter classWriter, byte[] code , int codeLength, int maxStack, int maxLocals) { var byteVector = new ByteVector(); byteVector.PutShort(platform == null ? 0 : classWriter.NewUTF8(platform)); return(byteVector); }
protected internal override ByteVector Write(ClassWriter classWriter, byte[] code , int codeLength, int maxStack, int maxLocals) { var byteVector = new ByteVector(); byteVector.PutShort(resolution); return(byteVector); }
/// <summary> /// Generates the property which decides if a compiled property is complex. /// </summary> /// <param name="sb">The class writer.</param> /// <param name="info">The property info.</param> private static void IsComplexProperty(ClassWriter sb, PropertyInfo info) { sb.AddProperty( $"Gets or sets a value indicating whether the {info.Name} condition should be compiled as a Complex condition.", AccessLevel.Public, "bool", $"{info.Name}_IsComplex"); }
protected override void SetUp() { document = NewMock <IDocumentWriter>(); cache = NewMock <IValuesCache>(); memberWriter = NewMock <IMemberWriter>(); baseTypeMembersWriter = NewMock <IBaseTypeMembersWriter>(); typeNamesCache = NewMock <ITypeNamesCache>(); writer = new ClassWriter(document, cache, memberWriter, baseTypeMembersWriter, typeNamesCache); }
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 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 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()); }
static void Main(string[] args) { TestObject TO = new TestObject(); StreamWriter Writer = new StreamWriter("./Out.txt", false); ClassWriter.WriteObject(TO, Writer); Writer.Flush(); Writer.Close(); StreamReader Reader = new StreamReader("./Out.txt"); var V = ClassReader.ReadObject(typeof(TestObject), Reader); }
public async Task Tests_Creation() { ClassReader reader = new ClassReader(); ClassWriter writer = new ClassWriter("result1"); GeneratorOptions options = new GeneratorOptions(2, 2, 2); Generator generator = new Generator(options, reader, writer); List <string> files = new List <string>(Directory.GetFiles("test1")); await generator.Generate(files); Assert.AreEqual(1, Directory.GetFiles("result1").Length); }
public void TestsTwoConstructors() { ClassReader reader = new ClassReader(); ClassWriter writer = new ClassWriter("result3"); GeneratorOptions options = new GeneratorOptions(2, 2, 2); Generator generator = new Generator(options, reader, writer); List <string> files = new List <string>(Directory.GetFiles("test3")); generator.Generate(files).Wait(); Assert.AreEqual(2, ParseCompilationUnit(File.ReadAllText(Directory.GetFiles("result3")[0])).DescendantNodes().OfType <MethodDeclarationSyntax>().Count()); }
public Type BuildTypeFromParent(String newTypeName, Type sourceContent, StringBuilder writer, IBuildVisitorDelegate buildVisitorDelegate) { newTypeName = GetBytecodeTypeName(newTypeName); StringBuilder sb = new StringBuilder(); ClassWriter cw = BeanContext.RegisterWithLifecycle(new ClassWriter(ambethClassLoader, sb)).Finish(); IClassVisitor visitor = cw;// new SuppressLinesClassVisitor(cw); visitor = new LogImplementationsClassVisitor(visitor); //visitor = new TraceClassVisitor(visitor, sb); IClassVisitor wrappedVisitor = visitor; Type originalModifiers = BytecodeBehaviorState.State.OriginalType; if (originalModifiers.IsInterface || originalModifiers.IsAbstract) { wrappedVisitor = new InterfaceToClassVisitor(wrappedVisitor); } if (!PublicConstructorVisitor.HasValidConstructor()) { wrappedVisitor = new PublicConstructorVisitor(wrappedVisitor); } wrappedVisitor = buildVisitorDelegate.Invoke(wrappedVisitor); if (Object.ReferenceEquals(wrappedVisitor, visitor)) { // there seem to be no custom action to be done with the new type. So we skip type enhancement return(null); } visitor = wrappedVisitor; visitor.Visit(sourceContent.Attributes, newTypeName, sourceContent, new Type[0]); Type content = null; try { visitor.VisitEnd(); content = cw.GetCreatedType(); } catch (Exception) { Log.Error(sb.ToString()); throw; } if (content == null) { throw new Exception("A visitor did not correctly call its cascaded visitor with VisitEnd()"); } //Verify(content); return(content); }
static void Main(string[] args) { ClassReader reader = new ClassReader(); ClassWriter writer = new ClassWriter("result1"); GeneratorOptions options = new GeneratorOptions(1, 1, 1); Generator generator = new Generator(options, reader, writer); List <string> files = new List <string>(Directory.GetFiles("D:\\test1")); generator.Generate(files).Wait(); Console.WriteLine("Finish..."); Console.ReadKey(); }
/// <summary> /// Generates a compatible Compiled Definition from the class info. /// </summary> /// <param name="classInfo">The class info to generate.</param> /// <returns>The class's C# code.</returns> public static string Generate(ClassInfo classInfo) { bool additionalParametersForClassDefined = classInfo.AdditionalParametersForMethods.Any(x => x.Equals(ClassInfo.AdditionalParamtersForClassMethod, StringComparison.Ordinal)); bool classAddParams = additionalParametersForClassDefined || classInfo.UsesAdditionalParametersForHoldingClass; ClassWriter sb = new ClassWriter( new ClassDefinition(classInfo.Namespace, classInfo.TypeName) { Nullable = true, Partial = true, Usings = Usings, }); FieldDefinitions(sb, classInfo); CompileMethod(sb, classInfo); AttachMethod(sb, classInfo); CombinedAdditionalParametersForClass(sb, additionalParametersForClassDefined); CombinedVariableTypeReassignments(sb, classInfo.TypeOfMethods); foreach (var prop in classInfo.CompiledProps) { IsComplexProperty(sb, prop); } foreach (var prop in classInfo.CompiledDictionaryProps) { IsComplexProperty(sb, prop); } foreach (var prop in classInfo.CompiledProps) { EvalConditionMethod(sb, prop, classInfo.AdditionalParametersForMethods, classAddParams); } foreach (var prop in classInfo.CompiledDictionaryProps) { EvalDictionaryConditionMethod(sb, prop, classInfo.AdditionalParametersForMethods, classAddParams); } foreach (var prop in classInfo.CompiledProps) { GetParametersMethod(sb, prop, classInfo.AdditionalParametersForMethods, classAddParams); } foreach (var prop in classInfo.CompiledDictionaryProps) { GetParametersMethod(sb, prop, classInfo.AdditionalParametersForMethods, classAddParams); } return(sb.ToString()); }
/// <summary> /// Constructs a method which gets the parameters list for the specified property. /// </summary> /// <param name="sb">The class writer.</param> /// <param name="info">The property info.</param> /// <param name="additionParameterMethods">The list of methods which return addition parameter names.</param> /// <param name="classAddParams">True if the class has additional parameters method.</param> private static void GetParametersMethod( ClassWriter sb, PropertyInfo info, IReadOnlyCollection <string> additionParameterMethods, bool classAddParams) { string VarToString((string Name, string Type) var) { return($"new CompiledVariable({SurroundInQuotes(var.Name)}, typeof({var.Type}))"); } string?matchingAdditionalParamtersMethod = additionParameterMethods.FirstOrDefault(x => x.Equals($"{ClassInfo.AdditionalParamtersMethodPrefix}{info.Name}")); using var braces = sb.AddMethod( new MethodDefinition($"GetParameters{info.Name}") { SummaryDoc = $"Gets all parameters which should be presented to the {info.Name} expression.", ReturnsDoc = "All parameters needed by the expression.", Access = AccessLevel.Public, Type = "IList<CompiledVariable>", }); sb.AppendLine($"List<CompiledVariable> parameters = new List<CompiledVariable> {{ {string.Join(", ", info.Variables.Select(VarToString))} }};"); if (matchingAdditionalParamtersMethod != null) { sb.AppendLine($"parameters.AddRange(this.{matchingAdditionalParamtersMethod}());"); } if (classAddParams) { sb.AppendLine($"parameters.AddRange(this.Combined{ClassInfo.AdditionalParamtersForClassMethod}());"); } // Reassign the parameters to have the reassigned types if needed. sb.AppendLine("List<CompiledVariable> reassignedParameters = new List<CompiledVariable>();"); sb.AppendLine("var reassignments = this.CombinedVariableTypeReassignments();"); sb.AppendLine("foreach (var parm in parameters)"); sb.StartBrace(); sb.AppendLine("if (reassignments.TryGetValue(parm.Name, out Type? newType))"); sb.StartBrace(); sb.AppendLine("reassignedParameters.Add(new CompiledVariable(parm.Name, newType));"); sb.EndBrace(); sb.AppendLine("else"); sb.StartBrace(); sb.AppendLine("reassignedParameters.Add(parm);"); sb.EndBrace(); sb.EndBrace(); sb.AppendLine("return reassignedParameters;"); }
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); } }
static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddCommandLine(args, new Dictionary <string, string> { ["-Name"] = "Name" }); var config = builder.Build(); var name = config["Name"]; Console.WriteLine(ClassWriter.WriteHello(name)); }
private void AddCompositePrimaryKey() { var keys = string.Join(", ", _table.Columns .Where(x => x.IsPrimaryKey) //primary keys must be scalar so if it's a foreign key use the Id mirror property //.Select(x => "x." + x.NetName + (x.IsForeignKey ? "Id" : string.Empty)) .Select(x => "x." + ClassWriter.PropertyName(x)) .ToArray()); _cb.AppendLine("// Primary key (composite)"); //double braces for a format _cb.AppendFormat(Builder + "HasKey(x => new {{ {0} }});", keys); }
public static void Main(string[] args) { Console.WriteLine ("Hello World!"); Config.DialectProvider = new FirebirdDialectProvider(); using (IDbConnection db = ("User=SYSDBA;Password=masterkey;Database=GYM.FDB;" + "DataSource=localhost;Dialect=3;charset=ISO8859_1;").OpenDbConnection()) using ( IDbCommand dbConn = db.CreateCommand()) { Schema fbd= new Schema(){ Connection = db }; ClassWriter cw = new ClassWriter(){ Schema=fbd, SpaceName="SuperGym.Records", Usings= "using System;\n"+ "using System.ComponentModel.DataAnnotations;\n"+ "using ServiceStack.Common;\n"+ "using ServiceStack.DataAnnotations;\n"+ "using ServiceStack.OrmSimple;\n" }; //var tables = fbd.Tables; //foreach(var t in tables){ // cw.WriteClass(t); //} Table t = new Table(){Name= "SALDOPORCOBRAR"}; cw.WriteClass(t); } Console.WriteLine ("This is The End my friend!"); }
public static void Main(string[] args) { Console.WriteLine ("Hello World!"); Config.DialectProvider = new FirebirdDialectProvider(); using (IDbConnection db = //"User=SYSDBA;Password=masterkey;Database=MAQUINARIA.FDB;DataSource=172.16.7.40;Dialect=3;charset=ISO8859_1;".OpenDbConnection()) ("User=SYSDBA;Password=masterkey;Database=employee.fdb;" + "DataSource=localhost;Dialect=3;charset=ISO8859_1;").OpenDbConnection()) //("User=SYSDBA;Password=masterkey;Database=/home/angel/bd/INTER2011/INTERNACIONAL2011.FDB;" + // "DataSource=localhost;Dialect=3;charset=ISO8859_1;").OpenDbConnection()) using ( IDbCommand dbConn = db.CreateCommand()) { Schema fbd= new Schema(){ Connection = db }; ClassWriter cw = new ClassWriter(){ Schema=fbd, }; foreach(var t in fbd.Tables){ cw.WriteClass( t); } /*Table t = new Table(){Name= "CONCEPTO"}; cw.WriteClass(t); */ //var materiales = dbConn.Select<Materialsuc>(" MATID='{0}' AND SUCID='{1}'", 9136,30) ; /* var kardex = dbConn.Select<Kardex>(" NUMERO LIKE 'RMDT%' ORDER BY NUMERO DESC ROWS 1 ") ; var r = kardex.FirstOrDefault(); if( r != default(Kardex) ) Console.WriteLine( r.Numero); */ //var concepto = dbConn.Select<Concepto>(" CODIGO = '{0}' ROWS 1 ", "000292") ; //does not work !!! /*var concepto = dbConn.Select<Concepto>( string.Format(" CODIGO = '{0}' ROWS 1 ", "000292") ); var c = concepto.FirstOrDefault(); if( c != default(Concepto) ) Console.WriteLine( c.Descrip ); */ //Console.WriteLine(materiales.Count); //Console.WriteLine("there is company with id:'{0}' ? {1}", // 5, // dbConn.Exists<Company>( "Id='{0}'",5 ) ); //Console.WriteLine("there is company with id:'{0}' ? {1}", // 100, // dbConn.Exists<Company>( "Id='{0}'",100 )) ; Company cp = new Company{Id=5}; Console.WriteLine("there is company with id:'{0}' ? {1}", cp.Id, dbConn.Exists<Company>( cp ) ); cp.Id=100; Console.WriteLine("there is company with id:'{0}' ? {1}", cp.Id, dbConn.Exists<Company>( cp )) ; Console.WriteLine(dbConn.HasChildren<Customer>(new Customer(){Id=20}) ); Console.WriteLine(dbConn.HasChildren<Customer>(new Customer(){Id=1001}) ); Customer cust =new Customer(){ Id=20}; Console.WriteLine("Has customer with Id:'{0}' Children in Sales ? {1}", cust.Id, dbConn.HasChildren<Sales>(cust) ); cust.Id=1001; Console.WriteLine("Has customer with Id:'{0}' Children in Sales ? {1}", cust.Id, dbConn.HasChildren<Sales>(cust) ); } Console.WriteLine ("This is The End my friend!"); }
/// <summary>Main entry-point for this application.</summary> /// <param name="args">Array of command-line argument strings.</param> public static void Main (string[] args) { OrmLiteConfig.DialectProvider = new FirebirdOrmLiteDialectProvider(); using (IDbConnection db = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;".OpenDbConnection()) using ( IDbCommand dbConn = db.CreateCommand()) { Schema fbd= new Schema(){ Connection = db }; ClassWriter cw = new ClassWriter(){ Schema=fbd, GenerateMetadata=true, //SpaceName= "your.app.namespace", //OutputDirectory="outputpath" //Usings="Using System;\nUsing System.Data\n" }; foreach(var t in fbd.Tables){ Console.Write("Generating POCO Class for table:'{0}'...", t.Name); cw.WriteClass( t); Console.WriteLine(" Done."); } Console.WriteLine("---------------------------------"); Console.WriteLine("See classes in: '{0}'", cw.OutputDirectory); //compilar ... CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable=false; cp.GenerateInMemory=false; cp.ReferencedAssemblies.AddRange( new string[]{ "System.dll", "System.ComponentModel.DataAnnotations.dll", Path.Combine( Directory.GetCurrentDirectory(), "NServiceKit.OrmLite.dll"), Path.Combine( Directory.GetCurrentDirectory(), "NServiceKit.Common.dll"), Path.Combine( Directory.GetCurrentDirectory(),"NServiceKit.Interfaces.dll") }); cp.OutputAssembly= Path.Combine(cw.OutputDirectory, cw.SpaceName+".dll"); var providerOptions = new Dictionary<string,string>(); providerOptions.Add("CompilerVersion", "v3.5"); CodeDomProvider cdp =new CSharpCodeProvider(providerOptions); string [] files = Directory.GetFiles(cw.OutputDirectory,"*.cs"); CompilerResults cr= cdp.CompileAssemblyFromFile(cp, files); if( cr.Errors.Count==0){ Console.WriteLine("Generated file {0}", Path.Combine(cw.OutputDirectory, cw.SpaceName+".dll")); } else{ foreach (CompilerError ce in cr.Errors) Console.WriteLine(ce.ErrorText); } } Console.WriteLine ("This is The End my friend!"); }
public static void Main (string[] args) { OrmLiteConfig.DialectProvider = new FirebirdOrmLiteDialectProvider(); using (IDbConnection db = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;".OpenDbConnection()) { Schema fbd= new Schema(){ Connection = db }; Console.WriteLine("--------TABLES-------------"); var tables = fbd.Tables; foreach(Table t in tables){ Console.WriteLine(t.Name); } Console.WriteLine("-------users's owner--------------"); Table t1 = fbd.GetTable("USERS"); Console.WriteLine(t1.Owner); Console.WriteLine ("---------user's columns ----------------"); var Columns = fbd.GetColumns("USERS"); foreach(Column cl in Columns){ Console.WriteLine("{0}--{1}--{2}--{3} -- {4}-- {5}--{6} ", cl.Name,cl.Position, cl.Nullable, cl.Length, cl.DbType, cl.NetType, cl.Sequence); } Console.WriteLine("--------------------------------------------"); Console.WriteLine("EMPLOYEE's Columns "); Columns = fbd.GetColumns("EMPLOYEE"); foreach(Column cl in Columns){ Console.WriteLine("{0}--{1}--{2}--{3} -- {4}-- {5}--{6} -- Computed {7} ", cl.Name,cl.Position, cl.Nullable, cl.Length, cl.DbType, cl.NetType, cl.Sequence,cl.IsComputed); } Columns = fbd.GetColumns("COMPANY"); foreach(Column cl in Columns){ Console.WriteLine("{0}--{1}--{2}--{3} -- {4}-- {5}--{6} ", cl.Name,cl.Position, cl.Nullable, cl.Length, cl.DbType, cl.NetType, cl.Sequence); } Console.WriteLine("--------------------------------------------"); Console.WriteLine("-----------------Procedure---------------------------"); Console.WriteLine ("----- ADD_EMP_PROJ ----"); Procedure p = fbd.GetProcedure("ADD_EMP_PROJ"); Console.WriteLine("p.Name {0} p.Owner {1} p.Inputs {2} p.Outputs {3} p.Type {4}", p.Name, p.Owner, p.Inputs, p.Outputs, p.Type); var parameters = fbd.GetParameters(p); foreach( var par in parameters){ Console.WriteLine("p.ProcedureName {0} p.Name {1} p.Position {2} p.ParameterType {3} p.DbType {4} p.NetType {5}", par.ProcedureName, par.Name, par.Position, par.Direction, par.DbType, par.NetType); } Console.WriteLine ("----- ALL_LANGS ----"); p = fbd.GetProcedure("ALL_LANGS"); Console.WriteLine("p.Name {0} p.Owner {1} p.Inputs {2} p.Outputs {3} p.Type {4}", p.Name, p.Owner, p.Inputs, p.Outputs, p.Type); parameters = fbd.GetParameters(p); parameters = fbd.GetParameters(p); foreach( var par in parameters){ Console.WriteLine("p.ProcedureName {0} p.Name {1} p.Position {2} p.ParameterType {3} p.DbType {4} p.NetType {5}", par.ProcedureName, par.Name, par.Position, par.Direction, par.DbType, par.NetType); } ClassWriter cw = new ClassWriter(){ Schema=fbd, }; cw.WriteClass( new Table(){Name="EMPLOYEE"} ); Console.WriteLine("This is The End my friend"); //DTOGenerator } }