Click here to Skip to main content
15,896,111 members
Articles / Programming Languages / C#

Custom DataBindable BusinessObjects and The Typed DataSet

Rate me:
Please Sign up or sign in to vote.
4.80/5 (36 votes)
3 Jan 200716 min read 149.8K   2K   147  
An article about Custom Businessobjects in conjunction with the DataSet to Retrieve Data
using System;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using DCAF.DataLayer;


namespace DCAF.BusinessLayer
{
    public class CustomerBO : Publisher
    {
        private ObjectChangedListener m_listener = new ObjectChangedListener();
        private string m_CustomerId;
        private string m_CompanyName;
        private List<OrderBO> m_Orders = new List<OrderBO>();
        private CustomerOrderTDS m_dataContainer = new CustomerOrderTDS();


        public CustomerBO()
        {
            this.RegisterListener<IEventListener>(m_listener);
        }

        public string CustomerId
        {
            get { return m_CustomerId; }
            set 
            { 
                m_CustomerId = value;
                NotifyListeners();
            }
        }
        public string CompanyName
        {
            get { return m_CompanyName; }
            set 
            { 
                m_CompanyName = value;
                NotifyListeners();
            }
        }

        public List<OrderBO> Orders
        {
            get { return m_Orders; }
        }


        public void SyncroOrderID(List<OrderBO> p_changedOrders)
        {
            
            int currentChangedOrderIndex = 0;
            string oldCustomerID = string.Empty;

            while (currentChangedOrderIndex < p_changedOrders.Count)
            {
                //--- Get Break By ID
                oldCustomerID = p_changedOrders[currentChangedOrderIndex].Customer.CustomerId;

                //--- First Count Number of changed orders for current Customer
                int numChangedOrdersForCurrentCustomer = 0;
                foreach (OrderBO order in p_changedOrders)
                {
                    if (order.Customer.CustomerId == oldCustomerID)
                    {
                        numChangedOrdersForCurrentCustomer++;
                    }
                }

                //--- Get Appropriate Records in the DataContainer
                BindingSource orderBindingSource = new BindingSource(m_dataContainer, m_dataContainer.Orders.TableName);
                orderBindingSource.Filter = string.Format("CustomerID = '{0}'", oldCustomerID);
                orderBindingSource.Sort = "OrderID ASC";

                //--- Set Pointer for current container to the newly added rows
                int currentDataContainerOrderIndex = orderBindingSource.Count - numChangedOrdersForCurrentCustomer;

                while (p_changedOrders[currentChangedOrderIndex].Customer.CustomerId == oldCustomerID)
                {

                    DataRowView drv = (DataRowView)orderBindingSource[currentDataContainerOrderIndex];
                    
                    //--- Only update New Added Records
                    if (p_changedOrders[currentChangedOrderIndex].IsNew)
                    {
                        p_changedOrders[currentChangedOrderIndex].OrderId = (int)drv.Row[m_dataContainer.Orders.OrderIDColumn.ColumnName];
                    }
                    
                    currentChangedOrderIndex++;
                    currentDataContainerOrderIndex++;

                    if (currentChangedOrderIndex == p_changedOrders.Count)
                    {
                        break;
                    }

                    
                }

            }

        }

        public int GetLastOrderID()
        {
            if (m_dataContainer == null)
            {
                return 0;
            }
            else
            {
                BindingSource orderBindingSource = new BindingSource(m_dataContainer, m_dataContainer.Orders.TableName);
                orderBindingSource.Filter = string.Empty;
                orderBindingSource.Sort = "OrderID DESC";
                
                if (orderBindingSource == null)
                {
                    return 0;
                }
                else
                {
                    if (orderBindingSource.Count == 0)
                    {
                        return 0;
                    }
                    else
                    {
                        
                        System.Data.DataRowView drv = (System.Data.DataRowView)orderBindingSource[0];

                        int lastOrderID = 0;
                        bool converted = int.TryParse(drv.Row[m_dataContainer.Orders.OrderIDColumn.ColumnName].ToString(), out lastOrderID);

                        if (converted)
                            return lastOrderID;

                        return 0;
                        
                    }

                }
            }
        }

        public List<CustomerBO> GetCustomerOrders()
        {
            //--- Create the DataService
            CustomerOrderService dataService = new CustomerOrderService();
            
            
            
            //--- Clear the DataContainer for Customers and Orders retrieval
            m_dataContainer.Clear();
            

            //--- Get the Data from the DataService into the DataContainer
            m_dataContainer.Merge(dataService.GetCustomerOrders());
            
            
            //--- Create a CustomerObject List to hold the Customers
            List<CustomerBO> custList = new List<CustomerBO>();

            
            //--- Loop through the CustomerData from our DataContainer
            foreach (CustomerOrderTDS.CustomersRow custRow in m_dataContainer.Customers.Rows)
            {
                
                //--- Create a Customer Object Instance
                CustomerBO customer = new CustomerBO();

                
                //--- Map the Relational data to Object properties for Customer
                ORM.RelationalToObject(customer, custRow);
                
               
                //--- Select the Related Orders of the Customer
                CustomerOrderTDS.OrdersRow[] orderRows = (CustomerOrderTDS.OrdersRow[])custRow.GetChildRows("FK_Orders_Customers");

                //--- Loop through the related OrderData for the Current Customer
                int numOrder = 0;
                foreach (CustomerOrderTDS.OrdersRow orderRow in orderRows)
                {
                    numOrder++;

                    //--- Create an Order Object Instance
                    OrderBO order = new OrderBO();

                    //--- Map the Relational data to Object properties for Order
                    ORM.RelationalToObject(order, orderRow);
                    
                    //--- Add the Customer Reference to the Order
                    order.Customer = customer;
                    
                    order.ProductName = string.Format("Product {0}-{1}", order.OrderId, numOrder);

                    order.Initializing = false;
                    
                    //--- Relate the Order to The Current Customer
                    customer.Orders.Add(order);
                    
                }
                

                customer.Initializing = false;

                //--- Add the Customer to the CustomerList
                custList.Add(customer);
                

            }


            return custList;
        }

        public int SaveCustomerOrders(List<CustomerBO> p_addedOrModifiedCustomers, List<CustomerBO> p_deletedCustomers, List<OrderBO> p_AddedOrModifiedorders, List<OrderBO> p_deletedOrders)
        {
                       
            //--- Create the Service to update the Data
            CustomerOrderService dataService = new CustomerOrderService();


            //--------------------------------------------------------
            //--- Step 1 : Add Deleted Customer Object Information ---
            //--------------------------------------------------------

            if (p_deletedCustomers != null)
            {
                foreach (CustomerBO deletedCustomerObject in p_deletedCustomers)
                {
                    
                    //--- Create New CustomerRow to Hold Reference to the Deleted CustomerRow
                    CustomerOrderTDS.CustomersRow deletedCustomerRow = m_dataContainer.Customers.NewCustomersRow();
                    
                    //--- Check if Row Exists in Our DataContainer
                    deletedCustomerRow = m_dataContainer.Customers.FindByCustomerID(deletedCustomerObject.CustomerId);

                    
                    //--- Set RowState to Delete in our DataContainer
                    if (deletedCustomerRow != null)
                    {
                        deletedCustomerRow.Delete();
                    }
                    

                }

            }

            
            //--------------------------------------------------------
            //--- Step 2 : Add Deleted Order Object Information    ---
            //--------------------------------------------------------

            if (p_deletedOrders != null)
            {
                foreach (OrderBO deletedOrderObject in p_deletedOrders)
                {
                    //--- Create a New OrderRow to Hold Reference to the Deleted OrderRow
                    CustomerOrderTDS.OrdersRow deletedOrderRow = m_dataContainer.Orders.NewOrdersRow();

                    //--- Check if Row Exists in Our DataContainer
                    deletedOrderRow = m_dataContainer.Orders.FindByOrderID(deletedOrderObject.OrderId);

                    //--- Set RowState to Delete in our DataContainer
                    if (deletedOrderRow != null)
                    {
                        deletedOrderRow.Delete();
                    }
                }

            }

            

            //-------------------------------------------------------------
            //--- Step 3 : Add New/Modified Customer Object Information ---
            //-------------------------------------------------------------

            if (p_addedOrModifiedCustomers != null)
            {
                foreach (CustomerBO addedOrModifiedCustomerObject in p_addedOrModifiedCustomers)
                {
                    
                    //--- First Check If Current Customer Object is a New or Modified Object in our DataContainer
                    if (addedOrModifiedCustomerObject.IsNew)
                    {
                        //--- Add a New CustomerRow to Our DataContainer.Customer Table
                        CustomerOrderTDS.CustomersRow newCustomerRow = m_dataContainer.Customers.NewCustomersRow();

                        //--- Map object properties to rowcolumns
                        ORM.ObjectToRelational(addedOrModifiedCustomerObject, newCustomerRow);

                        //--- Add the New Customer Row to Our DataContainer
                        m_dataContainer.Customers.AddCustomersRow(newCustomerRow);
                    }
                    else
                    {
                        //--- Get Modified Row Information
                        CustomerOrderTDS.CustomersRow modifiedCustomerRow = m_dataContainer.Customers.NewCustomersRow();

                        //--- Map object properties to rowcolumns
                        ORM.ObjectToRelational(addedOrModifiedCustomerObject, modifiedCustomerRow);

                        if (modifiedCustomerRow != null)
                        {
                            //--- Search modified Row in DataContainer
                            CustomerOrderTDS.CustomersRow customerRowToModify = m_dataContainer.Customers.FindByCustomerID(modifiedCustomerRow.CustomerID);

                            //--- Map Changed Data, RowState will be set to True for our DataContainer.Customer Row !
                            if (customerRowToModify != null)
                            {
                                for (int i = 0; i < m_dataContainer.Customers.Columns.Count; i++)
                                {
                                    customerRowToModify[i] = modifiedCustomerRow[i];
                                }
                            }

                        }
                        

                    }
                     
                }
            }

            
            
            //------------------------------------------------------------
            //--- Step 4 : Add New/Modified Order Object Information   ---
            //------------------------------------------------------------

            if (p_AddedOrModifiedorders != null)
            {
                foreach (OrderBO addedOrModifiedOrderObject in p_AddedOrModifiedorders)
                {
                    //--- First Check if Current Order is a New or Modified object in our DataContainer
                    if (addedOrModifiedOrderObject.IsNew)
                    {
                        //--- Add a New OrderRow to Our DataContainer.Order Table
                        CustomerOrderTDS.OrdersRow newOrderRow = m_dataContainer.Orders.NewOrdersRow();

                        //--- Map object properties to rowcolumns
                        ORM.ObjectToRelational(addedOrModifiedOrderObject, newOrderRow);

                        //--- Map Foreign Key for Customers
                        newOrderRow.CustomerID = addedOrModifiedOrderObject.Customer.CustomerId;

                        //--- Add the New Order Row to Our DataContainer
                        m_dataContainer.Orders.AddOrdersRow(newOrderRow);
                    }
                    else
                    {
                        //--- Get Modified Row Information
                        CustomerOrderTDS.OrdersRow modifiedOrderRow = m_dataContainer.Orders.NewOrdersRow();

                        //--- Map object properties to rowcolumns
                        ORM.ObjectToRelational(addedOrModifiedOrderObject, modifiedOrderRow);

                        if (modifiedOrderRow != null)
                        {
                            //--- Search Modified Row in DataContainer
                            CustomerOrderTDS.OrdersRow orderRowToModify = m_dataContainer.Orders.FindByOrderID(modifiedOrderRow.OrderID);

                            //--- Map Changed Data, RowState will be set to True for our DataContainer.Order Row !
                            if (orderRowToModify != null)
                            {
                                
                                for (int i = 0; i < m_dataContainer.Orders.Columns.Count; i++)
                                {
                                    System.Data.DataColumn column = orderRowToModify.Table.Columns[i];

                                    if (!column.ReadOnly)
                                    {
                                        orderRowToModify[i] = modifiedOrderRow[i];
                                    }

                                }

                                //--- Re-Map Foreign Key for Customer
                                orderRowToModify.CustomerID = addedOrModifiedOrderObject.Customer.CustomerId;

                              
                            }
                        }


                    }

                }
            }

            //--- Update through the DataService class
            if(m_dataContainer.HasChanges())
            {
                bool updateOK = true;

                try
                {
                    return dataService.SaveWithTransaction(m_dataContainer,false);

                }
                catch (DBConcurrencyException dbconcEx)
                {
                    //--- DbConcurrency Occured, ask User either to Persist his changes or reload from server

                    string message = dbconcEx.Message + "\r\n";
                    message += "Persist changes to the DataBase [Yes]\r\n" +
                               "Reload the changed Data from the Server [No]";
                    string caption = "DbConcurrency !";
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    DialogResult result;

                    // Displays the MessageBox.

                    result = MessageBox.Show(message, caption, buttons);

                    if (result == DialogResult.Yes)
                    {

                        //--- Persist the changes to the Database
                        try
                        {
                            return dataService.SaveWithTransaction(m_dataContainer, true);
                        }
                        catch (Exception ex)
                        {
                            m_dataContainer.RejectChanges();
                            updateOK = false;
                            throw ex;
                        }


                    }
                    else
                    {
                        try
                        {
                            //--- Reload data from server and merge with local data
                            if (m_dataContainer.HasErrors)
                            {
                                if (m_dataContainer.Customers.HasErrors)
                                {

                                    //------------------------------------------
                                    //--- Resolve DbConcurrency For Customers---
                                    //------------------------------------------

                                    //---Get Serverside RowData
                                    CustomerOrderTDS.CustomersRow[] customerErrorRows
                                        = (CustomerOrderTDS.CustomersRow[])m_dataContainer.Customers.GetErrors();

                                    //---Merge with local DataSet
                                    foreach (CustomerOrderTDS.CustomersRow customerErrorRow in customerErrorRows)
                                    {
                                        m_dataContainer.Customers.Merge(dataService.GetCustomerRow(customerErrorRow.CustomerID));

                                    }

                                    //--- Remap changed Data to object Data
                                    foreach (CustomerBO customerObject in p_addedOrModifiedCustomers)
                                    {

                                        //--- Get the Updated Row from our DataContainer
                                        CustomerOrderTDS.CustomersRow customerRow =
                                            (CustomerOrderTDS.CustomersRow)m_dataContainer.Customers.FindByCustomerID(customerObject.CustomerId);


                                        //--- Only Update Error Objects
                                        bool isErrorRow = false;
                                        foreach (CustomerOrderTDS.CustomersRow customerErrorRow in customerErrorRows)
                                        {
                                            if (customerErrorRow.CustomerID == customerObject.CustomerId)
                                            {
                                                isErrorRow = true;
                                                break;
                                            }
                                        }

                                        if (customerRow != null && isErrorRow)
                                        {
                                            ORM.RelationalToObject(customerObject, customerRow);
                                        }
                                    }
                                }

                                //------------------------------------------
                                //--- Resolve DbConcurrency For Orders   ---
                                //------------------------------------------

                                if (m_dataContainer.Orders.HasErrors)
                                {
                                    //--- Get ServerSideData
                                    CustomerOrderTDS.OrdersRow[] orderErrorRows
                                        = (CustomerOrderTDS.OrdersRow[])m_dataContainer.Orders.GetErrors();


                                    //--- Merge with local DataSet
                                    foreach (CustomerOrderTDS.OrdersRow orderErrorRow in orderErrorRows)
                                    {
                                        m_dataContainer.Orders.Merge(dataService.GetOrderRow(orderErrorRow.OrderID));

                                    }


                                    //--- Remap changed Data to object Data
                                    foreach (OrderBO orderObject in p_AddedOrModifiedorders)
                                    {
                                        //--- Get the Updated Row from our DataContainer
                                        CustomerOrderTDS.OrdersRow orderRow =
                                            (CustomerOrderTDS.OrdersRow)m_dataContainer.Orders.FindByOrderID(orderObject.OrderId);

                                        //--- Only Update Error Objects
                                        bool isErrorRow = false;
                                        foreach (CustomerOrderTDS.OrdersRow orderErrorRow in orderErrorRows)
                                        {
                                            if (orderErrorRow.OrderID == orderObject.OrderId)
                                            {
                                                isErrorRow = true;
                                                break;
                                            }
                                        }

                                        if (orderRow != null && isErrorRow)
                                        {
                                            ORM.RelationalToObject(orderObject, orderRow);
                                        }

                                    }
                                }


                                    
                            }
                        }
                        catch (Exception ex)
                        {
                            m_dataContainer.RejectChanges();
                            updateOK = false;
                            throw ex;
                        }
                    
                        
                    }
                                        
                }
                finally
                {
                    if (updateOK)
                    {
                        //--- Accept the Changes on the DataSet
                        m_dataContainer.AcceptChanges();

                    }
                }

            }

            return 0;
            
        }
    }
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Belgium Belgium
Working in the IT-Branch for more then 10 years now. Starting as a programmer in WinDev, moved to Progress and actualy working in .NET since 2003. At the moment i'm employed as a .NET architect and teamleader at BERCO N.V. at Ronse (Belgium). In my spare time, i'm a die hard mountainbiker and together with my son Jarne, we're climbing the hills in the "Flemish Ardens" and the wonderfull "Pays des Collines". I also enjoy "a p'tit Jack" (Jack Daniels Whiskey) or a "Duvel" (beer) for "l'après VTT !".

Comments and Discussions