Click here to Skip to main content
12,629,684 members (31,966 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.8K views
3 bookmarked
Posted

Writing Business Objects Using Enterprise Library

, 3 May 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How to write business object in C#

Introduction

I have tried to manage the external transaction, and connection issue in this article

Background 

I was writing a test sample and and came up with solution, so thought might be use full for someone.

Using the code 

Read care fully.

I have added three classes

  • Businessobject.cs
  • User.cs
  • UserCollection.cs

You also need a table mapping schema. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace WindowsFormsApplication4.DAL
{
    /// <summary>
    /// Base business object
    /// </summary>
    [Serializable()]
    public abstract class BusinessObject
    {
        /// <summary>
        /// internal Database context
        /// </summary>
        internal Database dbContext;

        #region Properties

        private long mOID;
        /// <summary>
        /// the auto increment Id
        /// </summary>
        public long OID
        {
            get { return mOID; }
            set { mOID = value; }
        }

        private bool mIsDirty;
        /// <summary>
        /// is set if Object is dirty, or invalid
        /// </summary>
        public bool IsDirty
        {
            get { return mIsDirty; }
            set { mIsDirty = value; }
        }

        private bool mIsChanged;
        /// <summary>
        /// is set if object has changed its original condition
        /// </summary>
        public bool IsChanged
        {
            get { return mIsChanged; }
            set { mIsChanged = value; }
        }

        private bool mIsNew;
        /// <summary>
        /// is set when a new object is created
        /// </summary>
        public bool IsNew
        {
            get { return mIsNew; }
            set { mIsNew = value; }
        }


        private bool mUseExternalTransaction = false;
        /// <summary>
        /// is set when external transaction has to be used
        /// </summary>
        public bool UserExternalTransaction
        {
            get { return mUseExternalTransaction; }
            set { mUseExternalTransaction = value; }
        }

        private bool mIsLoadedfromReader = false;
        /// <summary>
        /// is set when object is loaded by reader
        /// </summary>
        public bool IsLoadedFromReader
        {
            get { return mIsLoadedfromReader; }
            set { mIsLoadedfromReader = value; }
        }

        /// <summary>
        /// created by 
        /// </summary>
        public Nullable<long> CreatedBy { get; set; }
        /// <summary>
        /// created on date
        /// </summary>
        public Nullable<DateTime> CreatedOn { get; set; }
        /// <summary>
        /// modified by 
        /// </summary>
        public Nullable<long> ModifiedBy { get; set; }
        /// <summary>
        /// modified on date
        /// </summary>
        public Nullable<DateTime> ModifiedOn { get; set; }

        [NonSerialized()]
        private IDbConnection mConnection;
        /// <summary>
        /// non serialized connection object
        /// </summary>
        [System.Xml.Serialization.XmlIgnore()]
        public IDbConnection Connection
        {
            get { return mConnection; }
            set { mConnection = value; }
        }

        [NonSerialized()]
        private System.Data.Common.DbTransaction mtransaction;
        /// <summary>
        /// non serialized transaction object
        /// </summary>
        [System.Xml.Serialization.XmlIgnore()]
        public System.Data.Common.DbTransaction Transaction
        {
            get { return mtransaction; }
            set
            {
                mtransaction = value;
                mConnection = Transaction.Connection;
                mUseExternalTransaction = true;
            }
        }

        #endregion

        #region Constructors
        /// <summary>
        /// Enpty constructor will created local database context
        /// </summary>
        public BusinessObject()
        {
            dbContext = DatabaseFactory.CreateDatabase();
        }

        /// <summary>
        /// DB connection passed if need to be used
        /// </summary>
        /// <param name="conn"></param>
        public BusinessObject(System.Data.Common.DbConnection conn)
            : this()
        {
            SetupDatabaseConnectivity(conn: conn);
        }

        /// <summary>
        /// passed transaction if businessobject is to be used in external transaction
        /// </summary>
        /// <param name="trans"></param>
        public BusinessObject(System.Data.Common.DbTransaction trans)
            : this()
        {
            SetupDatabaseConnectivity(trans: trans);
        }

        /// <summary>
        /// pass transaction and conenction
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        public BusinessObject(System.Data.Common.DbConnection conn, 
                     System.Data.Common.DbTransaction trans)
            : this()
        {
            SetupDatabaseConnectivity(conn: conn, trans: trans);
        }



        #endregion

        #region  Helper
        /// <summary>
        /// set up database connectivity of business object
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        public void SetupDatabaseConnectivity(System.Data.Common.DbConnection conn = 
               null, System.Data.Common.DbTransaction trans = null)
        {
            if (trans == null)
                Connection = conn;
            else
            {
                Transaction = trans;
                Connection = trans.Connection;
                UserExternalTransaction = true;
            }
        }

        /// <summary>
        /// unhook object to conisder as new object
        /// </summary>
        public void Unhook()
        {
            // reset primary Key variables
            mOID = 0;
            mIsNew = true;
        }
        #endregion
    }
}


//////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace WindowsFormsApplication4.DAL.Classes
{
    /// <summary>
    /// Class representing User business object
    /// </summary>
    public class User : BusinessObject
    {
        #region  Constants

        const string SP_FETCH = "spUser_Fetch";
        const string SP_FETCH_LIST = "spUser_FetchList";
        const string SP_SAVE = "spUSER_Save";
        const string SP_DELETE = "spUSER_Delete";

        #endregion

        #region DB Properties
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public Nullable<long> UserTypeOID { get; set; }
        public string Address { get; set; }
        public string PostCode { get; set; }
        public string City { get; set; }
        public Nullable<long> CountryOID { get; set; }
        public Nullable<bool> Active { get; set; }
        #endregion

        #region Constructors
        /// <summary>
        /// see Business object constructor details
        /// </summary>
        public User()
            : base()
        {

        }
        /// <summary>
        /// see Business object constructor details
        /// </summary>

        public User(System.Data.Common.DbConnection conn)
            : base(conn)
        {

        }
        /// <summary>
        /// see Business object constructor details
        /// </summary>

        public User(System.Data.Common.DbTransaction trans)
            : base(trans)
        {

        }
        /// <summary>
        /// see Business object constructor details
        /// </summary>

        public User(System.Data.Common.DbConnection conn, System.Data.Common.DbTransaction trans)
            : base(conn: conn, trans: trans)
        {

        }
        /// <summary>
        /// see Business object constructor details
        /// </summary>

        public User(System.Data.IDataReader reader)
            : this()
        {
            SysResponse msg = new SysResponse();
            msg = this.LoadFromReader(reader);
            if (!msg.Success)
                throw new ApplicationException(msg.Message);
        }



        #endregion

        #region LoadFromReader
        
        /// <summary>
        /// Load onject from Reader
        /// </summary>
        /// <param name="reader"></param>
        /// <returns>sysResponse</returns>
        private SysResponse LoadFromReader(System.Data.IDataReader reader)
        {
            SysResponse msg = new SysResponse();
            try
            {

                int ordinalOID = reader.GetOrdinal("OID");
                if (!reader.IsDBNull(ordinalOID))
                    OID = reader.GetInt64(ordinalOID);
                int ordinalTitle = reader.GetOrdinal("Title");
                if (!reader.IsDBNull(ordinalTitle))
                    Title = reader.GetString(ordinalTitle);
                int ordinalFirstName = reader.GetOrdinal("FirstName");
                if (!reader.IsDBNull(ordinalFirstName))
                    FirstName = reader.GetString(ordinalFirstName);
                int ordinalMiddleName = reader.GetOrdinal("MiddleName");
                if (!reader.IsDBNull(ordinalMiddleName))
                    MiddleName = reader.GetString(ordinalMiddleName);
                int ordinalLastName = reader.GetOrdinal("LastName");
                if (!reader.IsDBNull(ordinalLastName))
                    LastName = reader.GetString(ordinalLastName);
                int ordinalEmail = reader.GetOrdinal("Email");
                Email = reader.GetString(ordinalEmail);
                int ordinalUserName = reader.GetOrdinal("UserName");
                if (!reader.IsDBNull(ordinalUserName))
                    UserName = reader.GetString(ordinalUserName);
                int ordinalPassword = reader.GetOrdinal("Password");
                if (!reader.IsDBNull(ordinalPassword))
                    Password = reader.GetString(ordinalPassword);
                int ordinalUerTypeOID = reader.GetOrdinal("UserTypeOID");
                if (!reader.IsDBNull(ordinalUerTypeOID))
                    UserTypeOID = reader.GetInt64(ordinalUerTypeOID);
                int ordinalAddress = reader.GetOrdinal("Address");
                if (!reader.IsDBNull(ordinalAddress))
                    Address = reader.GetString(ordinalAddress);
                int ordinalPostCode = reader.GetOrdinal("PostCode");
                if (!reader.IsDBNull(ordinalPostCode))
                    PostCode = reader.GetString(ordinalPostCode);
                int ordinalCity = reader.GetOrdinal("City");
                if (!reader.IsDBNull(ordinalCity))
                    City = reader.GetString(ordinalCity);
                int ordinalCountryOID = reader.GetOrdinal("CountryOID");
                if (!reader.IsDBNull(ordinalCountryOID))
                    CountryOID = reader.GetInt64(ordinalCountryOID);
                int ordinalActive = reader.GetOrdinal("Active");
                if (!reader.IsDBNull(ordinalActive))
                    Active = reader.GetBoolean(ordinalActive);

                IsNew = false;
                IsLoadedFromReader = true;

                msg.Success = true;

            }
            catch (Exception ex)
            {
                // here we should have some siignment utility
                // method to assign ex object rather message only.
                msg.Message = ex.Message;
            }
            return msg;
        }
        #endregion

        #region Save

        public SysResponse Save()
        {
            SysResponse msg = new SysResponse();
            System.Data.Common.DbCommand dbCommand = dbContext.GetStoredProcCommand(SP_SAVE);
            try
            {
                dbContext.AddParameter(dbCommand, "OID", System.Data.DbType.Int64, 
                  System.Data.ParameterDirection.InputOutput, 
                  "OID", System.Data.DataRowVersion.Default, OID);
                dbContext.AddInParameter(dbCommand, "Title", System.Data.DbType.String, Title);
                dbContext.AddInParameter(dbCommand, "FirstName", System.Data.DbType.String, FirstName);
                dbContext.AddInParameter(dbCommand, "MiddleName", System.Data.DbType.String, MiddleName);
                dbContext.AddInParameter(dbCommand, "LastName", System.Data.DbType.String, LastName);
                dbContext.AddInParameter(dbCommand, "Email", System.Data.DbType.String, Email);
                dbContext.AddInParameter(dbCommand, "UserName", System.Data.DbType.String, UserName);
                dbContext.AddInParameter(dbCommand, "Password", System.Data.DbType.String, Password);
                dbContext.AddInParameter(dbCommand, "UserTypeOID", System.Data.DbType.Int64, UserTypeOID);
                dbContext.AddInParameter(dbCommand, "Address", System.Data.DbType.String, Address);
                dbContext.AddInParameter(dbCommand, "PostCode", System.Data.DbType.String, PostCode);
                dbContext.AddInParameter(dbCommand, "City", System.Data.DbType.String, City);
                dbContext.AddInParameter(dbCommand, "CountryOID", System.Data.DbType.Int64, CountryOID);
                dbContext.AddInParameter(dbCommand, "Active", System.Data.DbType.String, Active);

                dbContext.ExecuteNonQuery(dbCommand);

                OID = long.Parse(dbContext.GetParameterValue(dbCommand, "OID").ToString());
            }
            catch (Exception ex)
            {
                msg.Message = ex.Message;
            }
            return msg;
        }
        #endregion

        #region Fetch
        public SysResponse Fetch(long id)
        {
            OID = id;
            object[] param = { id };

            SysResponse msg = new SysResponse();
            System.Data.IDataReader reader;

            if (UserExternalTransaction)
                reader = dbContext.ExecuteReader(Transaction, SP_FETCH, param);
            else
                reader = dbContext.ExecuteReader(SP_FETCH, param);
            try
            {
                if (reader.Read())
                {
                    msg = LoadFromReader(reader);
                    if (!msg.Success)
                        return msg;
                }

                msg.Success = true;
            }
            catch (Exception ex)
            {
                // here we should have some siignment utility method to assign ex object rather message only.
                msg.Message = ex.Message;

            }

            return msg;
        }
        #endregion

        #region FetchList

        public static SysResponse FetchList(ref UserCollection list)
        {
            return FetchList(null, ref list);
        }

        public static SysResponse FetchList(System.Data.Common.DbTransaction trans, ref UserCollection list)
        {
            Database db = DatabaseFactory.CreateDatabase();
            SysResponse msg = new SysResponse();
            System.Data.IDataReader reader;

            try
            {
                if (trans != null)
                    reader = db.ExecuteReader(trans, SP_FETCH_LIST);
                else
                    reader = db.ExecuteReader(SP_FETCH_LIST);

                list = new UserCollection();
                while (reader.Read())
                {
                    User newItem = new User(reader);
                    list.Add(newItem);
                }
            }
            catch (Exception ex)
            {
                msg.Message = ex.Message;
            }


            return msg;
        }
        #endregion

        #region Delete

        /// <summary>
        /// object level delete method
        /// </summary>
        /// <returns></returns>
        public SysResponse Delete()
        {
            SysResponse msg = new SysResponse();
            if (UserExternalTransaction)
            {
                msg = DeleteInternal(Transaction, OID);
            }
            else
            {
                msg = DeleteInternal(null, OID);
            }
            if (msg.Success)
                IsNew = true;
            return msg;
        }

        /// <summary>
        /// static delete method to be used with external transactions
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static SysResponse Delete(long id)
        {
            return DeleteInternal(null, id);
        }

        /// <summary>
        /// private static method to wrap local working process.
        /// </summary>
        /// <param name="trans"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private static SysResponse DeleteInternal(System.Data.Common.DbTransaction trans, long id)
        {
            Database db = DatabaseFactory.CreateDatabase();
            SysResponse msg = new SysResponse();
            object[] param = { id };

            try
            {
                // here we mioght have to check dependency and add template code
                if (trans != null)
                    db.ExecuteNonQuery(trans, SP_DELETE, param);
                else
                    db.ExecuteReader(SP_DELETE, param);

                msg.Success = true;

            }
            catch (Exception ex)
            {
                msg.Message = ex.Message;
            }

            return msg;
        }
        #endregion

        #region " Equals "

        /// <summary>
        /// This equals does not implement the IComparer rather ionly compare the OID of object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            User compareTo = (User)obj;
            if (this.OID != compareTo.OID)
                return false;
            return true;
        }

        #endregion

        #region "ShallowCopy"

        /// <summary>
        /// performs shallow copy
        /// </summary>
        /// <returns></returns>
        public User ShallowCopy()
        {
            return ShallowCopy(true);
        }

        /// <summary>
        ///  performs shallow copy and unhook the the object as well
        /// </summary>
        /// <param name="unhook"></param>
        /// <returns></returns>
        public User ShallowCopy(bool unhook)
        {
            User result = (User)this.MemberwiseClone();
            if (unhook)
            {
                result.Unhook();
            }
            return result;
        }

        #endregion
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication4.DAL.Classes
{
   public class UserCollection : List<User>
    {
       // add as many properties as we like to extend 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

WAQASGHAZANFAR
Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161205.3 | Last Updated 3 May 2013
Article Copyright 2013 by WAQASGHAZANFAR
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid