Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Populating a business logical layer from Stored Procedures

, 22 Sep 2014 CPOL
A brief look at a technique mapping tables to a basic business layer.
doPersistence-noexe.zip
doPersistence
doPersistence.csproj.user
doPersistence.csproj.vspscc
obj
Debug
Release
Properties
doLogicCode
bin
Debug
doLogicCode.vshost.exe.manifest
doLogicCode.csproj.vspscc
obj
x86
Debug
doLogicCode.frmCodeGenerator.resources
doLogicCode.Properties.Resources.resources
Properties
Settings.settings
doPersistence.zip
Test
doLogic
bin
Debug
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
Release
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
obj
Debug
DesignTimeResolveAssemblyReferencesInput.cache
doLogic.dll
doLogic.pdb
ResolveAssemblyReference.cache
TempPE
Release
DesignTimeResolveAssemblyReferencesInput.cache
doLogic.dll
doLogic.pdb
ResolveAssemblyReference.cache
TempPE
Properties
doLogicCode
bin
Debug
doLogicCode.exe
doLogicCode.pdb
doLogicCode.vshost.exe
doLogicCode.vshost.exe.manifest
doPersistence.dll
doPersistence.pdb
obj
x86
Debug
DesignTimeResolveAssemblyReferencesInput.cache
doLogicCode.exe
doLogicCode.frmCodeGenerator.resources
doLogicCode.pdb
doLogicCode.Properties.Resources.resources
GenerateResource.read.1.tlog
GenerateResource.write.1.tlog
ResolveAssemblyReference.cache
TempPE
Properties.Resources.Designer.cs.dll
Properties
Settings.settings
doPersistence
bin
Debug
doPersistence.dll
doPersistence.pdb
Release
doPersistence.dll
doPersistence.pdb
doPersistence.csproj.vspscc
obj
Debug
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.dll
doPersistence.pdb
TempPE
Release
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.dll
doPersistence.pdb
TempPE
Properties
Test.suo
TestSite
Account
App_Data
bin
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
TestSite.dll
TestSite.pdb
Global.asax
obj
Debug
DesignTimeResolveAssemblyReferencesInput.cache
ResolveAssemblyReference.cache
TempPE
TestSite.dll
TestSite.pdb
Release
CSAutoParameterize
original
Account
transformed
Account
Database
DesignTimeResolveAssemblyReferencesInput.cache
Package
PackageTmp
Account
bin
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
TestSite.dll
TestSite.pdb
Global.asax
Scripts
Styles
ResolveAssemblyReference.cache
TempPE
TestSite.dll
TestSite.pdb
TransformWebConfig
original
transformed
Account
Properties
Scripts
Styles
TestSite.csproj.user
dopersistenceexample.zip
doLogic.dll
doPersistence.dll
doPersistence.dll
doLogic.dll
doPersistence.dll
TestSite.dll
Global.asax
TestSite.csproj.user
dopersistencepocodynamicsqlexample.zip
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
DesignTimeResolveAssemblyReferencesInput.cache
doLogic.dll
doLogic.pdb
ResolveAssemblyReference.cache
DesignTimeResolveAssemblyReferencesInput.cache
doLogic.dll
doLogic.pdb
ResolveAssemblyReference.cache
doPersistence.dll
doPersistence.pdb
doPersistence.dll
doPersistence.pdb
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.dll
doPersistence.pdb
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.dll
Test.suo
doLogic.dll
doLogic.pdb
doPersistence.dll
doPersistence.pdb
TestSite.dll
TestSite.pdb
Global.asax
DesignTimeResolveAssemblyReferencesInput.cache
ResolveAssemblyReference.cache
TestSite.dll
TestSite.pdb
DesignTimeResolveAssemblyReferencesInput.cache
ResolveAssemblyReference.cache
TestSite.dll
TestSite.pdb
TestSite.csproj.user
PersistenceTest20131129-noexe.zip
PersistenceTest_orig
Account
App_Code
App_Data
Bin
Persistence.pdb
Global.asax
Scripts
Styles
Persistence
bin
Debug
doPersistence.pdb
Persistence.pdb
Release
doPersistence.pdb
doPersistence.csproj.vspscc
obj
Debug
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.csprojResolveAssemblyReference.cache
doPersistence.pdb
Persistence.pdb
TempPE
Release
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.pdb
TempPE
Persistence.csproj.user
Properties
PersistenceTest_orig.v11.suo
CodeGenerator
bin
Debug
doLogicCode.pdb
doLogicCode.vshost.exe.manifest
doPersistence.pdb
Persistence.pdb
CodeGenerator.csproj.vspscc
obj
x86
Debug
CodeGenerator.csproj.GenerateResource.Cache
CodeGenerator.csprojResolveAssemblyReference.cache
CodeGenerator.frmCodeGenerator.resources
CodeGenerator.Properties.Resources.resources
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
doLogicCode.csproj.GenerateResource.Cache
doLogicCode.csprojResolveAssemblyReference.cache
doLogicCode.pdb
TempPE
Properties
Settings.settings
PersistenceTest20131129.zip
AjaxControlToolkit.dll
Persistence.dll
Persistence.pdb
Global.asax
doPersistence.dll
doPersistence.pdb
Persistence.dll
Persistence.pdb
doPersistence.dll
doPersistence.pdb
doPersistence.csproj.vspscc
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.csprojResolveAssemblyReference.cache
doPersistence.dll
doPersistence.pdb
Persistence.dll
Persistence.pdb
DesignTimeResolveAssemblyReferencesInput.cache
doPersistence.dll
doPersistence.pdb
Persistence.csproj.user
PersistenceTest_orig.v11.suo
doLogicCode.exe
doLogicCode.pdb
doLogicCode.vshost.exe
doLogicCode.vshost.exe.manifest
doPersistence.dll
doPersistence.pdb
Persistence.dll
Persistence.pdb
CodeGenerator.csproj.vspscc
CodeGenerator.csproj.GenerateResource.Cache
CodeGenerator.csprojResolveAssemblyReference.cache
CodeGenerator.frmCodeGenerator.resources
CodeGenerator.Properties.Resources.resources
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
doLogicCode.csproj.GenerateResource.Cache
doLogicCode.csprojResolveAssemblyReference.cache
doLogicCode.exe
doLogicCode.pdb
Properties.Resources.Designer.cs.dll
Settings.settings
using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using System.Collections;
using System.Configuration;

/*
 * todo:
 * CopyStructure to DataTable from SP resultset
*/

namespace doPersistence
{
	internal class SqlServer
    {
		internal static readonly bool _AllowsDirectSql = false;
		public static readonly Exception InitializationError = null;

        static SqlServer()
        {
            try
            {
                using (SqlConnection cn = new SqlConnection(Database._ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("sys_ExtendedProperty");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@PropertyName", "AllowsDirectSql");
                    cmd.Connection = cn;
                    cn.Open();

                    object value = cmd.ExecuteScalar();
                    int i = 0;
                    if (value != null && int.TryParse(Convert.ToString(value), out i) && i == 1)
                        _AllowsDirectSql = true;
                }
            }
            catch (Exception ex) { InitializationError = ex; }
        }

		private static Hashtable tables = new Hashtable();

		public static DataTable GetTableStructure(string tableName, string connString)
        {
			if (tables.ContainsKey(tableName))
				return ((DataTable)tables[tableName]).Clone();

			DataTable table = new DataTable();
			table.TableName = tableName;

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand("sys_StructureForTable", conn);
				cmd.CommandType = CommandType.StoredProcedure;
				cmd.Parameters.AddWithValue("@TableName", tableName);
                SqlDataReader reader = cmd.ExecuteReader();
				
				while (reader.Read())
                {
                    DataColumn col = new DataColumn();
                    col.ColumnName = reader["Name"].ToString();
                    col.DataType = TypeMapper.ToNetType(reader["Type"].ToString());
                    col.AllowDBNull = Convert.ToBoolean(reader["IsNullable"]);
					col.AutoIncrement = Convert.ToBoolean(reader["AutoIncrement"]);
                    table.Columns.Add(col);
                }
			
				if (table.Columns.Count < 1)
					throw new ApplicationException(String.Format("Unable to retrieve schema information on table {0} in {1}.  {2} '{3}' returned 0 rows.", cmd.Parameters[0].Value, cmd.Connection.Database, cmd.CommandText, cmd.Parameters[0].Value));
			}

			tables.Add(tableName, table.Clone());

            return table;
        }

        public static void StoreBulk(string tableName, DataTable table, string connString)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();

                //create temporary table
                string sql = String.Format("select top 0 * into #{0} from {0}", tableName);
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

                //bulk copy
                using (SqlBulkCopy bulk = new SqlBulkCopy(conn))
                {
                    bulk.DestinationTableName = "#" + tableName;
                    bulk.WriteToServer(table);
                }

                //merge temp table into production
                cmd = new SqlCommand(Database.SpPrefix + "merge_" + tableName, conn);
                cmd.ExecuteNonQuery();
            }
        }

        public static int LoadAll<T>(PersistentList<T> list, string action, string connString)
        {
            string spName = Database.SpPrefix + "list_" + list.GetItemDataSource + action;

            SqlCommand cmd = GetCommand(spName, connString);
            Database.MapParameterValues(list, cmd);

			int pageNumber = list.PageNumber;
			int pageSize = list.PageSize;

            using (SqlConnection cn = new SqlConnection(connString))
            {
                cmd.Connection = cn;
                cn.Open();
                SqlDataReader reader = cmd.ExecuteReader();

				//pagination skip to appropriate row number
				int rows = 0;
				int endRow = pageNumber * pageSize;
				while (rows < (endRow - pageSize) && reader.Read())
					rows++;

                while (reader.Read())
                {
					T newItem = list.CreateNewItem();
                    Database.MapToInstance(reader, newItem);
                    list.Add(newItem);
					rows++;

					//end of page, read to the end to get total count
					if (rows == pageSize * pageNumber)
						while (reader.Read())
							rows++;
				}
				list._totalRows = rows;
                return rows;
            }
        }

		public static void Load(object o) { Load(o, ""); }
        public static void Load(object o, string action) { Load(o, action, Database._ConnectionString); }
		public static void Load(object o, string action, string connString)
        {
            PersistableAttribute info = Class.GetPersistenceInfo(o);

			if (info.UseDirectSql)
			{
				LoadViaDirectSql(o, connString);
				return;
			}

			string spName = Database.SpPrefix + "load_" + info.DataSource + action;

			SqlCommand cmd = GetCommand(spName, connString);
			Database.MapParameterValues(o, cmd);

            using (SqlConnection cn = new SqlConnection(connString))
            {
                cmd.Connection = cn;
                cn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
					Database.MapToInstance(reader, o);
                else
                    throw new ApplicationException(String.Format("No record found in {0} where {1} = {2}.", info.DataSource, cmd.Parameters[0].ParameterName, cmd.Parameters[0].Value));
            }
		}

        public static DataTable ExecuteDataTable(string spName, object properties, string connString)
        {
            SqlCommand cmd = SqlServer.GetCommand(spName, Database._ConnectionString);
            Database.MapParameterValues(properties, cmd);

            using (SqlConnection cn = new SqlConnection(connString))
            {
                cmd.Connection = cn;
                cn.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                DataTable table = new DataTable();
                table.Load(reader);
                return table;
            }
            //list<DataRow> dr = dt.AsEnumerable().ToList(); 
        }

		public static void LoadViaDirectSql(object o, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

            PersistableAttribute info = Class.GetPersistenceInfo(o);
			string sql = String.Format("select * from {0} where {1}={2}", info.DataSource, info.PrimaryKeyName, Class.GetPropertyValueByName(o, info.PrimaryKeyName));

			using (SqlConnection cn = new SqlConnection(connString))
			{
				SqlCommand cmd = new SqlCommand(sql);
				cmd.Connection = cn;
				cn.Open();
				SqlDataReader reader = cmd.ExecuteReader();
				if (reader.Read())
					Database.MapToInstance(reader, o);
				else
                    throw new ApplicationException(String.Format("{0} id {1} was not found.", info.DataSource, info.PrimaryKeyValue));
            }
		}

		public static int StoreViaDirectSql(object o, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

            PersistableAttribute info = Class.GetPersistenceInfo(o);

			SqlCommand cmd;
			if (info.PrimaryKeyValue > 0)
				cmd = SqlServer.GetUpdateCommand(o, connString);
			else
				cmd = SqlServer.GetInsertCommand(o, connString);

			using (SqlConnection cn = new SqlConnection(connString))
			{
				cmd.Connection = cn;
				cn.Open();
				if (Class.GetPersistenceInfo(o).PrimaryKeyValue > 0)
                {
					int rowsAffected = cmd.ExecuteNonQuery();
					if (rowsAffected == 0)
						throw new ApplicationException(String.Format("No rows affected while updating {0} ({1}={2}).", info.DataSource, info.PrimaryKeyName, info.PrimaryKeyValue));
					return rowsAffected;
                }
                else
				{
					object id = cmd.ExecuteScalar();
					if (id == null || Convert.ToInt32(id) == 0)
						throw new ApplicationException(String.Format("SqlServer did not return a primary key after inserting {0}.", Class.GetPersistenceInfo(o).DataSource));

					info.PrimaryKeyValue = Convert.ToInt32(id);
					return 1;
				}
			}
		}

		public static bool DeleteViaDirectSql(object o, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

			PersistableAttribute info = Class.GetPersistenceInfo(o);
			string sql = String.Format("delete from {0} where {1}={2}", info.DataSource, info.PrimaryKeyName, info.PrimaryKeyValue);
			using (SqlConnection cn = new SqlConnection(connString))
			{
				SqlCommand cmd = new SqlCommand(sql);
				cmd.Connection = cn;
				cn.Open();
				return (cmd.ExecuteNonQuery() > 0);
			}
		}

		public static int Store(object o)
		{
            return Store(o, Database._ConnectionString);
		}

        public static int Store(object o, string connString)
        {
			if (Class.GetPersistenceInfo(o).UseDirectSql)
				return StoreViaDirectSql(o, connString);

			PersistableAttribute pi = Class.GetPersistenceInfo(o);

			string spName = Database.SpPrefix + "store_" + pi.DataSource;

            SqlCommand cmd = GetCommand(spName, connString);
            Database.MapParameterValues(o, cmd);

            int rowsAffected = 0;
            using (SqlConnection cn = new SqlConnection(connString))
            {
                cmd.Connection = cn;
                cn.Open();
                rowsAffected = cmd.ExecuteNonQuery();

                //set output parameter on object (eg. identity key)
                foreach (SqlParameter p in cmd.Parameters)
                {
                    if (p.ParameterName.ToLower() == "@" + pi.PrimaryKeyName.ToLower()
                            && p.Direction == ParameterDirection.Input)
                        throw new ApplicationException("Primary key must be set as an output parameter in the stored procedure: " + spName);
                    if (p.Direction != ParameterDirection.Input)
                    {
                        string name = p.ParameterName;
                        if (name.StartsWith("@"))
                            name = name.Substring(1);

						Class.SetPropertyValueByName(o, name, p.Value);
                    }
                }
            }
            return rowsAffected;
        }

		public static bool Delete(object o)
		{
            return Delete(o, Database._ConnectionString);
		}

        public static bool Delete(object o, string connString)
        {
			if (Class.GetPersistenceInfo(o).UseDirectSql)
				return DeleteViaDirectSql(o, connString);

			string spName = Database.SpPrefix + "delete_" + Class.GetPersistenceInfo(o).DataSource;

            SqlCommand cmd = GetCommand(spName, connString);
            Database.MapParameterValues(o, cmd);

            using (SqlConnection cn = new SqlConnection(connString))
            {
                cmd.Connection = cn;
                cn.Open();
                return cmd.ExecuteNonQuery() > 0;
            }
        }

        public static int ExecuteNonQuery(string sql, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

			using (SqlConnection cn = new SqlConnection(connString))
			{
				SqlCommand cmd = new SqlCommand(sql);
				cmd.Connection = cn;
				cn.Open();
				return cmd.ExecuteNonQuery();
			}
		}

		public static SqlDataReader ExecuteReader(string sql, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

			using (SqlConnection cn = new SqlConnection(connString))
			{
				SqlCommand cmd = new SqlCommand(sql);
				cmd.Connection = cn;
				cn.Open();
				return cmd.ExecuteReader();
			}
		}

		public static object ExecuteScalar(string sql, string connString)
		{
			if (!Database.AllowsDirectSql)
				throw new ApplicationException("The database does not allow direct sql.  To enable, set AllowsDirectSql = 1 in SqlServer's extended properties (sys.extended_properties).");

			using (SqlConnection cn = new SqlConnection(connString))
			{
				SqlCommand cmd = new SqlCommand(sql);
				cmd.Connection = cn;
				cn.Open();
				return cmd.ExecuteScalar();
			}
		}

		private static Hashtable cmds = new Hashtable();

        public static SqlCommand GetCommand(string spName, string connString)
        {
			SqlCommand cmd = null;
			if (cmds.ContainsKey(spName))
            {
				cmd = ((SqlCommand)cmds[spName]).Clone();   //thread safety
			}
            else
            {
				cmd = new SqlCommand(spName);
				cmd.CommandType = CommandType.StoredProcedure;
				CreateParameters(cmd, spName, connString);
				cmds.Add(spName, cmd);
			}
			return cmd;
		}

        public static void CreateParameters(SqlCommand cmd, string spName, string connString)
        {
			using (SqlConnection cn = new SqlConnection(connString))
            {
				SqlCommand parmCmd = new SqlCommand("sys_ParametersForSP", cn);
                parmCmd.CommandType = CommandType.StoredProcedure;
                parmCmd.Parameters.AddWithValue("@SPName", spName);

				cn.Open();
				SqlDataReader reader = parmCmd.ExecuteReader();

				while (reader.Read())
                {
                    SqlParameter parm = new SqlParameter();
                    parm.ParameterName = "@" + Convert.ToString(reader["Name"]);
                    parm.IsNullable = Convert.ToBoolean(reader["IsNullable"]);
                    parm.Precision = Convert.ToByte(reader["XPrec"]);
                    parm.Size = Convert.ToInt32(reader["Length"]);
                    parm.SqlDbType = TypeMapper.ToSqlDbType(Convert.ToString(reader["Type"]));
                    if (Convert.ToBoolean(reader["IsOutParam"]))
						parm.Direction = ParameterDirection.InputOutput;
					else
						parm.Direction = ParameterDirection.Input;

					cmd.Parameters.Add(parm);
				}
			}
		}

		public static SqlCommand GetUpdateCommand(object o, string connString)
		{
			string sql = "update {0} set {1} where {2}={3}";
			string sets = "";

			PersistableAttribute pi = Class.GetPersistenceInfo(o);

			SqlCommand cmd = new SqlCommand();

			DataTable table = SqlServer.GetTableStructure(pi.DataSource, connString);
			foreach (DataColumn col in table.Columns)
			{
				if (col.ColumnName == pi.PrimaryKeyName)
					continue;
				if (col.AutoIncrement)
					continue;

				if (!string.IsNullOrEmpty(sets))
					sets += ", ";

				sets += col.ColumnName + "=@" + col.ColumnName;
			
				object value = Class.GetPropertyValueByName(o, col.ColumnName);

				if (Class.IsNull(value))
					value = DBNull.Value;

				cmd.Parameters.Add("@" + col.ColumnName, TypeMapper.ToSqlDbType(col.DataType), col.MaxLength).Value = value;
			}

			if (String.IsNullOrEmpty(sets))
				throw new ApplicationException("Table not found in database: " + Class.GetPersistenceInfo(o).DataSource);

			cmd.CommandText = String.Format(sql, pi.DataSource, sets, pi.PrimaryKeyName, pi.PrimaryKeyValue);

			return cmd;
		}

		public static SqlCommand GetInsertCommand(object o, string connString)
		{
			string sql = "insert into {0} ({1}) values ({2}); select scope_identity();";
			string fields = "";
			string parms = "";

			PersistableAttribute pi = Class.GetPersistenceInfo(o);

			SqlCommand cmd = new SqlCommand();

			DataTable table = SqlServer.GetTableStructure(pi.DataSource, connString);
			foreach (DataColumn col in table.Columns)
			{
				if (col.ColumnName == pi.PrimaryKeyName)
					continue;
				if (col.AutoIncrement)
					continue;

				if (!string.IsNullOrEmpty(fields))
					fields += ", ";
				if (!string.IsNullOrEmpty(parms))
					parms += ", ";

				fields += col.ColumnName;
				parms += "@" + col.ColumnName;

				object value = Class.GetPropertyValueByName(o, col.ColumnName);

				if (Class.IsNull(value))
					value = DBNull.Value;

				cmd.Parameters.Add("@" + col.ColumnName, TypeMapper.ToSqlDbType(col.DataType), col.MaxLength).Value = value;
			}

			if (String.IsNullOrEmpty(fields))
				throw new ApplicationException("Table not found in database: " + pi.DataSource);

			cmd.CommandText = String.Format(sql, pi.DataSource, fields, parms);

			return cmd;
		}
	}
}

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

andrewbb@gmail.com
Architect
United States United States
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 22 Sep 2014
Article Copyright 2012 by andrewbb@gmail.com
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid