Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
 
Add your own
alternative version
Go to top

Implementing Model-View-Presenter in ASP.NET

, 17 Nov 2007
Three implementations of Model-View-Presenter in ASP.NET 2.0.
MVPSampleApp.zip
MVP.SampleApp
Lib
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
MySql.Data.dll
nunit.framework.dll
Rhino.Mocks.dll
Model
Data
Interfaces
Properties
Presentation
Presentation.Tests
Properties
Interfaces
Properties
SubSonic
ActiveRecord
Builder
CodeGeneration
Templates
CodeLanguage
Configuration
Controls
Calendar
lang
skin
active-bg.gif
calendar.gif
dark-bg.gif
hover-bg.gif
menuarrow.gif
normal-bg.gif
rowhover-bg.gif
status-bg.gif
title-bg.gif
today-bg.gif
Resources
DataProviders
Properties
Sql Tools
SubSonic.snk
Sugar
WebApp
App_Data
Views
SQL2000SampleDb.zip
SQL2000SampleDb.msi
using System;
using System.Collections;
using System.Configuration.Provider;
using System.Data;
using System.Data.Common;
using SubSonic.Utilities;

namespace SubSonic
{

    public class DataProviderCollection : ProviderCollection
    {
        public new DataProvider this[string name]
        {
            get { return (DataProvider)base[name]; }
        }

        public override void Add(ProviderBase provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            if (!(provider is DataProvider))
            {
                throw new ArgumentException("Invalid provider type", "provider");
            }
            base.Add(provider);
        }
    }

    public abstract class DataProvider : ProviderBase
    {
        #region props
        
        private string[] viewNames = null;
        protected string[] ViewNames
        {
            get { return viewNames; }
            set { viewNames = value; }
        }

        private string[] tableNames = null;
        protected string[] TableNames
        {
            get { return tableNames; }
            set { tableNames = value; }
        }
        
        private string _defaultConnectionString;
        public string DefaultConnectionString
        {
            get
            {
                if (String.IsNullOrEmpty(_defaultConnectionString) && !String.IsNullOrEmpty(connectionStringName))
                {
                    try
                    {
                        //_defaultConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
                        _defaultConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
                    }
                    catch
                    {
                        //swallow the exception, since the connection string will be set later possibly
                        _defaultConnectionString = "NOT SET";
                    }
                }
                return _defaultConnectionString;
            }
            set
            {
                _defaultConnectionString = value;
            }
        }

        private string _databaseVersion;
        public string DatabaseVersion
        {
            get
            {
                if (String.IsNullOrEmpty(_databaseVersion))
                {
                    _databaseVersion = GetDatabaseVersion(Name);
                }
                return _databaseVersion;
            }
        }

        public void SetDefaultConnectionString(string defaultConnectionString)
        {
            _defaultConnectionString = defaultConnectionString;
        }
        //protected string connectionString = string.Empty;
        //public string ConnectionString
        //{
        //    get { return connectionString; }
        //    set { connectionString = value; }
        //}

        private string connectionStringName;
        public string ConnectionStringName
        {
            get { return connectionStringName; }
            set { connectionStringName = value; }
        }

        private string generatedNamespace = "SubSonic.Generated";
        public string GeneratedNamespace
        {
            get { return generatedNamespace; }
            set { generatedNamespace = value; }
        }

        private bool fixPluralClassNames = true;
        public bool FixPluralClassNames
        {
            get { return fixPluralClassNames; }
            set { fixPluralClassNames = value; }
        }

        private bool setPropertyDefaultsFromDatabase = false;
        public bool SetPropertyDefaultsFromDatabase
        {
            get { return setPropertyDefaultsFromDatabase; }
            set { setPropertyDefaultsFromDatabase = value; }
        }

        private string spClassName = ClassName.STORED_PROCEDURES;
        public string SPClassName
        {
            get { return spClassName; }
            set { spClassName = value; }
        }

        private string stripTableText = string.Empty;
        public string StripTableText
        {
            get { return stripTableText; }
            set { stripTableText = value; }
        }

        private string stripSPText = string.Empty;
        public string StripSPText
        {
            get { return stripSPText; }
            set { stripSPText = value; }
        }

        private string stripViewText = string.Empty;
        public string StripViewText
        {
            get { return stripViewText; }
            set { stripViewText = value; }
        }

        private string stripColumnText = string.Empty;
        public string StripColumnText
        {
            get { return stripColumnText; }
            set { stripColumnText = value; }
        }

        private string stripParamText = string.Empty;
        public string StripParamText
        {
            get { return stripParamText; }
            set { stripParamText = value; }
        }

        private string appendWith = string.Empty;
        public string AppendWith
        {
            get { return appendWith; }
            set { appendWith = value; }
        }

        private string spStartsWith = string.Empty;
        public string SPStartsWith
        {
            get { return spStartsWith; }
            set { spStartsWith = value; }
        }

        private string viewStartsWith = string.Empty;
        public string ViewStartsWith
        {
            get { return viewStartsWith; }
            set { viewStartsWith = value; }
        }

        private string relatedTableLoadPrefix = string.Empty;
        public string RelatedTableLoadPrefix
        {
            get { return relatedTableLoadPrefix; }
            set { relatedTableLoadPrefix = value; }
        }

        private bool removeUnderscores = true;
        public bool RemoveUnderscores
        {
            get { return removeUnderscores; }
            set { removeUnderscores = value; }
        }

        private string manyToManySuffix = "_Map";
        public string ManyToManySuffix
        {
            get { return manyToManySuffix; }
            set { manyToManySuffix = value; }
        }

        private bool useSPs = true;
        public bool UseSPs
        {
            get { return useSPs; }
            set { useSPs = value; }
        }

        private string regexMatchExpression = String.Empty;
        public string RegexMatchExpression
        {
            get { return regexMatchExpression; }
            set { regexMatchExpression = value; }
        }

        private string regexReplaceExpression = String.Empty;
        public string RegexReplaceExpression
        {
            get { return regexReplaceExpression; }
            set { regexReplaceExpression = value; }
        }

        private string regexDictionaryReplace = String.Empty;
        public string RegexDictionaryReplace
        {
            get { return regexDictionaryReplace; }
            set { regexDictionaryReplace = value; }
        }

        private bool regexIgnoreCase;
        public bool RegexIgnoreCase
        {
            get { return regexIgnoreCase; }
            set { regexIgnoreCase = value; }
        }

        private string includeTableList = "*";

        public string[] IncludeTables
        {
            get
            {
                string[] result = new string[0];
                if (!String.IsNullOrEmpty(includeTableList))
                {
                    result = includeTableList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                return result;

            }
        }

        private string excludeTableList = string.Empty;

        public string[] ExcludeTables
        {
            get
            {
                string[] result = new string[0];
                if (!String.IsNullOrEmpty(excludeTableList))
                {
                    result = excludeTableList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                return result;
            }
        }

        private string includeProcedureList = "*";
        public string[] IncludeProcedures
        {
            get
            {
                string[] result = new string[0];
                if (!String.IsNullOrEmpty(includeProcedureList))
                {
                    result = includeProcedureList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                return result;
            }
        }

        /* jeff_huntsman added: support for SP exclusion list */
        private string excludeProcedureList = String.Empty;
        public string[] ExcludeProcedures
        {
            get
            {
                string[] result = new string[0];
                if (!String.IsNullOrEmpty(excludeProcedureList))
                {
                    result = excludeProcedureList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                return result;
            }
        }

        private bool generateLazyLoads;
        public bool GenerateLazyLoads
        {
            get { return generateLazyLoads; }
            set { generateLazyLoads = value; }
        }

        private bool generateRelatedTablesAsProperties;
        public bool GenerateRelatedTablesAsProperties
        {
            get { return generateRelatedTablesAsProperties; }
            set { generateRelatedTablesAsProperties = value; }
        }

        private bool extractClassNameFromSPName;
        public bool ExtractClassNameFromSPName
        {
            get { return extractClassNameFromSPName; }
            set { extractClassNameFromSPName = value; }
        }

        private bool useExtendedProperties;
        public bool UseExtendedProperties
        {
            get { return useExtendedProperties; }
            set { useExtendedProperties = value; }
        }

        private bool generateNullableProperties = true;
        public bool GenerateNullableProperties
        {
            get { return generateNullableProperties; }
            set { generateNullableProperties = value; }
        }


        private bool generateODSControllers = true;
        public bool GenerateODSControllers
        {
            get { return generateODSControllers; }
            set { generateODSControllers = value; }
        }

        public void AddSchema(string tableName, TableSchema.Table schema)
        {
            if (!this.schemaCollection.ContainsKey(tableName))
            {
                schemaCollection.Add(tableName, schema);
            }
        }
        internal System.Collections.Generic.SortedList<string, TableSchema.Table> schemaCollection = new System.Collections.Generic.SortedList<string, TableSchema.Table>();



        #endregion

        internal abstract string GetDatabaseVersion(string providerName);
        public virtual string MakeParam(string paramName)
        {
            return Utility.PrefixParameter(paramName, this);
        }
        public abstract IDataReader GetReader(QueryCommand cmd);
        public virtual DataSet GetDataSet(QueryCommand cmd) { return GetDataSet<DataSet>(cmd); }
        public abstract T GetDataSet<T>(QueryCommand qry) where T : DataSet, new();

        public abstract object ExecuteScalar(QueryCommand cmd);
        public abstract int ExecuteQuery(QueryCommand cmd);
        public abstract TableSchema.Table GetTableSchema(string tableName, TableType tableType);
        public abstract string[] GetSPList();
        public abstract string[] GetTableNameList();
        public abstract string[] GetViewNameList();
        public abstract IDataReader GetSPParams(string spName);

        public abstract string[] GetForeignKeyTables(string tableName);
        public abstract string GetTableNameByPrimaryKey(string pkName, string providerName);

        public abstract ArrayList GetPrimaryKeyTableNames(string tableName);
        public abstract TableSchema.Table[] GetPrimaryKeyTables(string tableName);
        public abstract string GetForeignKeyTableName(string fkColumnName);
        public abstract string GetForeignKeyTableName(string fkColumnName, string tableName);
        public TableSchema.Table GetForeignKeyTable(TableSchema.TableColumn fkColumn, TableSchema.Table table)
        {
            string fkName = GetForeignKeyTableName(fkColumn.ColumnName, table.Name);
            if (!String.IsNullOrEmpty(fkName))
            {
                return DataService.GetSchema(fkName, Name, table.TableType);
            }
            return null;
        }
        public abstract DbType GetDbType(string dataType);
        public abstract IDbCommand GetCommand(QueryCommand qry);
        public abstract DbCommand GetDbCommand(QueryCommand qry);


        internal abstract DbConnection CreateConnection();
        internal abstract DbConnection CreateConnection(string connectionString);

        [ThreadStatic]
        private static DbConnection __sharedConnection;
        public DbConnection CurrentSharedConnection
        {
            get { return __sharedConnection; }

            protected set
            {
                if (value == null)
                {
                    __sharedConnection.Dispose();
                    __sharedConnection = null;
                }
                else
                {
                    __sharedConnection = value;
                    __sharedConnection.Disposed += new EventHandler(__sharedConnection_Disposed);
                }
            }
        }

        private static void __sharedConnection_Disposed(object sender, EventArgs e)
        {
            __sharedConnection = null;
        }

        internal DbConnection InitializeSharedConnection()
        {
            if (CurrentSharedConnection == null)
                CurrentSharedConnection = CreateConnection();
            return CurrentSharedConnection;
        }

        internal DbConnection InitializeSharedConnection(string sharedConnectionString)
        {
            if (CurrentSharedConnection == null)
                CurrentSharedConnection = CreateConnection(sharedConnectionString);
            return CurrentSharedConnection;
        }

        internal void ResetSharedConnection()
        {
            CurrentSharedConnection = null;
        }

        public bool CurrentConnectionStringIsDefault
        {
            get
            {
                if(CurrentSharedConnection != null)
                {
                    if(CurrentSharedConnection.ConnectionString != DefaultConnectionString)
                    {
                        return false;
                    }
                }
                return true;
            }
        }

        public bool UseRegexReplace
        {
            get { return !String.IsNullOrEmpty(RegexMatchExpression) || !String.IsNullOrEmpty(RegexDictionaryReplace); }
        }

        /// <summary>
        /// Returns the total number of records matching the current query.
        /// </summary>
        /// <returns></returns>
        public virtual int GetRecordCount(Query qry)
        {
            string select = SqlFragment.SELECT + "COUNT (1) FROM ";
            if (qry.IsDistinct && !String.IsNullOrEmpty(qry.SelectList))
            {
                string[] distinct = qry.SelectList.Split(new char[] {','});
                select = SqlFragment.SELECT + "COUNT (DISTINCT " + distinct[0] + ") FROM ";
            }
            QueryCommand qc = BuildSelectCommand(select + Utility.QualifyColumnName(qry.Schema.SchemaName, qry.Schema.Name, qry.Provider) + BuildWhere(qry), qry);
            qc.CommandType = CommandType.Text;
            object obj = ExecuteScalar(qc);
            if (obj != null)
            {
                return (int)obj;
            }
            else
            {
                return 0;
            }
        }

        public QueryCommand BuildSelectCommand(Query qry)
        {
            //get the SQL
            string sql = GetSql(qry);
            return BuildSelectCommand(sql, qry);
        }

        public static void AddWhereParameters(QueryCommand cmd, Query qry)
        {
            foreach (Where where in qry.wheres)
            {
                if (where.ParameterValue != null && where.ParameterValue != DBNull.Value)
                {
                    cmd.AddParameter(where.ParameterName, where.ParameterValue, where.DbType);
                }
            }

            foreach (BetweenAnd between in qry.betweens)
            {
                cmd.AddParameter(between.StartParameterName, between.StartDate, DbType.DateTime);
                cmd.AddParameter(between.EndParameterName, between.EndDate, DbType.DateTime);
            }
            if (qry.inList != null)
            {
                if (qry.inList.Length > 0)
                {
                    int inCount = 1;
                    foreach (object inItem in qry.inList)
                    {
                        cmd.AddParameter("in" + inCount, inItem);
                        inCount++;
                    }
                }
            }
        }

        public static QueryCommand BuildSelectCommand(string sql, Query qry)
        {
            QueryCommand cmd = new QueryCommand(sql, qry.ProviderName);
            AddWhereParameters(cmd, qry);
           
            return cmd;
        }


        public string GetUpdateSql(Query qry)
        {
            //split the TablNames and loop out the SQL
            TableSchema.Table table = qry.Schema;
            string updateSQL = SqlFragment.UPDATE + Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider) + SqlFragment.SET;

            string cols = "";
            //int loopCount = 1;

            bool isFirstColumn = true;
            foreach (TableSchema.TableColumn col in table.Columns)
            {
                string colName = col.ColumnName;

                //don't want to change the created bits
                if (Utility.IsWritableColumn(col))
                {
                    if (!isFirstColumn)
                    {
                        cols += ", ";
                    }
                    isFirstColumn = false;
                    cols += Utility.MakeParameterAssignment(colName, colName, qry.Provider);
                }
            }

            //cols = cols.Remove(cols.Length - 1, 1);

            updateSQL += cols;

            if (qry.wheres.Count == 0)
            {
                // Thanks Jason!
                TableSchema.TableColumn[] keys = table.PrimaryKeys;
                updateSQL += SqlFragment.WHERE;
                for (int i = 0; i < keys.Length; i++)
                {
                    updateSQL += Utility.MakeParameterAssignment(keys[i].ColumnName, keys[i].ColumnName, qry.Provider);
                    if (i + 1 != keys.Length)
                        updateSQL += SqlFragment.AND;

                }

                updateSQL = AdjustUpdateSql(qry, table, updateSQL);

            }
            else
            {
                updateSQL += BuildWhere(qry);
            }
            return updateSQL;
        }

        protected virtual string AdjustUpdateSql(Query qry, TableSchema.Table table, string updateSql)
        {
            return updateSql + "; " + SqlFragment.SELECT + Utility.PrefixParameter(table.PrimaryKey.ColumnName, qry.Provider) + SqlFragment.AS + "id";
        }

        public QueryCommand BuildUpdateCommand(Query qry)
        {
            TableSchema.Table table = qry.Schema;
            if (qry.UpdateSettings == null)
                throw new Exception("No update settings have been set. Use Query.AddUpdateSetting to add some in");

            string sql = SqlFragment.UPDATE + table.Name;
            QueryCommand cmd = new QueryCommand(sql, qry.ProviderName);

            //append the update statements
            IDictionaryEnumerator looper = qry.UpdateSettings.GetEnumerator();
            string setClause = SqlFragment.SET;
            bool isFirstColumn = true;
            while (looper.MoveNext())
            {
                TableSchema.TableColumn column;
                column = table.GetColumn(looper.Key.ToString());
                if (column != null)
                {

                    if (!isFirstColumn)
                    {
                        sql += "," + Utility.MakeParameterAssignment(looper.Key.ToString(), looper.Key.ToString(), qry.Provider);
                    }
                    else
                    {
                        isFirstColumn = false;
                        sql += setClause + Utility.MakeParameterAssignment(looper.Key.ToString(), looper.Key.ToString(), qry.Provider);
                        setClause = String.Empty;
                    }
                    cmd.AddParameter(looper.Key.ToString(), looper.Value, column.DataType);

                }
                else
                {
                    throw new Exception("There is no column in " + table.Name + " called " + looper.Key);
                }
            }

            sql += BuildWhere(qry);
            AddWhereParameters(cmd, qry);
            cmd.CommandSql = sql;
            return cmd;
        }



        public QueryCommand BuildDeleteCommand(Query qry)
        {
            string sql = SqlFragment.DELETE_FROM + Utility.QualifyColumnName(qry.Schema.SchemaName, qry.Schema.Name, qry.Provider);
            QueryCommand cmd = new QueryCommand(sql, qry.ProviderName);
            if(qry.UpdateSettings != null)
            {
                IDictionaryEnumerator looper = qry.UpdateSettings.GetEnumerator();
                while(looper.MoveNext())
                {
                    TableSchema.TableColumn column;
                    column = qry.Schema.GetColumn(looper.Key.ToString());
                    if (column != null)
                    {
                        cmd.AddParameter(looper.Key.ToString(), looper.Value, column.DataType);
                    }
                }
            }
            sql += BuildWhere(qry);
            AddWhereParameters(cmd, qry);
            cmd.CommandSql = sql;
            return cmd;
        }


        public static string GetDeleteSql(Query qry)
        {
            TableSchema.Table table = qry.Schema;
            string sql = SqlFragment.DELETE_FROM + Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider);
            if (qry.wheres.Count == 0)
            {
                // Thanks Jason!
                TableSchema.TableColumn[] keys = table.PrimaryKeys;
                for (int i = 0; i < keys.Length; i++)
                {
                    sql += SqlFragment.WHERE + Utility.MakeParameterAssignment(keys[i].ColumnName, keys[i].ColumnName, qry.Provider);
                    if (i + 1 != keys.Length)
                        sql += SqlFragment.AND;

                }
            }
            else
            {
                sql += BuildWhere(qry);
            }
            return sql;
        }


        public static string BuildWhere(Query qry)
        {
            string where = String.Empty;
            string whereOperator = SqlFragment.WHERE;
            bool isFirstPass = true;


            foreach (Where wWhere in qry.wheres)
            {

                whereOperator = isFirstPass ? SqlFragment.WHERE : whereOperator = " " + Enum.GetName(typeof(Where.WhereCondition), wWhere.Condition) + " ";

                where += whereOperator +
                         Utility.QualifyColumnName(wWhere.TableName, wWhere.ColumnName, qry.Provider) +
                         Where.GetComparisonOperator(wWhere.Comparison);
                if (wWhere.ParameterValue != DBNull.Value && wWhere.ParameterValue != null)
                {
                    where += Utility.PrefixParameter(wWhere.ParameterName, qry.Provider);
                }
                else
                {
                    where += " NULL";
                }

                isFirstPass = false;
            }
            //isFirstPass = true;
            foreach (BetweenAnd between in qry.betweens)
            {
                if (qry.wheres.Count == 0 && isFirstPass)
                {
                    whereOperator = SqlFragment.WHERE;
                }
                else
                {
                    whereOperator = isFirstPass ? SqlFragment.WHERE : whereOperator = " " + Enum.GetName(typeof(Where.WhereCondition), between.Condition) + " ";
                }

                where += whereOperator +
                         Utility.QualifyColumnName(between.TableName, between.ColumnName, qry.Provider) +
                         SqlFragment.BETWEEN + Utility.PrefixParameter(between.StartParameterName, qry.Provider) +
                         SqlFragment.AND + Utility.PrefixParameter(between.EndParameterName, qry.Provider);
                isFirstPass = false;
            }

            for (int i = qry.wheres.Count - 1; i >= 0; i--)
            {
                if (qry.wheres[i].ParameterValue == DBNull.Value)
                {
                    qry.wheres.RemoveAt(i);
                }
            }

            if (qry.inList != null)
            {
                if (qry.inList.Length > 0)
                {
                    if (isFirstPass)
                    {
                        where += whereOperator;
                    }
                    else
                    {
                        where += SqlFragment.AND;
                    }

                    where += qry.Provider.DelimitDbName(qry.inColumn) + SqlFragment.IN + "(";
                    bool isFirst = true;

                    for (int i = 1; i <= qry.inList.Length; i++)
                    {
                        if (!isFirst)
                        {
                            where += ", ";
                        }
                        isFirst = false;

                        where += Utility.PrefixParameter("in" + i, qry.Provider);
                    }
                    where += ")";
                }
            }

            return where;
        }

        public abstract void SetParameter(IDataReader rdr, StoredProcedure.Parameter par);
        public abstract string GetParameterPrefix();
        public virtual string DelimitDbName(string columnName)
        {
            return columnName;
        }

        public abstract void ExecuteTransaction(QueryCommandCollection commands);


        //sql builders
        public abstract string GetSql(Query qry);
        public abstract string GetInsertSql(Query qry);
        public abstract string GetSelectSql(Query qry);

        public abstract QueryCommand BuildCommand(Query qry);

        public abstract string ScriptData(string tableName);
        public abstract string ScriptData(string tableName, string providerName);
        public abstract string ScriptSchema();
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            connectionStringName = config[ConfigurationPropertyName.CONNECTION_STRING_NAME].ToString();
            //connectionString = DefaultConnectionString;

            ApplyConfig(config, ref manyToManySuffix, ConfigurationPropertyName.MANY_TO_MANY_SUFFIX);
            ApplyConfig(config, ref relatedTableLoadPrefix, ConfigurationPropertyName.RELATED_TABLE_LOAD_PREFIX);
            ApplyConfig(config, ref viewStartsWith, ConfigurationPropertyName.VIEW_STARTS_WITH);
            ApplyConfig(config, ref spStartsWith, ConfigurationPropertyName.SP_STARTS_WITH);
            ApplyConfig(config, ref appendWith, ConfigurationPropertyName.APPEND_WITH);
            ApplyConfig(config, ref stripParamText, ConfigurationPropertyName.STRIP_PARAM_TEXT);
            ApplyConfig(config, ref stripColumnText, ConfigurationPropertyName.STRIP_COLUMN_TEXT);
            ApplyConfig(config, ref stripTableText, ConfigurationPropertyName.STRIP_TABLE_TEXT);
            ApplyConfig(config, ref stripViewText, ConfigurationPropertyName.STRIP_VIEW_TEXT);
            ApplyConfig(config, ref stripSPText, ConfigurationPropertyName.STRIP_STORED_PROCEDURE_TEXT);
            ApplyConfig(config, ref spClassName, ConfigurationPropertyName.STORED_PROCEDURE_CLASS_NAME);
            ApplyConfig(config, ref generatedNamespace, ConfigurationPropertyName.GENERATED_NAMESPACE);
            ApplyConfig(config, ref connectionStringName, ConfigurationPropertyName.CONNECTION_STRING_NAME);
            ApplyConfig(config, ref regexMatchExpression, ConfigurationPropertyName.REGEX_MATCH_EXPRESSION);
            ApplyConfig(config, ref regexReplaceExpression, ConfigurationPropertyName.REGEX_REPLACE_EXPRESSION);
            ApplyConfig(config, ref regexDictionaryReplace, ConfigurationPropertyName.REGEX_DICTIONARY_REPLACE);
            ApplyConfig(config, ref excludeTableList, ConfigurationPropertyName.EXCLUDE_TABLE_LIST);
            ApplyConfig(config, ref includeTableList, ConfigurationPropertyName.INCLUDE_TABLE_LIST);

            //Booleans
            ApplyConfig(config, ref useSPs, ConfigurationPropertyName.USE_STORED_PROCEDURES);
            //ApplyConfig(config, ref generateSPs, ConfigurationPropertyName.GENERATE_STORED_PROCEDURES);
            ApplyConfig(config, ref fixPluralClassNames, ConfigurationPropertyName.FIX_PLURAL_CLASS_NAMES);
            ApplyConfig(config, ref removeUnderscores, ConfigurationPropertyName.REMOVE_UNDERSCORES);
            ApplyConfig(config, ref regexIgnoreCase, ConfigurationPropertyName.REGEX_IGNORE_CASE);
            ApplyConfig(config, ref generateLazyLoads, ConfigurationPropertyName.GENERATE_LAZY_LOADS);
            ApplyConfig(config, ref generateRelatedTablesAsProperties, ConfigurationPropertyName.GENERATE_RELATED_TABLES_AS_PROPERTIES);
            ApplyConfig(config, ref extractClassNameFromSPName, ConfigurationPropertyName.EXTRACT_CLASS_NAME_FROM_SP_NAME);
            ApplyConfig(config, ref useExtendedProperties, ConfigurationPropertyName.USE_EXTENDED_PROPERTIES);
            ApplyConfig(config, ref setPropertyDefaultsFromDatabase, ConfigurationPropertyName.SET_PROPERTY_DEFAULTS_FROM_DATABASE);
            ApplyConfig(config, ref generateNullableProperties, ConfigurationPropertyName.GENERATE_NULLABLE_PROPERTIES);
            ApplyConfig(config, ref generateODSControllers, ConfigurationPropertyName.GENERATE_ODS_CONTROLLERS);

            ApplyConfig(config, ref excludeProcedureList, ConfigurationPropertyName.EXCLUDE_PROCEDURE_LIST);
            ApplyConfig(config, ref includeProcedureList, ConfigurationPropertyName.INCLUDE_PROCEDURE_LIST);

            includeTableList = Utility.StripWhitespace(includeTableList);
            excludeTableList = Utility.StripWhitespace(excludeTableList);
            includeProcedureList = Utility.StripWhitespace(includeProcedureList);
            excludeProcedureList = Utility.StripWhitespace(excludeProcedureList);
        }

        private static void ApplyConfig(System.Collections.Specialized.NameValueCollection config, ref string parameterValue, string configName)
        {
            if (config[configName] != null)
            {
                parameterValue = config[configName].ToString();
            }
        }

        private static void ApplyConfig(System.Collections.Specialized.NameValueCollection config, ref bool parameterValue, string configName)
        {
            if (config[configName] != null)
            {
                parameterValue = Convert.ToBoolean(config[configName]);
            }
        }

        /// <summary>
        /// DataSet helper class used to get the names of the tables in the DataSet.
        /// </summary>
        /// <param name="ds">The DataSet to get the names for.</param>
        /// <returns>The names of the tables in the DataSet.</returns>
        protected static string[] GetTableNames(DataSet ds)
        {
            int tblCount = ds.Tables.Count;
            string[] tableNames = new string[tblCount];
            for (int iTable = 0; iTable < tblCount; iTable++)
            {
                tableNames[iTable] = ds.Tables[iTable].TableName;
            }
            return tableNames;
        }

        /// <summary>
        /// DataSet helper class used to add table mappings to a DataAdapter.
        /// </summary>
        /// <remarks>
        /// TableMappings keep the table names during a Fill operation.
        /// </remarks>
        /// <param name="da">The DataAdapter to add the mappings to.</param>
        /// <param name="ds">The DataSet containing the tables to map.</param>
        protected static void AddTableMappings(DataAdapter da, DataSet ds)
        {
            string rootName = "Table";
            string[] tableNames = GetTableNames(ds);

            for (int i = 0; i < tableNames.Length; i++)
            {
                string newName = (i == 0) ? rootName : rootName + i;
                da.TableMappings.Add(newName, tableNames[i]);
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Alex Mueller
Web Developer
United States United States
No Biography provided

You may also be interested in...

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 17 Nov 2007
Article Copyright 2007 by Alex Mueller
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid