Click here to Skip to main content
15,886,806 members
Articles / Desktop Programming / WPF

Layers Pattern in Practice

Rate me:
Please Sign up or sign in to vote.
4.96/5 (59 votes)
23 Apr 2010CPOL25 min read 152.6K   8.1K   187  
Layers Pattern via a WPF project.
using System;
using System.Collections.Generic;
using System.Linq;
using BillsEntityLib;
using System.Collections.ObjectModel;
using BillsBusinessLogicLib;


namespace BillPayManager
{
    public class RecentBillsDataGridProxy : IDataGridProxy
    {
        private ObservableCollection<Bill> _collection;
        private Microsoft.Windows.Controls.DataGrid _datagrid;
        private readonly List<string> _updateList = new List<string>();
        private readonly List<string> _insertList = new List<string>();
        private readonly List<string> _deleteList = new List<string>();
        private readonly BillsBusinessLogicLib.IBillsManager _billsManager = BillsBusinessLogicLib.BillsManager.GetInstance();
        #region Constructors

        #endregion

        #region IDataGridProxy Members
        /// <summary>
        /// Initialize DataGrid control
        /// </summary>
        /// <param name="dataGrid">DataGrid to populate</param>
        /// <param name="bills">Bills which will populate datagrid</param>
        public void Initialize(Microsoft.Windows.Controls.DataGrid dataGrid, BillsEntityLib.Bills bills)
        {
            if (bills == null)
                return;
            this._datagrid = dataGrid;
            foreach (Bill bill in bills.Items)
            {
                bill.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(bill_PropertyChanged);
            }

            _collection = new ObservableCollection<Bill>(bills.Items);   //define the ObservableCollection<T> class
            this._datagrid.ItemsSource = _collection;                      //bind the data to the datasource
            //Collection Changed Event Handler
            _collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(CollectionCollectionChanged);

            //dataGrid.Cells

        }

        /// <summary>
        /// Updates Datagrid control
        /// </summary>
        /// <param name="bills"></param>
        public void UpdateDataGrid(BillsEntityLib.Bills bills)
        {
            if (this._datagrid == null) return;
            _collection = new ObservableCollection<Bill>(bills.Items);   //define the ObservableCollection<T> class
            this._datagrid.ItemsSource = _collection;                      //bind the data to the datasource
            //Collection Changed Event Handler
            _collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(CollectionCollectionChanged);
        }
        
        /// <summary>
        /// Commit changes in the bill collection to the datasource
        /// </summary>
        /// <exception cref="BillManagerException">BillManager Exception</exception>
        public void CommitChangesToDataSource()
        {
            if (_collection == null)
                return;
            List<Bill> listOfBills = _collection.ToList<Bill>();
            try
            {
                if (_insertList.Count != 0) //if there have been inserted bills
                {
                    //select bills which were inserted
                    var queryInsert = from totalBill in listOfBills
                                      join insertBill in _insertList on totalBill.ID equals insertBill
                                      select
                                          new Bill(totalBill.Name, totalBill.DueDate, totalBill.Amount,
                                                   totalBill.AddedOn,
                                                   totalBill.Status, totalBill.ID);
                    Bills bills = new Bills(queryInsert);
                    _billsManager.Insert(bills); //insert the bills into the datasource
                    _insertList.Clear();
                }
                if (_deleteList.Count != 0) //delete the bills from the datasource
                {
                    foreach (string id in _deleteList)
                        _billsManager.Delete(new Guid(id));
                    _deleteList.Clear();
                }
                if (_updateList.Count == 0) return;
                var queryUpdate = from totalBill in listOfBills
                                  join updateBill in _updateList on totalBill.ID equals updateBill
                                  select
                                      new Bill(totalBill.Name, totalBill.DueDate, totalBill.Amount, totalBill.AddedOn,
                                               totalBill.Status, totalBill.ID);
                foreach (Bill newBill in queryUpdate)
                    _billsManager.Update(new Guid(newBill.ID), newBill);
                _updateList.Clear();
            }
            catch
            {
                _insertList.Clear();
                _updateList.Clear();
                _deleteList.Clear();
                throw;
            }
        }

        public Microsoft.Windows.Controls.DataGrid DataGrid
        {
            get { return this._datagrid; }
        }

        public ObservableCollection<Bill> Collection
        {
            get { return this._collection; }
        }

        public void InsertBillToDataGrid(Bill bill)
        {
            bill.PropertyChanged += bill_PropertyChanged;
            this._collection.Add(bill);
        }

        public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged;

        public event System.ComponentModel.PropertyChangedEventHandler BillPropertyChanged;


        protected virtual void OnCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            System.Collections.Specialized.NotifyCollectionChangedEventHandler temp = CollectionChanged;
            if (temp != null)
            {
                temp.Invoke(sender, e);
            }
        }

        protected virtual void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            System.ComponentModel.PropertyChangedEventHandler temp = BillPropertyChanged;
            if (temp != null)
            {
                temp.Invoke(sender, e);
            }
        }

        #endregion

        //Observable collection changed
        private void CollectionCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            ///Add new Bill in the DataGrid
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (Bill bill in e.NewItems)
                {
                    if (!_insertList.Contains(bill.ID))
                        _insertList.Add(bill.ID);
                }
                this.OnCollectionChanged(sender, e);
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                //Delete new Bill from DataGrid
                foreach (Bill bill in e.OldItems)
                {
                    if (!_deleteList.Contains(bill.ID))
                        _deleteList.Add(bill.ID);
                }
                this.OnCollectionChanged(sender, e);
            }
        }
        //Bill property changed
        private void bill_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            BillPropertyChangeEventArgs args = (BillPropertyChangeEventArgs)e;
            if (!_updateList.Contains(args.ChangedId))
                _updateList.Add(args.ChangedId);
            this.OnPropertyChanged(sender, e);
        }
        
    }
}

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
Moldova (Republic of) Moldova (Republic of)
Interested in computer science, math, research, and everything that relates to innovation. Fan of agnostic programming, don't mind developing under any platform/framework if it explores interesting topics. In search of a better programming paradigm.

Comments and Discussions