private static TableDescription GetTable(OrmObjectsDef odef, string schema, string table) { string id = "tbl" + schema + table; TableDescription t = odef.GetTable(id); if (t == null) { t = new TableDescription(id, GetTableName(schema, table)); odef.Tables.Add(t); } return(t); }
public EntityDescription(string id, string name, string nameSpace, string description, OrmObjectsDef ormObjectsDef, EntityDescription baseEntity, EntityBehaviuor behaviour) { _id = id; _name = name; _description = description; _tables = new List <TableDescription>(); _properties = new List <PropertyDescription>(); _suppressedProperties = new List <PropertyDescription>(); _ormObjectsDef = ormObjectsDef; _namespace = nameSpace; _baseEntity = baseEntity; _behaviour = behaviour; }
protected PropertyDescription AppendColumn(Dictionary <Column, Column> columns, Column c, EntityDescription e, out bool created) { OrmObjectsDef odef = e.OrmObjectsDef; created = false; PropertyDescription pe = e.Properties.Find(delegate(PropertyDescription pd) { if (pd.FieldName == c.ColumnName || pd.FieldName.TrimEnd(']').TrimStart('[') == c.ColumnName) { return(true); } else { return(false); } }); if (pe == null) { string[] attrs = null; bool pk = GetAttributes(c, out attrs); string name = Trim(Capitalize(c.ColumnName)); if (pk) { name = "ID"; } pe = new PropertyDescription(name, null, attrs, null, GetType(c, columns, odef), c.ColumnName, e.Tables[0], AccessLevel.Private, AccessLevel.Public); e.Properties.Add(pe); created = true; } else { string[] attrs = null; if (GetAttributes(c, out attrs)) { pe.Name = "ID"; } pe.Attributes = Merge(pe.Attributes, attrs); if (!pe.PropertyType.IsUserType) { pe.PropertyType = GetType(c, columns, odef); } } return(pe); }
private static EntityDescription GetEntity(OrmObjectsDef odef, string schema, string tableName, out bool created) { created = false; string ename = GetEntityName(schema, tableName); EntityDescription e = odef.GetEntity(ename); if (e == null) { e = new EntityDescription(ename, Capitalize(tableName), "", null, odef); TableDescription t = GetTable(odef, schema, tableName); e.Tables.Add(t); odef.Entities.Add(e); created = true; } return(e); }
static void Main(string[] args) { Console.WriteLine("OrmObjects CodeGen utility."); Console.WriteLine(); CommandLine.Utility.Arguments cmdLine = new CommandLine.Utility.Arguments(args); string outputLanguage; string outputFolder; OrmObjectsDef ormObjectsDef; string inputFilename; CodeDomProvider codeDomProvider; bool split, separateFolder; string[] skipEntities; string[] processEntities; OrmCodeDomGeneratorSettings settings = new OrmCodeDomGeneratorSettings(); bool validateOnly, testRun; if (cmdLine["?"] != null || cmdLine["h"] != null || cmdLine["help"] != null || args == null || args.Length == 0) { Console.WriteLine("Command line parameters:"); Console.WriteLine(" -f\t- source xml file"); Console.WriteLine(" -v\t- validate input file against schema only"); Console.WriteLine(" -t\t- test run (generate files in memory)"); Console.WriteLine(" -l\t- code language [cs, vb] (\"cs\" by default)"); //Console.WriteLine(" -p\t- generate partial classes (\"false\" by default)"); Console.WriteLine(" -sp\t- split entity class and entity's schema definition\n\t\t class code by diffrent files (\"false\" by default)"); Console.WriteLine(" -sk\t- skip entities"); Console.WriteLine(" -e\t- entities to process"); //Console.WriteLine(" -cB\t- behaviour of class codegenerator\n\t\t [Objects, PartialObjects] (\"Objects\" by default)"); Console.WriteLine(" -sF\t- create folder for each entity."); Console.WriteLine(" -o\t- output files folder."); Console.WriteLine(" -pmp\t- private members prefix (\"_\" by default)"); Console.WriteLine(" -cnP\t- class name prefix (null by default)"); Console.WriteLine(" -cnS\t- class name suffix (null by default)"); Console.WriteLine(" -fnP\t- file name prefix (null by default)"); Console.WriteLine(" -fnS\t- file name suffix (null by default)"); return; } if (cmdLine["f"] != null) { inputFilename = cmdLine["f"]; } else { Console.WriteLine("Please give 'f' parameter"); return; } validateOnly = (cmdLine["v"] != null); testRun = (cmdLine["t"] != null); if (cmdLine["l"] != null) { outputLanguage = cmdLine["l"]; } else { outputLanguage = "CS"; } if (cmdLine["sF"] != null) { separateFolder = true; } else { separateFolder = false; } LanguageSpecificHacks languageHacks = LanguageSpecificHacks.None; if (outputLanguage.ToUpper() == "VB") { codeDomProvider = new VBCodeProvider(); languageHacks = LanguageSpecificHacks.VisualBasic; } else if (outputLanguage.ToUpper() == "CS") { codeDomProvider = new CSharpCodeProvider(); languageHacks = LanguageSpecificHacks.CSharp; } else { Console.WriteLine("Error: incorrect value in \"l\" parameter."); return; } if (cmdLine["sp"] != null) { split = true; } else { split = false; } if (cmdLine["o"] != null) { outputFolder = cmdLine["o"]; } else { outputFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (string.IsNullOrEmpty(outputFolder)) { outputFolder = System.IO.Path.GetPathRoot(System.Reflection.Assembly.GetExecutingAssembly().Location); } } if (cmdLine["sk"] != null) { skipEntities = cmdLine["sk"].Split(','); } else { skipEntities = new string[] { } }; if (cmdLine["e"] != null) { processEntities = cmdLine["e"].Split(','); } else { processEntities = new string[] { } }; if (cmdLine["pmp"] != null) { settings.PrivateMembersPrefix = cmdLine["pmp"]; } if (cmdLine["fnP"] != null) { settings.FileNamePrefix = cmdLine["fnP"]; } if (cmdLine["fnS"] != null) { settings.FileNameSuffix = cmdLine["fnS"]; } if (cmdLine["cnP"] != null) { settings.ClassNamePrefix = cmdLine["cnP"]; } if (cmdLine["cnS"] != null) { settings.ClassNameSuffix = cmdLine["cnS"]; } if (!System.IO.File.Exists(inputFilename)) { Console.WriteLine("Error: source file not found."); return; } if (!System.IO.Directory.Exists(outputFolder)) { Console.WriteLine("Error: output folder not found."); return; } if (string.IsNullOrEmpty(System.IO.Path.GetDirectoryName(outputFolder))) { outputFolder = System.IO.Path.GetPathRoot(outputFolder + System.IO.Path.DirectorySeparatorChar.ToString()); } else { outputFolder = System.IO.Path.GetDirectoryName(outputFolder + System.IO.Path.DirectorySeparatorChar.ToString()); } try { Console.Write("Parsing file '{0}'... ", inputFilename); using (XmlReader rdr = XmlReader.Create(inputFilename)) { ormObjectsDef = OrmObjectsDef.LoadFromXml(rdr, new XmlUrlResolver()); } Console.WriteLine("done!"); if (validateOnly) { Console.WriteLine("Input file validation success."); return; } } catch (Exception exc) { Console.WriteLine("error: {0}", exc.Message); if (exc.InnerException != null) { Console.WriteLine("error: {0}", exc.InnerException.Message); } return; } if (!Directory.Exists(outputFolder)) { try { Directory.CreateDirectory(outputFolder); } catch (Exception) { } } OrmCodeDomGenerator gen = new OrmCodeDomGenerator(ormObjectsDef); settings.Split = split; settings.LanguageSpecificHacks = languageHacks; Console.WriteLine("Generation entities from file '{0}' using these settings:", inputFilename); Console.WriteLine(" Output folder: {0}", outputFolder); Console.WriteLine(" Language: {0}", outputLanguage.ToLower()); Console.WriteLine(" Split files: {0}", split); Console.WriteLine(" Skip entities: {0}", string.Join(" ", skipEntities)); Console.WriteLine(" Process entities: {0}", string.Join(" ", processEntities)); List <string> errorList = new List <string>(); int totalEntities = 0; int totalFiles = 0; foreach (EntityDescription entity in ormObjectsDef.Entities) { bool skip = false; if (processEntities.Length != 0) { skip = true; foreach (string processEntityId in processEntities) { if (processEntityId == entity.Identifier) { skip = false; break; } } } foreach (string skipEntityId in skipEntities) { if (skipEntityId == entity.Identifier) { skip = true; break; } } if (skip) { continue; } string privateFolder; if (separateFolder) { privateFolder = outputFolder + System.IO.Path.DirectorySeparatorChar.ToString() + entity.Name + System.IO.Path.DirectorySeparatorChar; } else { privateFolder = outputFolder + System.IO.Path.DirectorySeparatorChar.ToString(); } Dictionary <string, CodeCompileUnit> unitsDic; unitsDic = gen.GetEntityDom(entity.Identifier, settings); Console.Write("."); if (!System.IO.Directory.Exists(privateFolder)) { System.IO.Directory.CreateDirectory(privateFolder); } foreach (string name in unitsDic.Keys) { Console.Write("."); try { GenerateCode(codeDomProvider, unitsDic[name], System.IO.Path.GetFullPath(privateFolder + System.IO.Path.DirectorySeparatorChar.ToString() + name), testRun); Console.Write("."); totalFiles++; } catch (Exception exc) { Console.Write("."); errorList.Add( string.Format("Entity: {0}; file: {1}; message: {2}", entity.Identifier, name, exc.Message)); } } totalEntities++; } Console.WriteLine(); Console.WriteLine("Result:"); Console.WriteLine("\t {0} entities processed", totalEntities); Console.WriteLine("\t {0} files generated", totalFiles); Console.WriteLine("\t {0} errors encountered", errorList.Count); if (errorList.Count != 0) { Console.WriteLine("Errors:"); foreach (string s in errorList) { Console.WriteLine("\t" + s); for (int i = 0; i < Console.WindowWidth; i++) { Console.Write("-"); } Console.WriteLine(); } } }
private static TypeDescription GetClrType(string dbType, bool nullable, OrmObjectsDef odef) { TypeDescription t = null; string id = null; string type = null; switch (dbType) { case "rowversion": case "timestamp": id = "tBytes"; type = "System.Byte[]"; break; case "varchar": case "nvarchar": case "char": case "nchar": case "text": case "ntext": id = "tString"; type = "System.String"; break; case "int": id = "tInt32"; type = "System.Int32"; break; case "smallint": id = "tInt16"; type = "System.Int16"; break; case "bigint": id = "tInt64"; type = "System.Int64"; break; case "tinyint": id = "tByte"; type = "System.Byte"; break; case "datetime": case "smalldatetime": id = "tDateTime"; type = "System.DateTime"; break; case "money": case "numeric": case "decimal": id = "tDecimal"; type = "System.Decimal"; break; case "float": id = "tDouble"; type = "System.Double"; break; case "real": id = "tSingle"; type = "System.Single"; break; case "varbinary": case "binary": id = "tBytes"; type = "System.Byte[]"; break; case "bit": id = "tBoolean"; type = "System.Boolean"; break; case "xml": id = "tXML"; type = "System.Xml.XmlDocument"; break; case "uniqueidentifier": id = "tGUID"; type = "System.Guid"; break; case "image": id = "tBytes"; type = "System.Byte[]"; break; default: throw new ArgumentException("Unknown database type " + dbType); } if (nullable) { id += "nullable"; } t = odef.GetType(id, false); if (t == null) { Type tp = GetTypeByName(type); if (nullable && tp.IsValueType) { type = String.Format("System.Nullable`1[{0}]", type); } t = new TypeDescription(id, type); odef.Types.Add(t); } return(t); }
protected TypeDescription GetRelatedType(string constraint, IDictionary <Column, Column> columns, OrmObjectsDef odef) { using (DbConnection conn = GetDBConn(_server, _m, _db, _i, _user, _psw)) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = @"select tc.table_schema,tc.table_name,cc.column_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on tc.constraint_name = rc.unique_constraint_name join INFORMATION_SCHEMA.constraint_column_usage cc on tc.table_name = cc.table_name and tc.table_schema = cc.table_schema and tc.constraint_name = cc.constraint_name where rc.constraint_name = @cn" ; DbParameter cn = cmd.CreateParameter(); cn.ParameterName = "cn"; cn.Value = constraint; cmd.Parameters.Add(cn); conn.Open(); using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Column c = new Column(reader.GetString(reader.GetOrdinal("table_schema")), reader.GetString(reader.GetOrdinal("table_name")), reader.GetString(reader.GetOrdinal("column_name")), false, null, null, null, false); if (columns.ContainsKey(c)) { string id = "t" + Capitalize(c.Table); TypeDescription t = odef.GetType(id, true); if (t == null) { bool cr; t = new TypeDescription(id, GetEntity(odef, c.Schema, c.Table, out cr)); odef.Types.Add(t); } return(t); } } } } } return(null); }
protected TypeDescription GetType(Column c, IDictionary <Column, Column> columns, OrmObjectsDef odef) { TypeDescription t = null; if (c.ConstraintType == "FOREIGN KEY") { t = GetRelatedType(c, columns, odef); } else { t = GetClrType(c.DbType, c.IsNullable, odef); } return(t); }
protected void ProcessProhibited(Dictionary <Column, Column> columns, List <Pair <string> > prohibited, OrmObjectsDef odef) { foreach (Pair <string> p in prohibited) { TypeDescription td = GetRelatedType(p.Second, columns, odef); if (td.Entity != null) { EntityDescription ed = td.Entity; string[] ss = p.First.Split('.'); AppendColumns(columns, ed, ss[0], ss[1], p.Second); TableDescription t = GetTable(odef, ss[0], ss[1]); if (!ed.Tables.Contains(t)) { ed.Tables.Add(t); } } } }
protected void ProcessM2M(Dictionary <Column, Column> columns, OrmObjectsDef odef) { List <Pair <string> > tables = new List <Pair <string> >(); using (DbConnection conn = GetDBConn(_server, _m, _db, _i, _user, _psw)) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = @"select table_schema,table_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_type = 'FOREIGN KEY' group by table_schema,table_name having count(*) = 2" ; conn.Open(); using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { tables.Add(new Pair <string>(reader.GetString(reader.GetOrdinal("table_schema")), reader.GetString(reader.GetOrdinal("table_name")))); } } } } foreach (Pair <string> p in tables) { string underlying = GetEntityName(p.First, p.Second); EntityDescription ued = odef.GetEntity(underlying); using (DbConnection conn = GetDBConn(_server, _m, _db, _i, _user, _psw)) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = @"select cc.table_schema,cc.table_name,cc2.column_name,rc.delete_rule from INFORMATION_SCHEMA.constraint_column_usage cc join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on rc.unique_constraint_name = cc.constraint_name join INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on tc.constraint_name = rc.constraint_name join INFORMATION_SCHEMA.constraint_column_usage cc2 on cc2.constraint_name = tc.constraint_name and cc2.table_schema = tc.table_schema and cc2.table_name = tc.table_name where tc.table_name = @tbl and tc.table_schema = @schema and tc.constraint_type = 'FOREIGN KEY'" ; DbParameter tbl = cmd.CreateParameter(); tbl.ParameterName = "tbl"; tbl.Value = p.Second; cmd.Parameters.Add(tbl); DbParameter schema = cmd.CreateParameter(); schema.ParameterName = "schema"; schema.Value = p.First; cmd.Parameters.Add(schema); conn.Open(); List <LinkTarget> targets = new List <LinkTarget>(); using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { //string ename = reader.GetString(reader.GetOrdinal("table_schema")) + "." + // reader.GetString(reader.GetOrdinal("table_name")); bool deleteCascade = false; switch (reader.GetString(reader.GetOrdinal("delete_rule"))) { case "NO ACTION": break; case "CASCADE": deleteCascade = true; break; default: throw new NotSupportedException("Cascade " + reader.GetString(reader.GetOrdinal("delete_rule")) + " is not supported"); } bool c; LinkTarget lt = new LinkTarget( GetEntity(odef, reader.GetString(reader.GetOrdinal("table_schema")), reader.GetString(reader.GetOrdinal("table_name")), out c), reader.GetString(reader.GetOrdinal("column_name")), deleteCascade); targets.Add(lt); } } RelationDescription rd = odef.GetSimilarRelation( new RelationDescription(targets[0], targets[1], null, null)); if (rd == null) { rd = new RelationDescription(targets[0], targets[1], GetTable(odef, p.First, p.Second), ued); odef.Relations.Add(rd); } } } } }
protected void ProcessColumns(Dictionary <Column, Column> columns, string file, string merge, bool dropColumns, string name_space, List <Pair <string> > prohibited) { OrmObjectsDef odef = null; if (File.Exists(file)) { if (merge == "error") { throw new InvalidOperationException("The file " + file + " is already exists."); } odef = OrmObjectsDef.LoadFromXml(new System.Xml.XmlTextReader(file)); } else { odef = new OrmObjectsDef(); odef.Namespace = name_space; odef.SchemaVersion = "1"; } foreach (Column c in columns.Keys) { bool ent, col; EntityDescription e = GetEntity(odef, c.Schema, c.Table, out ent); PropertyDescription pd = AppendColumn(columns, c, e, out col); if (ent) { Console.WriteLine("Create class {0} ({1})", e.Name, e.Identifier); _ents.Add(e.Identifier, null); } else if (col) { if (!_ents.ContainsKey(e.Identifier)) { Console.WriteLine("Alter class {0} ({1})", e.Name, e.Identifier); _ents.Add(e.Identifier, null); } Console.WriteLine("\tAdd property: " + pd.Name); } } ProcessProhibited(columns, prohibited, odef); ProcessM2M(columns, odef); if (dropColumns) { foreach (EntityDescription ed in odef.Entities) { List <PropertyDescription> col2remove = new List <PropertyDescription>(); foreach (PropertyDescription pd in ed.Properties) { string[] ss = ed.Tables[0].Name.Split('.'); Column c = new Column(ss[0].Trim(new char[] { '[', ']' }), ss[1].Trim(new char[] { '[', ']' }), pd.FieldName.Trim(new char[] { '[', ']' }), false, null, null, null, false); if (!columns.ContainsKey(c)) { col2remove.Add(pd); } } foreach (PropertyDescription pd in col2remove) { ed.Properties.Remove(pd); Console.WriteLine("Remove: {0}.{1}", ed.Name, pd.Name); } } } using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(file, System.Text.Encoding.UTF8)) { writer.Formatting = System.Xml.Formatting.Indented; odef.GetXmlDocument().Save(writer); } }
public EntityDescription(string id, string name, string nameSpace, string description, OrmObjectsDef ormObjectsDef, EntityDescription baseEntity) : this(id, name, nameSpace, description, ormObjectsDef, baseEntity, EntityBehaviuor.Default) { }
public EntityDescription(string id, string name, string nameSpace, string description, OrmObjectsDef ormObjectsDef) : this(id, name, nameSpace, description, ormObjectsDef, null) { }