[Adapdev-commits] Adapdev/src/Adapdev.Data/Schema AbstractSchemaBuilder.cs,1.2,1.3 AssociationType.c
Status: Beta
Brought to you by:
intesar66
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Schema In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data/Schema Added Files: AbstractSchemaBuilder.cs AssociationType.cs ColumnSchema.cs ColumnSchemaCollection.cs ColumnSchemaDictionary.cs ColumnSchemaEnumerator.cs CompareDatabaseSchemas.cs DatabaseSchema.cs ForeignKeyAssociation.cs ISchemaBuilder.cs LoadDatabaseSchema.cs MySqlSchemaBuilder.cs OleDbSchemaBuilder.cs ParameterSchema.cs ParameterSchemaDictionary.cs ProcedureInfo.cs ProcedureSchema.cs SaveDatabaseSchema.cs SchemaBuilder.cs SchemaConstants.cs TableSchema.cs TableSchemaCollection.cs TableSchemaDictionary.cs TableSchemaEnumerator.cs TableType.cs TableTypeConverter.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: TableType.cs --- namespace Adapdev.Data.Schema { /// <summary> /// The type of table /// </summary> public enum TableType { /// <summary> /// A system view table /// </summary> SYSTEM_VIEW, /// <summary> /// A system table /// </summary> SYSTEM_TABLE, /// <summary> /// A table /// </summary> TABLE, /// <summary> /// A view table /// </summary> VIEW, /// <summary> /// A alias to a Table /// </summary> SYNONYM } } --- NEW FILE: ParameterSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; /// <summary> /// Summary description for CacheMetaDataDictionary. /// </summary> /// [Serializable] public class ParameterSchemaDictionary : DictionaryBase { public ParameterSchema this[String key] { get { return ((ParameterSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, ParameterSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (ParameterSchema ci in this.Values) { sb.Append(ci.ToString()); } return sb.ToString(); } } } --- NEW FILE: ParameterSchema.cs --- namespace Adapdev.Data.Schema { /// <summary> /// Summary description for ParameterSchema. /// </summary> public class ParameterSchema { public string Name; public int Ordinal; public int DataTypeId; public bool HasDefault; public object Default; public bool AllowNulls; public int MaxLength; public string Description; public string DataTypeName; } } --- NEW FILE: CompareDatabaseSchemas.cs --- using System; namespace Adapdev.Data.Schema { using System.Reflection; using Adapdev.Attributes; /// <summary> /// Summary description for CompareSchemasCommand. /// </summary> public class CompareDatabaseSchemas { private DatabaseSchema _databaseSchema; private DatabaseSchema _savedDatabaseSchema; public CompareDatabaseSchemas(DatabaseSchema databaseSchema, DatabaseSchema savedDatabaseSchema) { this._databaseSchema = databaseSchema; this._savedDatabaseSchema = savedDatabaseSchema; } /// <summary> /// Compare the saved Schema and the database Schema by iterating through the DatabaseSchema's tables /// </summary> /// <returns>DatabaseSchema - the updated DatabaseSchema</returns> public DatabaseSchema Compare() { foreach(TableSchema table in _databaseSchema.SortedTables.Values) { //If the table exists check it otherwise add the table if(null != this._savedDatabaseSchema.GetTable(table.Name)) { foreach (PropertyInfo property in table.GetType().GetProperties()) { foreach (object attribute in property.GetCustomAttributes(typeof(SchemaDataRewritableAttribute),true)) { if(isRewritable(attribute, property)) { rewritePropertyForTable(table, property); } } } findAndUpdateColumns(table); } else { this._savedDatabaseSchema.AddTable(table); } } return _savedDatabaseSchema; } /// <summary> /// Iterate through the ColumnSchema's for a TableSchema and update properties that are rewritable from the Database Schema /// </summary> /// <param name="table">TableSchema table that we will check it's ColumnSchema's</param> private void findAndUpdateColumns(TableSchema table) { foreach(ColumnSchema column in table.SortedColumns.Values) { //If the column exists check it otherwise add the column if(null != this._savedDatabaseSchema.GetTable(table.Name).GetColumn(column.Name)) { foreach (PropertyInfo property in column.GetType().GetProperties()) { foreach(object attribute in property.GetCustomAttributes(typeof(SchemaDataRewritableAttribute),true)) { if(isRewritable(attribute,property)) { rewritePropertyForColumn(table,column,property); } } } } else { this._savedDatabaseSchema.GetTable(table.Name).AddColumn(column); } } } /// <summary> /// Rewrite the TableSchema proprety to match that from the Database /// </summary> /// <param name="tableToUpdateFrom">TableSchema object that we will use to update from</param> /// <param name="property">PropertyInfo</param> private void rewritePropertyForTable(TableSchema tableToUpdateFrom, PropertyInfo property) { TableSchema tableToUpdate = this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name); PropertyInfo tablePropertyToUpdate = tableToUpdate.GetType().GetProperty(property.Name); tablePropertyToUpdate.SetValue(this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name), property.GetValue(tableToUpdateFrom,null),null); } /// <summary> /// Rewrite the ColumnSchema proprety to match that from the Database /// </summary> /// <param name="tableToUpdateFrom">TableSchema object that we will use to update from</param> /// <param name="columnToUpdateFrom">ColumnSchema object that we will use to update from</param> /// <param name="property">PropertyInfo</param> private void rewritePropertyForColumn(TableSchema tableToUpdateFrom, ColumnSchema columnToUpdateFrom, PropertyInfo property) { ColumnSchema columnToUpdate = this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name).GetColumn(columnToUpdateFrom.Name); PropertyInfo columnPropertyToUpdate = columnToUpdate.GetType().GetProperty(property.Name); columnPropertyToUpdate.SetValue(columnToUpdate, property.GetValue(columnToUpdateFrom, null),null); } /// <summary> /// Is the SchemaDataRewritableAttribute set to update. /// </summary> /// <param name="attribute">The custom attribute for the property</param> /// <param name="property">The Schema PropertyInfo</param> /// <returns>bool</returns> private bool isRewritable(object attribute,PropertyInfo property) { return ((SchemaDataRewritableAttribute) attribute).Rewrite && property.CanWrite; } } } --- NEW FILE: ISchemaBuilder.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for ISchemaBuilder. /// </summary> internal interface ISchemaBuilder { DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType, string schemaFilter); } } --- NEW FILE: AbstractSchemaBuilder.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for AbstractSchemaBuilder. /// </summary> public abstract class AbstractSchemaBuilder : ISchemaBuilder { #region ISchemaBuilder Members public abstract DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter); public static bool EndProgress (Adapdev.IProgressCallback _callback, string message, bool ok) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message,""); _callback.SetRange(0, 1); if (ok) { _callback.StepTo(1); } else { _callback.StepTo(0); _callback.AddMessage(ProgressMessageTypes.Critical,"No database schema information found."); } } return true; } public static bool IncrProgress(Adapdev.IProgressCallback _callback, string message, ref int count) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message); _callback.StepTo(count++); } return true; } public static bool StartProgress (Adapdev.IProgressCallback _callback, string message, int max, ref int stepto) { if (max > 0) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message,""); _callback.SetRange(0, max); _callback.StepTo(stepto = 0); } } return true; } #endregion } } --- NEW FILE: MySqlSchemaBuilder.cs --- using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data.Sql; using MySql.Data.MySqlClient; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for MySqlSchemaBuilder. /// </summary> public class MySqlSchemaBuilder : AbstractSchemaBuilder { private Adapdev.Data.DbProviderType dbProviderType = DbProviderType.MYSQL; private Adapdev.IProgressCallback _callback = null; private int recordCount = 0; public MySqlSchemaBuilder(Adapdev.IProgressCallback callback, ref int recordCount) { this._callback = callback; this.recordCount = recordCount; } public override DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter) { return this.CreateMySqlDatabaseSchema(connectionString); } private DatabaseSchema CreateMySqlDatabaseSchema(string connectionString) { DataTable schemaTables = this.GetMySqlSchema(connectionString); DatabaseSchema di = new DatabaseSchema(); MySqlConnection c = new MySqlConnection(connectionString); di.Name = c.Database; c = null; foreach (DataRow dr in schemaTables.Rows) { TableSchema ti = CreateMySqlTableSchema(dr); CreateColumnSchemas(ti, connectionString, Adapdev.Data.DbType.MYSQL); DataTable columns = this.GetMySqlColumnSchema(connectionString, ti.Name); foreach(DataRow columnRow in columns.Rows) { if (columnRow["Key"] + "" == "PRI") { ti[columnRow["Field"].ToString()].IsPrimaryKey = true; } else if (columnRow["Key"] + "" == "MUL") { ti[columnRow["Field"].ToString()].IsForeignKey = true; } } di.AddTable(ti); } return di; } /// <summary> /// Creates the ColumnSchemas for a specified table /// </summary> /// <param name="ts">The TableSchema to add the ColumnSchema to</param> /// <param name="connectionString">The OleDb connectionstring to use</param> private void CreateColumnSchemas(TableSchema ts, string connectionString, Adapdev.Data.DbType databaseType) { DataTable dt = this.GetReaderSchema(connectionString, ts.Name, databaseType); if (!(dt == null)) { foreach (DataRow dr in dt.Rows) { ColumnSchema ci = new ColumnSchema(); ci.Alias = (string) dr["ColumnName"]; ci.AllowNulls = (bool) dr["AllowDBNull"]; ci.DataTypeId = (int) dr["ProviderType"]; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(this.dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); ci.IsAutoIncrement = (bool) dr["IsAutoIncrement"]; ci.IsForeignKey = false; ci.IsPrimaryKey = false; ci.IsUnique = (bool) dr["IsUnique"]; ci.Length = (int) dr["ColumnSize"]; ci.Name = (string) dr["ColumnName"]; ci.NetType = dr["DataType"].ToString(); ci.Ordinal = (int) dr["ColumnOrdinal"]; ci.IsReadOnly = (bool) dr["IsReadOnly"]; // hack because MySql has the same provider type for // strings and blobs, which results in blob // default and test values being incorrectly assigned to // string columns if((ci.DataTypeId == 252 && ci.NetType.Equals("System.String")) || ci.DataTypeId == 254) { ci.DataTypeId = 253; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(this.dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); } ts.AddColumn(ci); } } } /// <summary> /// Gets the OleDbDataReader.GetSchemaTable() for a specified database table /// </summary> /// <param name="oledbConnectionString">The connection string to use</param> /// <param name="tableName">The table to grab the schema for</param> /// <returns></returns> private DataTable GetReaderSchema(string oledbConnectionString, string tableName, Adapdev.Data.DbType databaseType) { return GetReaderSchema(new MySqlConnection(), new MySqlCommand(), oledbConnectionString, databaseType, tableName); } private DataTable GetReaderSchema(IDbConnection cn, IDbCommand cmd, string connectionString, Adapdev.Data.DbType databaseType, string tableName) { DataTable schemaTable = null; try { cn.ConnectionString = connectionString; cn.Open(); // Please Note: Use the GetPre and GetPostDelimiters here as in the case of // Oracle using [ ] around a Column Name is not valid. cmd.Connection = cn; cmd.CommandText = "SELECT * FROM " + QueryHelper.GetPreDelimeter(databaseType) + tableName + QueryHelper.GetPostDelimeter(databaseType); IDataReader myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly); schemaTable = myReader.GetSchemaTable(); myReader.Close(); cn.Close(); } catch (Exception ex) { schemaTable = null; if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Warning, "Could not load Column information for " + tableName + ". " + ex.Message); } return schemaTable; } private TableSchema CreateMySqlTableSchema(DataRow dr) { TableSchema ti = new TableSchema(); ti.Alias = dr[0].ToString(); ti.Name = ti.Alias; ti.TableType = TableType.TABLE; return ti; } private DataTable GetMySqlColumnSchema(string connectionString, string tableName) { DataTable schemaTable = new DataTable(); MySqlConnection cn = new MySqlConnection(); MySqlCommand cmd = new MySqlCommand(); MySqlDataAdapter da = new MySqlDataAdapter(); cn.ConnectionString = connectionString; cn.Open(); cmd.Connection = cn; cmd.CommandText = "SHOW COLUMNS IN " + tableName; da.SelectCommand = cmd; da.Fill(schemaTable); cn.Close(); return schemaTable; } /// <summary> /// Gets the OleDbConnection.GetOleDbSchemaTable for a specified connection /// </summary> /// <param name="mysqlConnectionString">The connection to use</param> /// <returns></returns> private DataTable GetMySqlSchema(string mysqlConnectionString) { MySqlConnection conn = new MySqlConnection(mysqlConnectionString); conn.Open(); MySqlCommand command = new MySqlCommand("SHOW TABLES", conn); DataTable tbl = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(command); da.Fill(tbl); conn.Close(); return tbl; } public string PrintReaderSchema(string connectionString, string table) { StringBuilder sb = new StringBuilder(); DataTable schemaTable; schemaTable = this.GetReaderSchema(connectionString, table, Adapdev.Data.DbType.MYSQL); sb.Append("\r\n=========== " + table + " Schema =====================\r\n\r\n"); foreach (DataRow myField in schemaTable.Rows) { foreach (DataColumn myProperty in schemaTable.Columns) { sb.Append(myProperty.ColumnName + " : " + myField[myProperty].ToString() + "\r\n"); } sb.Append("\r\n"); } sb.Append("\r\n\r\n"); return sb.ToString(); } } } --- NEW FILE: ColumnSchemaEnumerator.cs --- using System; using System.Collections; namespace Adapdev.Data.Schema { public class ColumnSchemaEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public ColumnSchemaEnumerator(ColumnSchemaCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public ColumnSchemaEnumerator(ColumnSchemaDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public ColumnSchema Current { get { return ((ColumnSchema)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: ForeignKeyAssociation.cs --- using System; namespace Adapdev.Data.Schema { using Adapdev.Text; /// <summary> /// Summary description for ForeignKeyAssociation. /// </summary> public class ForeignKeyAssociation { private ColumnSchema _foreignColumn = null; private TableSchema _foreignTable = null; private ColumnSchema _columnSchema = null; private AssociationType _association = AssociationType.OneToMany; public ColumnSchema ForeignColumn { get { return _foreignColumn; } set { _foreignColumn = value; } } public string ForeignColumnName { get{return this._foreignColumn.Name;} } public ColumnSchema Column { get { return _columnSchema; } set { _columnSchema = value; } } public string ColumnName { get{return this._columnSchema.Name;} } public TableSchema ForeignTable { get { return _foreignTable; } set { _foreignTable = value; } } public string ForeignTableName { get{return this._foreignTable.Name;} } public string ForeignKeyName { get{return this.ColumnName + "-" + this.ForeignTableName + "." + this.ForeignColumnName;} } public AssociationType AssociationType { get { return _association; } set { _association = value; } } public ForeignKeyAssociation(ColumnSchema columnSchema, ColumnSchema foreignColumn, TableSchema foreignTable) { this._columnSchema = columnSchema; this._foreignColumn = foreignColumn; this._foreignTable = foreignTable; } public override string ToString() { return StringUtil.ToString(this); } } } --- NEW FILE: ProcedureSchema.cs --- namespace Adapdev.Data.Schema { /// <summary> /// Represents the schema for a database procedure /// </summary> public class ProcedureSchema { protected ParameterSchemaDictionary parameters = new ParameterSchemaDictionary(); /// <summary> /// The name of the procedure /// </summary> public string Name; /// <summary> /// Adds a ParameterSchema /// </summary> /// <param name="p"></param> public void AddParameter(ParameterSchema p) { parameters[p.Name] = p; } /// <summary> /// Removes a ParameterSchema /// </summary> /// <param name="name">The name of the ParameterSchema to remove</param> public void RemoveParameter(string name) { parameters.Remove(name); } /// <summary> /// Retrieves a ParameterSchema /// </summary> /// <param name="name">The name of the ParameterSchema to retrieve</param> /// <returns></returns> public ParameterSchema GetParameter(string name) { return parameters[name]; } /// <summary> /// Returns a collection of parameters /// </summary> /// <returns></returns> public ParameterSchemaDictionary Parameters { get{return parameters;} set{this.parameters = value;} } } } --- NEW FILE: ColumnSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; using System.Xml.Serialization; /// <summary> /// Strongly-typed collection for ColumnSchemas /// </summary> /// [Serializable] public class ColumnSchemaDictionary : DictionaryBase, IXmlSerializable { private const string nameSpace = ""; private const string columnDictionaryElement = "ColumnDictionary"; public ColumnSchema this[String key] { get { return ((ColumnSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, ColumnSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (ColumnSchema ci in this.Values) { sb.Append(ci.ToString()); } return sb.ToString(); } #region IXmlSerializable Members /// <summary> /// XmlWriter that is used to write the ColumnSchemaDictionary as it implements IDictory that is not serializable /// using the normal methods. This uses the interface IXmlSerializable which isn't offically supported but still /// exists in the next framework /// </summary> /// <param name="writer">System.Xml.XmlWriter</param> public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(ColumnSchema)); writer.WriteStartElement(columnDictionaryElement, nameSpace); foreach(object key in Dictionary.Keys) { writer.WriteStartElement("key", nameSpace); keySer.Serialize(writer,key); writer.WriteEndElement(); writer.WriteStartElement("value", nameSpace); object value = Dictionary[key]; valueSer.Serialize(writer, value); writer.WriteEndElement(); } writer.WriteEndElement(); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Custom XmlReader to read the ColumnSchemaDictionary /// </summary> /// <param name="reader">System.Xml.XmlReader</param> public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(ColumnSchema)); reader.Read(); reader.ReadStartElement(columnDictionaryElement, nameSpace); while(reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("key", nameSpace); object key = keySer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value", nameSpace); object value = valueSer.Deserialize(reader); reader.ReadEndElement(); Dictionary.Add(key, value); reader.MoveToContent(); } reader.ReadEndElement(); } #endregion } } --- NEW FILE: TableSchemaEnumerator.cs --- using System; using System.Collections; namespace Adapdev.Data.Schema { public class TableSchemaEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public TableSchemaEnumerator(TableSchemaCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public TableSchemaEnumerator(TableSchemaDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public TableSchema Current { get { return ((TableSchema)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: LoadDatabaseSchema.cs --- using System; namespace Adapdev.Data.Schema { using System.Collections; using System.IO; using System.Xml.Serialization; /// <summary> /// Summary description for LoadDatabaseSchema. /// </summary> public class LoadDatabaseSchema { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private DatabaseSchema _dbSchema; private String schemaFile; private String _savedSchemaName; public LoadDatabaseSchema(String savedSchemaName, DatabaseSchema dbSchema) { this._savedSchemaName = savedSchemaName; this._dbSchema = dbSchema; } public DatabaseSchema Load() { schemaFile = System.IO.Path.Combine(SchemaConstants.SCHEMAPATH,this._savedSchemaName); if(File.Exists(schemaFile)) { XmlSerializer dbSerializer = new XmlSerializer(typeof(DatabaseSchema)); FileStream dbStream = new FileStream(schemaFile, FileMode.Open); _dbSchema = (DatabaseSchema) dbSerializer.Deserialize(dbStream); dbStream.Close(); } return _dbSchema; } } } --- NEW FILE: SchemaConstants.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for Constants Associated with the Schema /// </summary> public class SchemaConstants { public static readonly string SCHEMAPATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData); } } --- NEW FILE: AssociationType.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for AssociationType. /// </summary> public enum AssociationType { OneToOne, OneToMany, ManyToMany, ManyToOne } } --- NEW FILE: DatabaseSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using Adapdev.Text; /// <summary> /// Represents the schema for a database /// </summary> /// [Serializable] [XmlRoot("DatabaseSchema")] public class DatabaseSchema { protected TableSchemaDictionary tables = new TableSchemaDictionary(); protected string name = String.Empty; protected string connectionString = String.Empty; protected DbType databaseType = DbType.SQLSERVER; protected DbProviderType databaseProviderType = DbProviderType.SQLSERVER; /// <summary> /// Constructor /// </summary> public DatabaseSchema() { } /// <summary> /// Constructor /// </summary> /// <param name="name">The name of the database</param> public DatabaseSchema(string name) { this.Name = name; } /// <summary> /// The database name /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// The database connectionstring /// </summary> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// The database type /// </summary> public DbType DatabaseType { get { return this.databaseType; } set { this.databaseType = value; } } /// <summary> /// The database provider type /// </summary> public DbProviderType DatabaseProviderType { get { return this.databaseProviderType; } set { this.databaseProviderType = value; } } /// <summary> /// Adds the specified table schema to the database /// </summary> /// <param name="table">The TableSchema to add</param> public void AddTable(TableSchema table) { tables[table.Name] = table; } /// <summary> /// Gets the specified table schema /// </summary> /// <param name="name">The name of the TableSchema to retrieve</param> /// <returns>TableSchema</returns> public TableSchema GetTable(string name) { return tables[name]; } /// <summary> /// Indexer to retrieve a TableSchema /// </summary> public TableSchema this[String key] { get { return (tables[key]); } set { tables[key] = value; } } /// <summary> /// Returns a dictionary of the database's TableSchemas /// </summary> /// <returns></returns> public TableSchemaDictionary Tables { get{return this.tables;} set{this.tables = value;} } /// <summary> /// Returnes a SortedList of TableSchemas, sorted by the table names /// </summary> /// <returns>SortedList</returns> public SortedList SortedTables { get { SortedList sl = new SortedList(); foreach (TableSchema t in this.tables.Values) { sl.Add(t.Name, t); } return sl; } } public override string ToString() { return Environment.NewLine + StringUtil.ToString(this) + Environment.NewLine + this.Tables.ToString(); } } } --- NEW FILE: TableSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Xml.Serialization; using Adapdev.Attributes; using Adapdev.Text; /// <summary> /// Represents the schema for a database table /// </summary> [Serializable] public class TableSchema { protected TableType tableType = TableType.TABLE; protected bool _active = true; protected string _name = String.Empty; protected string _alias = String.Empty; protected ColumnSchemaDictionary columns = new ColumnSchemaDictionary(); protected DatabaseSchema parent = null; /// <summary> /// Property TableType (TableType) /// </summary> public TableType TableType { get { return this.tableType; } set { this.tableType = value; } } /// <summary> /// Adds the specified ColumnSchema /// </summary> /// <param name="c"></param> public void AddColumn(ColumnSchema c) { this.columns[c.Name] = c; } /// <summary> /// Removes the specified ColumnSchema /// </summary> /// <param name="name">The name of the ColumnSchema to remove</param> public void RemoveColumn(string name) { this.columns.Remove(name); } /// <summary> /// Retrieves the specified ColumnSchema /// </summary> /// <param name="name">The name of the ColumnSchema to retrieve</param> /// <returns></returns> public ColumnSchema GetColumn(string name) { return this.columns[name]; } /// <summary> /// Indexer to retrieve a ColumnSchema by name /// </summary> public ColumnSchema this[String key] { get { return (columns[key]); } set { columns[key] = value; } } /// <summary> /// Gets the number of primary keys /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public int PrimaryKeyCount { get { int i = 0; foreach (ColumnSchema c in columns.Values) { if(c.IsPrimaryKey)i++; } return i; } } /// <summary> /// Gets the number of foreign keys /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public int ForeignKeyCount { get { int i = 0; foreach (ColumnSchema c in columns.Values) { if(c.IsForeignKey)i++; } return i; } } /// <summary> /// Gets the specified primary key Column Schema by index. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <remarks> /// If a database table contains two primary keys, then index 0 would retrieve /// the first, and index 1 would be the second. The index is in relation /// to the number of primary keys, not the total number of columns /// </remarks> public ColumnSchema GetPrimaryKey(int index) { ArrayList al = new ArrayList(this.PrimaryKeys.Values); return ((ColumnSchema) al[index]); } /// <summary> /// Gets the specified primary key Column Schema by index. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <remarks> /// If a database table contains two foreign keys, then index 0 would retrieve /// the first, and index 1 would be the second. The index is in relation /// to the number of foreign keys, not the total number of columns /// </remarks> public ColumnSchema GetForeignKey(int index) { ArrayList al = new ArrayList(this.ForeignKeys.Values); return ((ColumnSchema) al[index]); } /// <summary> /// Returns the list of ColumnSchemas, sorted by their ordinal representation /// </summary> /// <returns></returns> [XmlIgnore] public SortedList OrdinalColumns { get { SortedList sl = new SortedList(); foreach (ColumnSchema c in this.columns.Values) { sl[c.Ordinal] = c; } return sl; } } /// <summary> /// Returns the list of ColumnSchemas, sorted by their names /// </summary> /// <returns></returns> [XmlIgnore] public SortedList SortedColumns { get { SortedList sl = new SortedList(); foreach (ColumnSchema c in this.columns.Values) { sl.Add(c.Name, c); } return sl; } } /// <summary> /// Returns the table name in proper case, with all spaces removed /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public string ProperName { get{return StringUtil.ToTrimmedProperCase(this.Name);} } /// <summary> /// Specifies whether the table is active. Used primarily /// for on/off state in GUIs. It allows for a table to still /// be part of a DatabaseSchema, but ignored for various reasons /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool IsActive { get { return this._active; } set { this._active = value; } } /// <summary> /// The table name /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(true)] public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// The table alias /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public string Alias { get { if(this._alias.Length == 0 || this._alias == this._name) return this.ProperName; else return this._alias; } set { this._alias = value; } } [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool HasForeignKeys { get { if(this.ForeignKeyCount > 0) return true; else return false; } } [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool HasPrimaryKeys { get { if(this.PrimaryKeyCount > 0) return true; else return false; } } /// <summary> /// Returns a collection of ColumnSchemas /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "Columns")] public ColumnSchemaDictionary Columns { get{return this.columns;} set{this.columns = value;} } /// <summary> /// Returns a collection of ColumnSchemas that are primary keys /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "PrimaryKeys")] public ColumnSchemaDictionary PrimaryKeys { get { ColumnSchemaDictionary pks = new ColumnSchemaDictionary(); foreach(ColumnSchema c in this.columns.Values) { if(c.IsPrimaryKey)pks[c.Name] = c; } return pks; } } /// <summary> /// Returns a collection of ColumnSchemas that are foreign keys /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "ForeignKeys")] public ColumnSchemaDictionary ForeignKeys { get { ColumnSchemaDictionary fks = new ColumnSchemaDictionary(); foreach(ColumnSchema c in this.columns.Values) { if(c.IsForeignKey)fks[c.Name] = c; } return fks; } } public override string ToString() { return Environment.NewLine + StringUtil.ToString(this) + Environment.NewLine + this.Columns.ToString(); } } } --- NEW FILE: TableTypeConverter.cs --- namespace Adapdev.Data.Schema { using System; /// <summary> /// Converts the string representation of a table type to a TableType enum /// </summary> public class TableTypeConverter { private TableTypeConverter() { } /// <summary> /// Converts the string representation of a table type to a TableType enum /// </summary> /// <param name="tableType">The string representation to convert</param> /// <returns></returns> public static TableType Convert(string tableType) { switch (tableType.ToUpper(new System.Globalization.CultureInfo("en-US"))) { case "SYSTEM TABLE": case "ACCESS TABLE": return TableType.SYSTEM_TABLE; case "SYSTEM VIEW": return TableType.SYSTEM_VIEW; case "TABLE": return TableType.TABLE; case "VIEW": return TableType.VIEW; case "SYNONYM": return TableType.SYNONYM; default: throw new Exception("TableType " + tableType + " is not supported."); } } } } --- NEW FILE: OleDbSchemaBuilder.cs --- using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data.Sql; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for OleDbSchemaBuilder. /// </summary> public class OleDbSchemaBuilder : AbstractSchemaBuilder { private Adapdev.IProgressCallback _callback = null; private Adapdev.Data.DbProviderType dbProviderType = DbProviderType.OLEDB; private int recordCount = 0; public OleDbSchemaBuilder(Adapdev.IProgressCallback callback, ref int recordCount) { this._callback = callback; this.recordCount = recordCount; } public override DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter) { DataTable schemaTables = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Tables, "",schemaFilter,"",""); DatabaseSchema di = new DatabaseSchema(); di.DatabaseProviderType = providerType; di.DatabaseType = databaseType; this.dbProviderType = providerType; if (schemaTables != null) { if (schemaTables.Rows.Count > 0) { //TODO: Note sure if this is valid. It does not work for Oracle DB's di.Name = schemaTables.Rows[0]["TABLE_CATALOG"].ToString(); if (di.Name == String.Empty) di.Name = "Unknown"; // Build the base schema information if (!StartProgress(_callback, "Building Table Details",schemaTables.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in schemaTables.Rows) { TableType tableType = TableTypeConverter.Convert(dr["TABLE_TYPE"].ToString()); if (tableType == TableType.TABLE || tableType == TableType.VIEW) { if (!IncrProgress(_callback, dr["TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema ti = CreateTableSchema(dr); CreateColumnSchemas(ti, connectionString, databaseType); if(ti.Columns.Count > 0) di.AddTable(ti); } } // Get the primary key information DataTable pkeys = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Primary_Keys, "",schemaFilter,"",""); if (pkeys != null) { if (!StartProgress(_callback, "Building Primary Key Details",pkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in pkeys.Rows) { string pkTable = dr["TABLE_NAME"].ToString(); if (!IncrProgress(_callback, dr["TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema tip = di[pkTable]; if (tip != null) { ColumnSchema ci = tip[dr["COLUMN_NAME"].ToString()]; if (ci != null) { ci.IsPrimaryKey = true; tip.AddColumn(ci); } } } } // Get the foreign key information DataTable fkeys = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Foreign_Keys, "",schemaFilter,"",""); if (fkeys != null) { if (!StartProgress(_callback, "Building Foreign Key Details",fkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in fkeys.Rows) { string fkTable = dr["FK_TABLE_NAME"].ToString(); if (!IncrProgress(_callback, dr["FK_TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema tif = di[fkTable]; if (tif != null) { ColumnSchema ci = tif[dr["FK_COLUMN_NAME"].ToString()]; if (ci != null) { ci.IsForeignKey = true; tif.AddColumn(ci); } } } } // Setup the Progress Display if one is defined. if (fkeys != null) { if (!StartProgress(_callback, "Building Foreign Key Relationships",fkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in fkeys.Rows) { if (!IncrProgress(_callback, dr["PK_TABLE_NAME"].ToString(), ref recordCount)) return null; // Get the name of the primary key table string pkTable = dr["PK_TABLE_NAME"].ToString(); // Get the name of the foreign key table string fkTable = dr["FK_TABLE_NAME"].ToString(); // Get the name of the foreign key column string fkColumn = dr["FK_COLUMN_NAME"].ToString(); // Get the table containing the primary key TableSchema tif = di[pkTable]; // Get the table containing the foreign key TableSchema fk = di[fkTable]; if (tif != null) { // Get the primary key ColumnSchema ci = tif[dr["PK_COLUMN_NAME"].ToString()]; // Get the foreign key ColumnSchema cf = fk[fkColumn]; if (ci != null) { // Add the association to the table and column containing the foreign key ci.ForeignKeyTables.Add(new ForeignKeyAssociation(ci, cf ,fk)); } } } } if (!EndProgress(_callback, "Finished Loading Tables",true)) return null; } else { if (!EndProgress(_callback, "No database schema information found.",false)) return null; } } else { if (!EndProgress(_callback, "No database schema information found.",false)) return null; } return di; } private TableSchema CreateTableSchema(DataRow dr) { TableSchema ti = new TableSchema(); ti.Alias = dr["TABLE_NAME"].ToString(); ti.Name = dr["TABLE_NAME"].ToString(); ti.TableType = TableTypeConverter.Convert(dr["TABLE_TYPE"].ToString()); return ti; } /// <summary> /// Creates the ColumnSchemas for a specified table /// </summary> /// <param name="ts">The TableSchema to add the ColumnSchema to</param> /// <param name="oledbConnectionString">The OleDb connectionstring to use</param> public void CreateColumnSchemas(TableSchema ts, string oledbConnectionString, Adapdev.Data.DbType databaseType) { DataTable dt = this.GetReaderSchema(oledbConnectionString, ts.Name, databaseType); if (!(dt == null)) { foreach (DataRow dr in dt.Rows) { ColumnSchema ci = new ColumnSchema(); ci.Alias = (string) dr["ColumnName"]; ci.AllowNulls = (bool) dr["AllowDBNull"]; ci.DataTypeId = (int) dr["ProviderType"]; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); ci.IsAutoIncrement = (bool) dr["IsAutoIncrement"]; ci.IsForeignKey = false; ci.IsPrimaryKey = false; ci.IsUnique = (bool) dr["IsUnique"]; ci.Length = (int) dr["ColumnSize"]; ci.Name = (string) dr["ColumnName"]; ci.NetType = dr["DataType"].ToString(); ci.Ordinal = (int) dr["ColumnOrdinal"]; ci.IsReadOnly = (bool) dr["IsReadOnly"]; ts.AddColumn(ci); } } } /// <summary> /// Gets the OLE db schema. /// </summary> /// <param name="oledbConnectionString">Oledb connection string.</param> /// <param name="guid">GUID.</param> /// <param name="filterCatalog">Filter catalog.</param> /// <param name="filterSchema">Filter schema.</param> /// <param name="filterName">Name of the filter.</param> /// <param name="filterType">Filter type.</param> /// <returns></returns> public DataTable GetOleDbSchema(Adapdev.IProgressCallback _callback, string oledbConnectionString, Guid guid, string filterCatalog, string filterSchema, string filterName, string filterType) { DataTable schemaTable = null; OleDbConnection conn = new OleDbConnection(oledbConnectionString); conn.Open(); try { schemaTable = conn.GetOleDbSchemaTable(guid, GetFilters(guid, filterCatalog, filterSchema, filterName, filterType)); } catch (Exception ex) { if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Critical, "Error obtaining Schema Information: " + ex.Message); } conn.Close(); return schemaTable; } private static object[] GetFilters(Guid guid, string filterCatalog, string filterSchema, string filterName, string filterType) { // Different OleDbSchemaGuid's require a different number of parameters. // These parameter depend on what we are trying to retirve from the database // so this function returns the correct parameter sets. // This should be a Switch statement, but the compiler did not like it. filterCatalog = filterCatalog == string.Empty ? null : filterCatalog; filterSchema = filterSchema == string.Empty ? null : filterSchema; filterName = filterName == string.Empty ? null : filterName; filterType = filterType == string.Empty ? null : filterType; if (guid.Equals(OleDbSchemaGuid.Tables)) return new object[] {filterCatalog, filterSchema, filterName, filterType}; if (guid.Equals(OleDbSchemaGuid.Views)) return new object[] {filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Primary_Keys)) return new object[] {filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Foreign_Keys)) return new object[] {filterCatalog, filterSchema, filterName, filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Columns)) return new object[] {filterCatalog, filterSchema, filterName, string.Empty}; return null; } public StringBuilder PrintOleDbSchema(string oledbConnection, Guid guid, string filter) { StringBuilder sb = new StringBuilder(); DataTable schemaTable; schemaTable = GetOleDbSchema(null, oledbConnection, guid, "","","",filter); foreach (DataRow row in schemaTable.Rows) { foreach (DataColumn column in schemaTable.Columns) { sb.Append("\t\t" + column + " : " + row[column] + "\r\n"); } sb.Append("\r\n"); } sb.Append("\r\n\r\n"); return sb; } public DataTable GetReaderSchema(string oledbConnectionString, string tableName, Adapdev.Data.DbType databaseType) { return GetReaderSchema(new OleDbConnection(), new OleDbCommand(), oledbConnectionString, databaseType, tableName); } private DataTable GetReaderSchema(IDbConnection cn, IDbCommand cmd, string connectionString, Adapdev.Data.DbType databaseType, string tableName) { DataTable schemaTable = null; try { cn.ConnectionString = connectionString; cn.Open(); // Please Note: Use the GetPre and GetPostDelimiters here as in the case of // Oracle using [ ] around a Column Name is not valid. cmd.Connection = cn; cmd.CommandText = "SELECT * FROM " + QueryHelper.GetPreDelimeter(databaseType) + tableName + QueryHelper.GetPostDelimeter(databaseType); IDataReader myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly); schemaTable = myReader.GetSchemaTable(); myReader.Close(); cn.Close(); } catch (Exception ex) { schemaTable = null; if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Warning, "Could not load Column information for " + tableName + ". " + ex.Message); } return schemaTable; } public StringBuilder PrintOleDbSchema(string oledbConnectionString, Guid guid) { return PrintOleDbSchema(oledbConnectionString, guid, ""); } } } --- NEW FILE: SchemaBuilder.cs --- namespace Adapdev.Data.Schema { using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data; using Adapdev.Data.Sql; using MySql.Data.MySqlClient; /// <summary> /// SchemaBuilder builds the schema for a specified database /// </summary> public class SchemaBuilder { private static Adapdev.IProgressCallback _callback; /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="oledbConnectionString">The OleDb connection to use</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string oledbConnectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType) { return SchemaBuilder.CreateDatabaseSchema(oledbConnectionString, databaseType, providerType, "", null); } /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="oledbConnectionString">The OleDb connection to use</param> /// <param name="providerType">The DbProviderType to set the DatabaseSchema to</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string oledbConnectionString, string databaseType, string providerType, string schemaFilter, Adapdev.IProgressCallback progress) { return SchemaBuilder.CreateDatabaseSchema(oledbConnectionString, DbTypeConverter.Convert(databaseType), DbProviderTypeConverter.Convert(providerType), schemaFilter, progress); } /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="connectionString">The OleDb connection to use</param> /// <param name="providerType">The DbProviderType to set the DatabaseSchema to</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType, string schemaFilter, Adapdev.IProgressCallback progress) { int recordCount = 0; _callback = progress as Adapdev.IProgressCallback; if (_callback != null) { _callback.SetText("Obtaining Schema Details",""); _callback.SetAutoClose(ProgressAutoCloseTypes.WaitOnError); } DatabaseSchema ds = null; switch(providerType) { case DbProviderType.OLEDB: case DbProviderType.SQLSERVER: case DbProviderType.ORACLE: ds = new OleDbSchemaBuilder(_callback, ref recordCount).BuildDatabaseSchema(connectionString, databaseType, providerType, schemaFilter); break; case DbProviderType.MYSQL: ds = new MySqlSchemaBuilder(_callback, ref recordCount).BuildDatabaseSchema(connectionString, databaseType, providerType, schemaFilter); break; } return ds; } // public static StringBuilder PrintReaderSchema(string oledbConnectionString, string table, Adapdev.Data.DbType databaseType) // { // StringBuilder sb = new StringBuilder(); // // DataTable schemaTable; // schemaTable = SchemaBuilder.GetReaderSchema(oledbConnectionString, table, databaseType); // // sb.Append("\r\n=========== " + table + " Schema =====================\r\n\r\n"); // // foreach (DataRow myField in schemaTable.Rows) // { // foreach (DataColumn myProperty in schemaTable.Columns) // { // sb.Append(myProperty.ColumnName + " : " + myField[myProperty].ToString() + "\r\n"); // } // sb.Append("\r\n"); // } // // sb.Append("\r\n\r\n"); // return sb; // } } } --- NEW FILE: ColumnSchemaCollection.cs --- using System; using System.Collections; using Adapdev.Data.Schema; namespace Adapdev.Data.Schema { [Serializable()] public class ColumnSchemaCollection : CollectionBase { public ColumnSchemaCollection() { } public ColumnSchemaCollection(IList value) { this.AddRange(value); } public ColumnSchemaCollection(ColumnSchema[] value) { this.AddRange(value); } public ColumnSchema this[int index] { get { return ((ColumnSchema)(List[index])); } set { List[index] = value; } } public int Add(ColumnSchema value) { return List.Add(value); } public void AddRange(ColumnSchema[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((ColumnSchema)value[i]); } } public bool Contains(ColumnSchema value) { return List.Contains(value); } public void CopyTo(ColumnSchema[] array, int index) { List.CopyTo(array, index); } public int IndexOf(ColumnSchema value) { return List.IndexOf(value); } public void Insert(int index, ColumnSchema value) { List.Insert(index, value); } public new ColumnSchemaEnumerator GetEnumerator() { return new ColumnSchemaEnumerator(this); } public void Remove(ColumnSchema value) { List.Remove(value); } } } --- NEW FILE: TableSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; using System.Xml.Serialization; [Serializable] public class TableSchemaDictionary : DictionaryBase, IXmlSerializable { private const string nameSpace = ""; private const string tableDictionaryElement = "TableDictionary"; public TableSchema this[String key] { get { return ((TableSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, TableSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (TableSchema ti in this.Values) { sb.Append(ti.ToString()); } return sb.ToString(); } #region IXmlSerializable Members /// <summary> /// XmlWriter that is used to write the TableSchemaDictionary as it implements IDictory that is not serializable /// using the normal methods. This uses the interface IXmlSerializable which isn't offically supported but still /// exists in the next framework /// </summary> /// <param name="writer">System.Xml.XmlWriter</param> public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(TableSchema)); writer.WriteStartElement(tableDictionaryElement,nameSpace); foreach(object key in Dictionary.Keys){ writer.WriteStartElement("key", nameSpace); keySer.Serialize(writer,key); writer.WriteEndElement(); writer.WriteStartElement("value", nameSpace); object value = Dictionary[key]; valueSer.Serialize(writer, value); writer.WriteEndElement(); } writer.WriteEndElement(); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Custom XmlReader to read the TableSchemaDictionary /// </summary> /// <param name="reader">System.Xml.XmlReader</param> public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(TableSchema)); reader.Read(); reader.ReadStartElement(tableDictionaryElement,nameSpace); while(reader.Name != tableDictionaryElement && reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("key", nameSpace); object key = keySer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value", nameSpace); object value = valueSer.Deserialize(reader); reader.ReadEndElement(); Dictionary.Add(key, value); reader.MoveToContent(); //navigate past the end element tags to the next table do{ reader.Skip(); }while(reader.NodeType == System.Xml.XmlNodeType.EndElement && reader.Name != tableDictionaryElement); } reader.ReadEndElement(); } #endregion } } --- NEW FILE: TableSchemaCollection.cs --- using System; using System.Collections; using Adapdev.Data.Schema; namespace Adapdev.Data.Schema { using System.Text; using Adapdev.Text; [Serializable()] public class TableSchemaCollection : CollectionBase { public TableSchemaCollection() { } public TableSchemaCollection(IList value) { this.AddRange(value); } public TableSchemaCollection(TableSchema[] value) { this.AddRange(value); } public TableSchema this[int index] { get { return ((TableSchema)(List[index])); } set { List[index] = value; } } public int Add(TableSchema value) { return List.Add(value); } public void AddRange(TableSchema[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((TableSchema)value[i]); } } public bool Contains(TableSchema value) { return List.Contains(value); } public void CopyTo(TableSchema[] array, int index) { List.CopyTo(array, index); } public int IndexOf(TableSchema value) { return List.IndexOf(value); } public void Insert(int index, TableSchema value) { List.Insert(index, value); } public new TableSchemaEnumerator GetEnumerator() { return new TableSchemaEnumerator(this); } public void Remove(TableSchema value) { List.Remove(value); } } } --- NEW FILE: SaveDatabaseSchema.cs --- using System; namespace Adapdev.Data.Schema { using System.IO; using System.Xml.Serialization; /// <summary> /// Summary description for SaveDatabaseSchema. /// </summary> public class SaveDatabaseSchema { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private DatabaseSchema _dbSchema; private String schemaFile; private String _savedSchemaName; public SaveDatabaseSchema(DatabaseSchema dbSchema, String savedSchemaName) { this._dbSchema = dbSchema; this._savedSchemaName = savedSchemaName; } public void Save() { schemaFile = System.IO.Path.Combine(SchemaConstants.SCHEMAPATH,_savedSchemaName); XmlSerializer dbSerializer = new XmlSerializer(typeof(DatabaseSchema)); StreamWriter schemaWriter = new StreamWriter(schemaFile); dbSerializer.Serialize(schemaWriter, _dbSchema); schemaWriter.Close(); } } } --- NEW FILE: ColumnSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Xml.Serialization; using Adapdev.Attributes; using Adapdev.Text; /// <summary> /// Represents the schema for a column in a table /// </summary> /// [Serializable] public class ColumnSchema { private string _name = String.Empty; private string _alias = String.Empty; private int _length; private string _dataType = String.Empty; private int _dataTypeId; private string _netType = String.Empty; private bool _isForeignKey; private bool _isPrimaryKey; private bool _isAutoIncrement; private bool _isUnique; private bool _allowNulls; private bool _active = true; private int _ordinal; private bool _isReadOnly; private string _defaultValue = String.Empty; private string _defaultTestValue = String.Empty; private ArrayList _fkReferences = new ArrayList(); private TableSchema _parent = null; /// <summary> /// Specifies whether the column is readonly /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(true)] public bool IsReadOnly { get { return this._isReadOnly; } set { this._isReadOnly = value; } } /// <summary> /// Specifies whether the column is active. Used primarily /// for on/off state in GUIs. It allows for a column to still /// be part of a TableSchema, but ignored for various reasons /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool IsActive { get { return this._active; } set { this._active = value; } } ... [truncated message content] |