Click here to Skip to main content
15,892,537 members
Articles / Web Development / HTML

Windows and Web Generic Components

Rate me:
Please Sign up or sign in to vote.
4.08/5 (7 votes)
23 Jul 2008CPOL4 min read 27.4K   742   15  
A method to create Windows and Web components with the same interface
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Data;
using System.Reflection;
using Framework.baInterfaces;
using Framework.Lib;

namespace Framework.UI.baWebControls
{
    [ToolboxData("<{0}:baBindingManager runat=server></{0}:baBindingManager>")]
    public class baBindingManager : ObjectDataSource, IBindingManager, ITransactionState, IBindable
    {
        /// <summary>
        /// For web conbtrols, the DataRow of the current row needs to
        /// be serialized so that the binded controls can be linked to datarow
        /// </summary>
        #region SerializeableDataRow Internal Classes
        [Serializable]
        internal class SerializeableDataRow : ISerializable, IDictionary
        {
            private Hashtable RowValueCollection;
            private DataColumn[] primaryKeys=null;
            private Int16 DataColumnLen = 0;
            private const string guid = "B3C1005707884674981E92BB9133304E"; // This guid make variables unique in the serialized string

            #region this[object index]
            /// <summary>
            /// return the Current Rows value base 
            /// on column name defined as index
            /// </summary>
            /// <param name="index">Column name</param>
            /// <returns>the value of the current row for a column</returns>
            public object this[object index]
            {
                get
                {
                    return RowValueCollection[index];
                }
                set
                {
                    RowValueCollection[index] = value;
                }
            }
            #endregion

            #region DataColumn PrimaryKeys
            public DataColumn[] PrimaryKeys
            {
                get
                {
                    return primaryKeys;
                }
            }
            #endregion

            #region DataColumn PrimaryKey values
            public object[] PrimaryKeysValue
            {
                get
                {
                    try
                    {
                        object[] vals = new object[primaryKeys.Length];
                        for (int i = 0; i < primaryKeys.Length; i++)
                        {
                            vals[i] = RowValueCollection[primaryKeys[i].ToString()];
                        }
                        return vals;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }
            #endregion

            #region SerializeableDataRow(DataRow theDataRow) constructor
            public SerializeableDataRow(DataRow theDataRow)
            {
                try
                {
                    if (theDataRow != null)
                    {
                        primaryKeys = theDataRow.Table.PrimaryKey;
                        DataColumnLen = (Int16)primaryKeys.Length;

                        RowValueCollection = new Hashtable(theDataRow.Table.Columns.Count);
                        /// Copy DataRow to internal collection
                        foreach (DataColumn col in theDataRow.Table.Columns)
                        {
                            RowValueCollection[col.ColumnName] = theDataRow[col.ColumnName];
                        }
                    }
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            #endregion

            #region SerializeableDataRow(SerializationInfo info, StreamingContext context)
            public SerializeableDataRow(SerializationInfo info, StreamingContext context)
                : base()
            {
                try
                {
                    RowValueCollection = new Hashtable();

                    if (info.MemberCount > 0)
                    {
                        /// de-serialize Primary Key Columns
                        DataColumnLen = info.GetInt16("DataColumnLen" + guid);
                        string primaryKeysStr = info.GetString("PrimaryKeysStr" + guid);
                        primaryKeys = new DataColumn[DataColumnLen];
                        StringLib<DataColumn>.Str2Array(primaryKeys, primaryKeysStr);

                        /// De-serialize RowValueCollection
                        SerializationInfoEnumerator e = info.GetEnumerator();
                        while (e.MoveNext())
                        {
                            if (e.Name.IndexOf(guid) < 0)
                                RowValueCollection[e.Name] = info.GetValue(
                                    e.Name,
                                    e.ObjectType);
                        }
                    }
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            #endregion

            #region Clear Collection
            public void Clear()
            {
                RowValueCollection.Clear();
            }
            #endregion

            #region GetObjectData
            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                try
                {
                    if (RowValueCollection != null)
                    {
                        info.AddValue("DataColumnLen" + guid, DataColumnLen);
                        string primaryKeysStr = StringLib<DataColumn>.Array2Str(PrimaryKeys);
                        info.AddValue("PrimaryKeysStr" + guid, primaryKeysStr);

                        /// Serialize DataRow hash table
                        foreach (System.Collections.DictionaryEntry de in RowValueCollection)
                        {
                            info.AddValue((string)de.Key, de.Value);
                        }
                    }
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            #endregion

            #region IDictionary Members

            public void Add(object key, object value)
            {
                try
                {
                    RowValueCollection.Add(key, value);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            public bool Contains(object key)
            {
                try
                {
                    return RowValueCollection.Contains(key);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            public IDictionaryEnumerator GetEnumerator()
            {
                try
                {
                    return RowValueCollection.GetEnumerator();
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            public bool IsFixedSize
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.IsFixedSize;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            public bool IsReadOnly
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.IsReadOnly;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            public ICollection Keys
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.Keys;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            public void Remove(object key)
            {
                try
                {
                    RowValueCollection.Remove(key);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            public ICollection Values
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.Values;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            #endregion

            #region ICollection Members

            public void CopyTo(Array array, int index)
            {
                try
                {
                    RowValueCollection.CopyTo(array, index);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            public int Count
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.Count;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            public bool IsSynchronized
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.IsSynchronized;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            public object SyncRoot
            {
                get 
                {
                    try
                    {
                        return RowValueCollection.SyncRoot;
                    }
                    catch (Exception baExp)
                    {
                        throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                    }
                }
            }

            #endregion

            #region IEnumerable Members

            IEnumerator IEnumerable.GetEnumerator()
            {
                try
                {
                    return RowValueCollection.GetEnumerator();
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

            #endregion
        }
        #endregion

        #region private member variables
        private object oDataSource = null;
        #endregion

        #region IBindingManager TransactionStateChange event
        public event TransactionStateChangeEventHandler TransactionStateChange;
        protected void OnTransactionStateChange(object sender, TransactionStateChangeArgs Was, TransactionStateChangeArgs Will)
        {
            try
            {
                if (TransactionStateChange != null)
                {
                    TransactionStateChange(sender, Was, Will);
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region IBindingManager TransactionStateChanging event
        public event TransactionStateChangeEventHandler TransactionStateChanging;
        protected void OnTransactionStateChanging(object sender, TransactionStateChangeArgs Was, TransactionStateChangeArgs Will)
        {
            /// Do the Business related events (Database) first
            /// When the Changing Transaction event happens
            if ((Will.TransactionState == TransactionStateKind.Confirm) &&
                (Was.TransactionState == TransactionStateKind.Add))
            {
                OnAddConfirmed(sender, new BindingManagerArgs(this));
            }
            if ((Will.TransactionState == TransactionStateKind.Confirm) &&
                (Was.TransactionState == TransactionStateKind.Edit))
            {
                OnEditConfirmed(sender, new BindingManagerArgs(this));
            }
            if ((Will.TransactionState == TransactionStateKind.Confirm) &&
                (Was.TransactionState == TransactionStateKind.Delete))
            {
                OnDeleteConfirmed(sender, new BindingManagerArgs(this));
            }
            /// The Business related events happened
            /// So call the other components waiting 
            /// for this changing event
            if (TransactionStateChanging != null)
                TransactionStateChanging(sender, Was, Will);
        }
        #endregion

        #region IBindingManager TransactionStateChanged event
        public event TransactionStateChangeEventHandler TransactionStateChanged;
        protected void OnTransactionStateChanged(object sender, TransactionStateChangeArgs Was, TransactionStateChangeArgs Will)
        {
            try
            {
                if (TransactionStateChanged != null)
                    TransactionStateChanged(sender, Was, Will);
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region IBindingManager TransactionStateConfirmedEventHandler event
        public event TransactionStateConfirmedEventHandler AddConfirmed;
        protected void OnAddConfirmed(object sender, BindingManagerArgs e)
        {
            if (AddConfirmed != null)
                AddConfirmed(sender, e);
        }
        #endregion

        #region IBindingManager TransactionStateConfirmedEventHandler event
        public event TransactionStateConfirmedEventHandler DeleteConfirmed;
        protected void OnDeleteConfirmed(object sender, BindingManagerArgs e)
        {
            if (DeleteConfirmed != null)
                DeleteConfirmed(sender, e);
        }
        #endregion

        #region IBindingManager TransactionStateConfirmedEventHandler event
        public event TransactionStateConfirmedEventHandler EditConfirmed;
        protected void OnEditConfirmed(object sender, BindingManagerArgs e)
        {
            if (EditConfirmed != null)
                EditConfirmed(sender, e);
        }
        #endregion

        #region TableName
        public string TableName
        {
            get
            {
                return (string)ViewState["TableName"];
            }
            set
            {
                ViewState["TableName"] = value;
            }
        }
        #endregion TableName

        #region serializeableDataRow
        internal SerializeableDataRow serializeableDataRow
        {
            get
            {
                try
                {
                    if (TableName == null)
                        return null;
                    else
                        return (SerializeableDataRow)this.ViewState[TableName];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    this.ViewState[TableName] = value;
                    /// Reposition current row accuired
                    OnPositionChanged(new EventArgs());
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region int Count
        public int Count
        {
            get
            {
                DataTable dTbl = ((DataTable)oDataSource);
                if (dTbl == null)
                    return 0;
                else
                
                    return dTbl.Rows.Count;
            }
        }

        #endregion

        #region this[object index]
        /// <summary>
        /// return the Current Rows value base 
        /// on column name defined as index
        /// </summary>
        /// <param name="index">Column name</param>
        /// <returns>the value of the current row for a column</returns>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public object this[object columnName]
        {
            get
            {
                try
                {
                    if (serializeableDataRow == null)
                        return null;
                    else
                        return StringLib<object>.GetStringNull(serializeableDataRow[columnName]);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    if (serializeableDataRow != null)
                        serializeableDataRow[columnName] = value;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region Find: Set Current Position to founded Primary Key

        private bool bIfNotFoundMoveToLastRow=false;
        private bool IfNotFoundMoveToLastRow
        {
            get
            {
                return bIfNotFoundMoveToLastRow;
            }
            set
            {
                bIfNotFoundMoveToLastRow = value;
            }
        }

        public int Find(object key)
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                    return -1;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    if ((dTbl.Rows.Count > 0) && (dTbl.PrimaryKey.Length>0))
                    {
                        DataRow dRow = dTbl.Rows.Find(key);
                        if (dRow == null) // Row is didnt find
                        {
                            if(IfNotFoundMoveToLastRow)
                                dRow = dTbl.Rows[dTbl.Rows.Count - 1];
                            else
                                dRow = dTbl.Rows[0];
                        }
                        serializeableDataRow = InstanciateADataRow(oDataSource, dRow);
                        
                        return dTbl.Rows.IndexOf(dRow);
                    }
                    else
                        return -1;
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }

        private int Find(object[] key)
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                    return -1;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    if (dTbl.Rows.Count > 0 && key.Length>0)
                    {
                        DataRow dRow = dTbl.Rows.Find(key);
                        if (dRow == null) // Row is the last row
                        {
                            //dRow = dTbl.Rows[dTbl.Rows.Count - 1];
                            if (IfNotFoundMoveToLastRow)
                                dRow = dTbl.Rows[dTbl.Rows.Count - 1];
                            else
                                dRow = dTbl.Rows[0];
                        }
                        serializeableDataRow = InstanciateADataRow(oDataSource, dRow);
                        return dTbl.Rows.IndexOf(dRow);
                    }
                    else
                        return -1;
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region MoveLast()
        public void MoveLast()
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    DataRow dRow = dTbl.Rows[dTbl.Rows.Count - 1];
                    serializeableDataRow = InstanciateADataRow(oDataSource, dRow);
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region MoveFirst()
        public void MoveFirst()
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    DataRow dRow = dTbl.Rows[0];
                    serializeableDataRow = InstanciateADataRow(oDataSource, dRow);
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion 

        #region MovePrevious()
        public void MovePrevious()
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                    {
                        DataRow dRow = dTbl.Rows.Find(PrimaryKeysValue);
                        int idx = dTbl.Rows.IndexOf(dRow);
                        if ((dRow != null) && (idx>0))
                            serializeableDataRow = InstanciateADataRow(oDataSource, dTbl.Rows[idx-1]);
                    }
                    
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region MoveNext()
        public void MoveNext()
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRow = null;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                    {
                        DataRow dRow = dTbl.Rows.Find(PrimaryKeysValue);
                        int idx = dTbl.Rows.IndexOf(dRow);
                        if ((dRow != null) && (idx > 0))
                            serializeableDataRow = InstanciateADataRow(oDataSource, dTbl.Rows[idx + 1]);
                    }

                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion
        
        #region private Type GetType(string typeName)
        /// <summary>
        /// Find a string name of a Type in current executable
        /// and its referenced assemblies and return its Type 
        /// </summary>
        /// <param name="typeName">Name of Type to be search for</param>
        /// <returns>Returns the type of typeName class</returns>
        private Type GetType(string typeName)
        {
            Type typeNameType = null;

            // First check if current assembly has typeName type
            typeNameType = Type.GetType(typeName);
            if (typeNameType != null)
                return typeNameType;
            // Then check if typeName type is in App_Code assembly!
            typeNameType = Type.GetType(typeName + ", App_Code");
            if (typeNameType != null)
                return typeNameType;

            // Try to find the type name in its referencing names in its name
            string[] tokens = typeName.Split(new char[1]{'.'});
            string refLib = "";
            foreach (string token in tokens)
            {
                typeNameType = Type.GetType(typeName + "," + refLib+token);
                if (typeNameType != null)
                    return typeNameType;
                refLib += token+".";
            }

            // Now search all assemblies being used in current executing assembly
            // To find the typeName type in any one of them
            // AssemblyName[] assemblyNames = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
            AssemblyName[] assemblyNames = this.Page.GetType().Assembly.GetReferencedAssemblies();
            foreach (AssemblyName assemblyName in assemblyNames)
            {
                typeNameType = Type.GetType(typeName + "," + assemblyName.ToString());
                if (typeNameType != null)
                    return typeNameType;
            }

            // The assembly was not found, so return null
            return typeNameType;
        }
        #endregion

        #region DataTable CreateTableFromTypeName()
        private DataTable CreateTableFromTypeName()
        {
            Type tblType = this.GetType(this.TypeName);
            if (tblType == null)
                return null;
            else
            {
                MethodInfo selectMethodinfo = tblType.GetMethod(this.SelectMethod);

                DataTable tbl = (DataTable)Activator.CreateInstance(selectMethodinfo.ReturnType);
                return tbl;
            }
        }
        #endregion

        #region override void OnInit(EventArgs e)
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Selecting += new ObjectDataSourceSelectingEventHandler(baBindingManager_Selecting);
            DataTable dyamicTable = CreateTableFromTypeName();
            if (dyamicTable != null)
                DataSource = CreateTableFromTypeName();
        }
        #endregion

        #region void baBindingManager_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        void baBindingManager_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.Cancel = true;
        }
        #endregion

        #region DataSource
        //[AttributeProvider(typeof(IListSource))]
        [ThemeableAttribute(false)]
        [BindableAttribute(true)]
        [AttributeProvider(typeof(System.Data.DataTable))]
        public object DataSource
        {
            get
            {
                return oDataSource;
            }
            set
            {
                try
                {
                    /// If DataRow is already assigned do not create 
                    /// SerializeableDataRow object
                    if ((serializeableDataRow == null) && (value.GetType().BaseType == typeof(System.Data.DataTable)))
                    {
                        if (((DataTable)value).Rows.Count > 0)
                            serializeableDataRow = InstanciateADataRow(value, ((DataTable)value).Rows[0]);
                        else
                        {
                            oDataSource = value;
                            DataRow AnEmptyRow= NewRow();
                            serializeableDataRow = InstanciateADataRow(oDataSource, AnEmptyRow);

                            // Create an empty Original value that contains old DataRow which are null
                            InitOriginal(AnEmptyRow);

                            PrimaryKeysValue = null;
                        }
                    }
                    
                    oDataSource = value;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region void ClearDatasource()
        public void ClearDatasource()
        {
            if ((DataSource!=null) && (DataSource.GetType().BaseType == typeof(System.Data.DataTable)))
            {
                if (((DataTable)DataSource).Rows.Count > 0)
                {
                    ((DataTable)DataSource).Clear();
                    //serializeableDataRow.Clear();
                }
            }
        }
        #endregion

        #region InstanciateADataRow(object tbl, DataRow row)
        /// <summary>
        /// Instanciate a serializeableDataRow 
        /// object that points to a DataRow object
        /// </summary>
        /// <param name="tbl">the data table object </param>
        /// <param name="row">the default row in table</param>
        /// <returns>an instance of SerializeableDataRow</returns>
        private SerializeableDataRow InstanciateADataRow(object tbl, DataRow row)
        {
            try
            {
                /// If the datasource object is a DataTable
                /// then if current row was null then
                ///     set the current row to first row
                if (tbl.GetType().BaseType == typeof(System.Data.DataTable))
                {
                    if (TableName==null)
                        TableName = ((DataTable)tbl).TableName;
                    /// Set CurrentRow to the first row
                    SerializeableDataRow sd = new SerializeableDataRow(row);

                    return sd;
                }
                else
                    return null;
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region TransactionStateKind transactionState
        private TransactionStateKind transactionState
        {
            get
            {
                try
                {
                    if (ViewState["TransactionStateViewState"] == null)
                        return TransactionStateKind.Null;
                    else
                        return (TransactionStateKind)ViewState["TransactionStateViewState"];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    if ((TransactionStateKind)value == TransactionStateKind.Null)
                        ViewState["TransactionStateViewState"] = TransactionStateKind.Null;
                    else
                        ViewState["TransactionStateViewState"] = value;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region void SetRowData(DataRow rw)
        private void SetRowData(DataRow rw)
        {
            try
            {
                if (serializeableDataRow!=null)
                foreach (DictionaryEntry de in serializeableDataRow)
                {
                    if(!rw.Table.Columns[(string)de.Key].ReadOnly)
                        rw[(string)de.Key] = de.Value;
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region PreCheck(TransactionStateKind val, TransactionStateKind VSVal)
        private TransactionStateKind ts = TransactionStateKind.Null;
        private bool PreCheck(TransactionStateKind val, TransactionStateKind VSVal)
        {
            try
            {
                bool A, B;
                A = VSVal == TransactionStateKind.Null;
                B = ts == TransactionStateKind.Null;
                return (A && B) || (!A && !B);
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region GetRowPrimaryKeysValue(DataRow dr)
        private void GetRowPrimaryKeysValue(DataRow rw)
        {
            foreach (System.Data.DataColumn IDcol in serializeableDataRow.PrimaryKeys)
            {
                bool ro;
                if (IDcol != null)
                {
                    ro = IDcol.ReadOnly;
                    try
                    {
                        IDcol.ReadOnly = false;
                        if (serializeableDataRow[IDcol.ToString()]!=null)
                            rw[IDcol.ToString()] = serializeableDataRow[IDcol.ToString()];
                    }
                    finally
                    {
                        IDcol.ReadOnly = ro;
                    }
                }
            }
        }
        #endregion

        #region TransactionState
        public TransactionStateKind TransactionState
        {
            get
            {
                return transactionState;
            }
            set
            {
                TransactionStateChangeArgs willBe = new TransactionStateChangeArgs(value);
                try
                {
                    if (PreCheck(willBe.TransactionState, transactionState))
                    {
                        //OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                        OnTransactionStateChange(this, new TransactionStateChangeArgs(transactionState), willBe);
                        #region Switch Case
                        /// Set the state of the BindingManager
                        switch (value)
                        {
                            /// If state is Add then clear all binded controls
                            case TransactionStateKind.Add:
                                {
                                    if (serializeableDataRow != null)
                                    {
                                        PrimaryKeysValue = serializeableDataRow.PrimaryKeysValue;
                                        if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                            FindOriginal(PrimaryKeysValue);
                                        serializeableDataRow.Clear();
                                    }
                                    //OnTransactionStateChange(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    break;
                                }
                            /// If state is Edit or Delete then just save the old row position
                            case TransactionStateKind.Edit:
                            case TransactionStateKind.Delete:
                                {
                                    if (serializeableDataRow != null)
                                    {
                                        PrimaryKeysValue = serializeableDataRow.PrimaryKeysValue;
                                        if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                            FindOriginal(PrimaryKeysValue);
                                    }
                                    OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    break;
                                }
                            /// If state is Initial then return to previous state
                            case TransactionStateKind.Null:
                                {
                                    /// April 25, 06:
                                    /// When the Transaction state should be NULL
                                    /// then nothing should happen when the table is empty
                                    //PrimaryKeysValue = serializeableDataRow.PrimaryKeysValue;
                                    //if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                    //    FindOriginal(PrimaryKeysValue); 
                                    //if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                    //    Find(PrimaryKeysValue); 
                                    OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    break;
                                }
                            case TransactionStateKind.EmptyDataSource:
                            case TransactionStateKind.EditOnly:
                            case TransactionStateKind.AddEditOnly:
                            case TransactionStateKind.SearchOnly:
                            case TransactionStateKind.Initial:
                                {
                                    if (!((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0) && (Find(PrimaryKeysValue) >= 0)) 
                                        && willBe.TransactionState!= TransactionStateKind.Null)
                                        if ((serializeableDataRow != null) && (((DataTable)DataSource).Rows.Count <= 0))
                                        {
                                            // June 16, 06
                                            //value = TransactionStateKind.EmptyDataSource;
                                            willBe.TransactionState = TransactionStateKind.EmptyDataSource;
                                            serializeableDataRow.Clear();
                                        }
                                    OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    break;
                                }
                            case TransactionStateKind.Confirm:
                                {
                                    OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    switch (transactionState)
                                    {
                                        case TransactionStateKind.Add:
                                            {
                                                if (DataSource.GetType().BaseType == typeof(System.Data.DataTable))
                                                {
                                                    DataRow rw = NewRow();
                                                    // Remove the constraints, it will be back on next post back!
                                                    if(rw.Table.DataSet!=null)
                                                        rw.Table.DataSet.EnforceConstraints = false;
                                                    GetRowPrimaryKeysValue(rw);
                                                    rw.Table.Rows.Add(rw);
                                                    MoveLast();
                                                }
                                                break;
                                            }
                                        case TransactionStateKind.Delete:
                                            {
                                                if (DataSource.GetType().BaseType == typeof(System.Data.DataTable))
                                                {
                                                    DataTable tbl = (DataTable)DataSource;
                                                    DataRow rw = tbl.Rows.Find(PrimaryKeysValue);
                                                    tbl.Rows.Remove(rw);
                                                    if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                                        if (Find(PrimaryKeysValue) < 0)
                                                            if (serializeableDataRow != null)
                                                            {
                                                                // June 16, 06
                                                                //value = TransactionStateKind.EmptyDataSource;
                                                                willBe.TransactionState = TransactionStateKind.EmptyDataSource;
                                                                serializeableDataRow.Clear();
                                                                serializeableDataRowOriginal.Clear();
                                                                InitOriginal(NewRow());
                                                                //serializeableDataRowOriginal = InstanciateADataRow(oDataSource, NewRow());
                                                                //serializeableDataRowOriginal = null;
                                                            }
                                                }
                                                break;
                                            }
                                        case TransactionStateKind.Edit:
                                            {
                                                if (DataSource.GetType().BaseType == typeof(System.Data.DataTable))
                                                {
                                                    DataTable tbl = (DataTable)DataSource;
                                                    DataRow rw = tbl.Rows.Find(PrimaryKeysValue);
                                                    SetRowData(rw);
                                                    if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                                        Find(PrimaryKeysValue);
                                                }
                                                break;
                                            }
                                        case TransactionStateKind.Null:
                                        case TransactionStateKind.EmptyDataSource:
                                        case TransactionStateKind.EditOnly:
                                        case TransactionStateKind.AddEditOnly:
                                        case TransactionStateKind.SearchOnly:
                                        case TransactionStateKind.Initial:
                                            {
                                                if ((PrimaryKeysValue != null) && (PrimaryKeysValue.Length > 0))
                                                {
                                                    Find(PrimaryKeysValue);
                                                }
                                                break;
                                            }
                                    }
                                    //OnTransactionStateChanging(this, new TransactionStateChangeArgs(transactionState), new TransactionStateChangeArgs(value));
                                    break;
                                }
                        }
                        #endregion
                        //transactionState = value;
                        transactionState = willBe.TransactionState;
                        OnTransactionStateChanged(this, new TransactionStateChangeArgs(transactionState), willBe);
                    }
                    else
                        if (ts != TransactionStateKind.Null)
                            //transactionState = value;
                            transactionState = willBe.TransactionState;
                    ts = willBe.TransactionState;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region DataRow NewRow()
        private DataRow NewRow()
        {
            try
            {
                DataTable tbl;
                DataRow rw;
                tbl = (DataTable)DataSource;
                rw = tbl.NewRow();
                SetRowData(rw);
                return rw;
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region PrimaryKeysValue
        /// <summary>
        /// Get/Set primary keys value to be used 
        /// in find function of DataTable object
        /// </summary>
        private const string Guid = "8D0A4c9e808F9F452C1A47A6";
        public object[] PrimaryKeysValue
        {
            get
            {
                try
                {
                    if (this.ViewState["PrimaryKeysValue" + Guid] == null)
                        return null;
                    else
                    {
                        string str = this.ViewState["PrimaryKeysValue" + Guid].ToString();
                        object[] obj = null;
                        obj = StringLib<object>.Str2Array(obj, str);
                        return obj;
                    }
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    if (value == null)
                        this.ViewState["PrimaryKeysValue" + Guid] = null;
                    else
                        this.ViewState["PrimaryKeysValue" + Guid] = StringLib<object>.Array2Str(value);
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }

        }
        #endregion

        #region Original value before change
        public IDictionary Original
        {
            get
            {
                return serializeableDataRowOriginal;
            }
        }
        #endregion

        #region serializeableDataRowOriginal
        internal SerializeableDataRow serializeableDataRowOriginal
        {
            get
            {
                try
                {
                    if (TableName == null)
                        return null;
                    else
                        return (SerializeableDataRow)this.ViewState[TableName + "Original"];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    this.ViewState[TableName + "Original"] = value;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }

        internal int FindOriginal(object[] key)
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRowOriginal = null;
                    return -1;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    DataRow dRow = dTbl.Rows.Find(key);
                    serializeableDataRowOriginal = InstanciateADataRow(oDataSource, dRow);
                    return dTbl.Rows.IndexOf(dRow);
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }

        internal void InitOriginal(DataRow InitByRow)
        {
            try
            {
                if (oDataSource == null)
                {
                    serializeableDataRowOriginal = null;
                }
                else
                {
                    serializeableDataRowOriginal = InstanciateADataRow(oDataSource, InitByRow);
                    serializeableDataRow.Clear();
                    serializeableDataRowOriginal.Clear();
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region PositionChanged Event
        public event EventHandler PositionChanged;
        protected void OnPositionChanged(EventArgs e)
        {
            if (PositionChanged != null)
            {
                PositionChanged(this, e);
            }
            PrimaryKeysValue = serializeableDataRow.PrimaryKeysValue;
        }
        #endregion

        #region Filter
        public string Filter
        {
            get
            {
                return (string)ViewState["sTableName"];
            }
            set
            {
                ViewState["sTableName"] = value;
            }
        }
        #endregion

        #region IBindingManager FetchDataEventHandler event
        public event FetchDataEventHandler FetchData;
        protected void OnFetchData(object sender, BindingManagerArgs e)
        {
            if (FetchData != null)
                FetchData(sender, e);
        }
        #endregion

        #region void DoFetchData()
        public void DoFetchData()
        {
            OnFetchData(this, new BindingManagerArgs(this));
        }
        #endregion 

        #region void DataBind()
        public override void DataBind()
        {
            base.DataBind();
            if (serializeableDataRow != null)
            {
                if (PrimaryKeysValue == null && this.Count > 0)
                    this.MoveFirst();
                else
                    if ((serializeableDataRow.PrimaryKeysValue[0] == null) && (TransactionState == TransactionStateKind.Initial))
                    {
                        Find(PrimaryKeysValue);
                    }
            }
        }
        #endregion

        #region bool Exist(object key)
        public bool Exist(object key)
        {
            try
            {
                if (oDataSource == null)
                {
                    return false;
                }
                else
                {
                    DataTable dTbl = ((DataTable)oDataSource);
                    if ((dTbl.Rows.Count > 0) && (dTbl.PrimaryKey.Length > 0))
                    {
                        DataRow dRow = dTbl.Rows.Find(key);
                        if (dRow == null) // Row is didnt find
                        {
                            return false;
                        }
                        else
                            return true;
                    }
                    else
                        return false;
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
        }
        #endregion

        #region IsEmpty
        public bool IsEmpty
        {
            get
            {
                DataTable dTbl = ((DataTable)oDataSource);
                if (dTbl == null || dTbl.Rows == null || dTbl.Rows.Count<=0)
                    return true;
                else
                    return false;
            }
        }
        #endregion

        #region Save/Restore old row values
        public void SaveRowData(IDictionary storage)
        {
            /*
            try
            {
                foreach (DataColumn col in ((DataTable)oDataSource).Columns)
                {
                    storage[col.ColumnName] = this[col.ColumnName];
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
            /**/
        }

        public void RestoreRowData(IDictionary storage)
        {
            /*
            try
            {
                foreach (DataColumn col in ((DataTable)oDataSource).Columns)
                {
                    this[col.ColumnName] = storage[col.ColumnName];
                }
            }
            catch (Exception baExp)
            {
                throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
            }
            /**/
        }
        #endregion

        #region Old transaction states
        private bool bEnabled
        {
            get
            {
                return bool.Parse( this.ViewState["bEnabled"].ToString() );
            }
            set
            {
                this.ViewState["bEnabled"] = value;
            }
        }

        private TransactionStateKind OldEnableDisableTransactionState
        {
            get
            {
                try
                {
                    if (ViewState["OldEDTS"] == null)
                        return TransactionStateKind.Null;
                    else
                        return (TransactionStateKind)ViewState["OldEDTS"];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    if ((TransactionStateKind)value == TransactionStateKind.Null)
                        ViewState["OldEDTS"] = TransactionStateKind.Null;
                    else
                        ViewState["OldEDTS"] = value;
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region bool Enabled
        public bool Enabled
        {
            get
            {
                return bEnabled;
            }
            set
            {
                bEnabled = value;
                if (bEnabled)  // If enabled
                {
                    if (OldEnableDisableTransactionState != TransactionStateKind.Null)
                    {
                        /// Apply the old state to the binded controls
                        OnTransactionStateChanged(this, new TransactionStateChangeArgs(TransactionStateKind.Null),
                            new TransactionStateChangeArgs(OldEnableDisableTransactionState));
                        //OnTransactionStateChanging(this, new TransactionStateChangeArgs(TransactionStateKind.Null),
                        //    new TransactionStateChangeArgs(OldEnableDisableTransactionState));
                        OldEnableDisableTransactionState = TransactionStateKind.Null;
                    }
                }
                else // If disabled
                {
                    if (OldEnableDisableTransactionState == TransactionStateKind.Null)
                    {
                        OldEnableDisableTransactionState = TransactionState;
                        /// Apply the new state to the binded controls
                        OnTransactionStateChanged(this, new TransactionStateChangeArgs(TransactionState),
                            new TransactionStateChangeArgs(TransactionStateKind.Null));
                        //OnTransactionStateChanging(this, new TransactionStateChangeArgs(TransactionState),
                        //    new TransactionStateChangeArgs(TransactionStateKind.Null));
                    }
                }
            }
        }
        #endregion

        #region void Refresh()
        public void Refresh()
        {
            this.TransactionState = transactionState;
        }
        #endregion

        #region DefaultTransactionState
        public TransactionStateKind DefaultTransactionState
        {
            get
            {
                try
                {
                    if (ViewState["_defaultTransactionState"] == null)
                        return TransactionStateKind.Null;
                    else
                        return (TransactionStateKind)ViewState["_defaultTransactionState"];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
            set
            {
                try
                {
                    if ((TransactionStateKind)value == TransactionStateKind.Null)
                        ViewState["_defaultTransactionState"] = TransactionStateKind.Null;
                    else
                        ViewState["_defaultTransactionState"] = value;
                    //this.TransactionState = (TransactionStateKind)ViewState["_defaultTransactionState"];
                }
                catch (Exception baExp)
                {
                    throw new baException(baExp, System.Reflection.MethodBase.GetCurrentMethod());
                }
            }
        }
        #endregion

        #region IBindable  Bind()
        public void Bind()
        {
            // Fire the Binded Event
            OnBinded(this, new EventArgs());
            TransactionState = DefaultTransactionState;
        }
        #endregion

        #region IBindable  Binded event
        public event EventHandler Binded;
        protected void OnBinded(object sender, EventArgs e)
        {
            if (Binded != null)
                Binded(sender, e);
        }
        #endregion

        #region int Position
        /// <summary>
        /// Gets or sets the index of the current item in the underlying list. 
        /// </summary>
        public int Position
        {
            get
            {
                return -1;
            }
            set
            {

            }
        }
        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.DesignMode)
                writer.Write("<b>Binding Manager:</b>" + this.ID);
            else
                base.Render(writer);
        }
    }
}

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)


Written By
Software Developer (Senior)
Canada Canada
Software development experience since 1993

Skills
- Programming Languages: C# .NET, Delphi, C++, Java and VB
- Development Methodologies (SDLC): RUP, Scrum and XP
- Database: SQL server, Oracle, Apollo database and MS Access.

Educations & Certificates
- Microsoft® Certified Professional (MCP)
- Sun® Certified Java2 Programmer
- B.S. in computer science

Comments and Discussions