1/28/19

Repository / Abstract Design Pattern in C# coding reference | program code guide


We have already viewed "What is the repository design pattern". If you didn't viewed, you can click this link.
https://najathi.blogspot.com/2019/01/repository-pattern-what-is-repository.html



Repository
Mediates between the domain and data mapping layers, acting like an in-memory collection of domain objects.

Benefits
-          Minimizes duplicates of query logic
-          Decouples the application from persistence framework
-          Unit Tests are easy

Unit of Work
Maintain a list of objects affected by a business transaction and coordinates the writing out changes.



Code References.....

Repository Pattern

1. Data
2. Services
3. Domain - Entities
4. Test
5. Presentation (UI)

1.       Data

a)      Data – This project will contain the main repository Interface

public interface IRepository : IDisposable
    {
        IQueryable<T> GetAll<T>() where T : class;
        void Add<T>(T entity) where T : class;
        void Update<T>(T entity) where T : class;
        void Delete<T>(T entity) where T : class;
 DbContextTransaction BeginTransaction();
    }


b)      Repository – This project will contain the repository of all the entity and the .EDMX file

public class AccountingRepositary : IRepository
    {
        private readonly AccountingEntityContext _context;

        public AccountingRepositary()
        {
            _context = new AccountingEntityContext();
        }

        public void Dispose()
        {
            _context?.Dispose();
        }


        public IQueryable<T> GetAll<T>() where T : class
        {
            return _context.Set<T>();
        }

        public void Add<T>(T entity) where T : class
        {
            _context.Entry(entity).State = EntityState.Added;
            _context.SaveChanges();
        }


public void Update<T>(T entity) where T : class
        {
            _context.Entry(entity).State = EntityState.Modified;
            _context.SaveChanges();
        }

        public void Delete<T>(T entity) where T : class
        {
            _context.Entry(entity).State = EntityState.Deleted;
            _context.SaveChanges();
        }

 public DbContextTransaction BeginTransaction()
        {
            return _context.Database.BeginTransaction();
        }
    }


2.       Services – This project will contain services of all the entity

    public class ChartOfAccountsServices
    {
        private readonly IRepository _repository;

        public ChartOfAccountsServices()
        {
            _repository = new AccountingRepositary();
        }

        public List<Entity.ChartofAccount> ListAllChartOfAccounts()
        {
            var query = _repository.GetAll<Entity.ChartofAccount>();
            return query.ToList();
        }

        public List<Entity.ChartofAccount> ListAllChartOfAccounts(string accountNo)
        {
            var query = _repository.GetAll<Entity.ChartofAccount>()
.Where(p => p.AccountNumber.Trim() == accountNo.Trim());
            return query.ToList();
        }

        public void Add(Entity.ChartofAccount chartofAccount)
        {
            _repository.Add(chartofAccount);
        }

        public void Delete(Entity.ChartofAccount chartofAccount)
        {
            _repository.Delete(chartofAccount);
        }

        public void Update(Entity.ChartofAccount chartofAccount)
        {
            _repository.Update(chartofAccount);
        }

public DbContextTransaction BeginTransaction()
        {
            return _repository.BeginTransaction();
        }
    }

3.       Domain – This project will contain all models of the context.

    public partial class ChartofAccount
    {
        public string AccountNumber { get; set; }
        public string AccountGroupName { get; set; }
        public string ParentAccountNumber { get; set; }
        public string AccountName { get; set; }
    }


    [TestClass]
    public class ChartOfAccountsTest
    {
        private IRepository _repository;

        [TestInitialize]
        public void Initialize()
        {
            _repository = new AccountingRepositary();
        }

       [TestMethod]
        public void Query_All_ChartOfAccounts_NoException()
        {
            var query = _repository.GetAll<ChartofAccount>();
            var list = query.ToList();

            foreach (var item in list)
            {
                Trace.TraceInformation("Accounts : {0} {1} {2} {3}",              
                item.AccountGroupName, item.AccountNumber,
                item.ParentAccountNumber, item.AccountName);
            }
        }


Unit Test – This project will test the units

       

        [TestMethod]
        public void Query_All_ChartOfAccounts_With_Selection()
        {
            var query = _repository.GetAll<ChartofAccount>()
                  .Where(p => p.AccountNumber.Trim().ToUpper() == "1000");
            var list = query.ToList();

            foreach (var item in list)
            {
                Trace.TraceInformation("Accounts : {0} {1} {2} {3}",    
                item.AccountGroupName, item.AccountNumber,
                item.ParentAccountNumber, item.AccountName);
            }
        }

        [TestMethod]
        public void Add_Data_To_ChartOfAccounts_Table()
        {
            var newitem = new ChartofAccount
            {
                AccountGroupName = "Test",
                AccountNumber = "TestAccNo",
                ParentAccountNumber = "TestPAccNo",
                AccountName = "TestAccName"

            };

            _repository.Add(newitem);

            var query = _repository.GetAll<ChartofAccount>()
                    .Where(p => p.AccountNumber.Trim() == "TestAccNo");
            var list = query.ToList();

            foreach (var item in list)
            {
                Trace.TraceInformation("Accounts : {0} {1} {2} {3}",
                item.AccountGroupName, item.AccountNumber,
                item.ParentAccountNumber, item.AccountName);
            }
        }


        [TestMethod]
        public void Update_Records_Of_ChartOfAccounts_Table()
        {
            var newitem = new ChartofAccount
            {
                AccountGroupName = "UTest",
                AccountNumber = "TestAccNo",
                ParentAccountNumber = "UTPAccNo",
                AccountName = "UTestAccName"
            };

            _repository.Update(newitem);

            var query = _repository.GetAll<ChartofAccount>()
               .Where(p => p.AccountNumber.Trim() == "UTestAccNo");
            var list = query.ToList();

            foreach (var item in list)
            {
                Trace.TraceInformation("Accounts : {0} {1} {2} {3}",
                item.AccountGroupName, item.AccountNumber,
                item.ParentAccountNumber, item.AccountName);
            }
        }

        [TestMethod]
        public void Delete_Records_From_ChartOfAccounts_Table()
        {
            var newitem = new ChartofAccount { AccountNumber =
                                                 "TestAccNo" };

            _repository.Delete(newitem);

            var query = _repository.GetAll<ChartofAccount>()
                 .Where(p => p.AccountNumber.Trim() == "Test");
            var list = query.ToList();

            foreach (var item in list)
            {
                Trace.TraceInformation("Accounts : {0} {1} {2} {3}",
                item.AccountGroupName, item.AccountNumber,
                item.ParentAccountNumber, item.AccountName);
            }
        }
    }



5.       Presentation – UI – This will contain the forms


public partial class FormChartOfAccounts : Form
    {
        readonly ChartOfAccountsServices _chartOfAccountsServices;
        readonly AccountsGroupServices _accountGroup;
        private bool _generateFlag;

        public FormChartOfAccounts()
        {
            InitializeComponent();

             _accountGroup = new AccountsGroupServices();
            _chartOfAccountsServices = new ChartOfAccountsServices();
        }



// Initialize Services
  _party = new PartyServices();

// Initialize Databinding for Combo Box
var databinding = partyType.ListAllPartyType().OrderBy(i=>i.PartyTypeCode).ToList();
            comboBoxPartyType.DataSource = databinding;
            comboBoxPartyType.DisplayMember = "PartyTypeCode";
            comboBoxPartyType.ValueMember = "PartyTypeCode";





private void ButtonAdd_Click(object sender, EventArgs e)
{
    try
    {
        var party = new Entity.Party
        {
            PartyID = int.Parse(textBoxPartyId.Text),
                    PartyTypeCode =    
                       comboBoxPartyType.SelectedValue.ToString(),
                    Name = textBoxPartyName.Text,
                    Address = textBoxAddress.Text,
                    City = textBoxCity.Text,
                    Telephone = textBoxTelephoneNo.Text
                };

                _party.Add(party);

                buttonClear.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
  


        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                var party = new Entity.Party
                {
                    PartyID = int.Parse(textBoxPartyId.Text),
                    PartyTypeCode = comboBoxPartyType.SelectedValue.ToString(),
                    Name = textBoxPartyName.Text,
                    Address = textBoxAddress.Text,
                    City = textBoxCity.Text,
                    Telephone = textBoxTelephoneNo.Text
                };

                _party.Add(party);

                buttonClear.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ButtonUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                var party = _party.ListAllParty().FirstOrDefault(p => p.PartyID ==
                    int.Parse(textBoxPartyId.Text));

                if (party != null)
                {
                    party.PartyTypeCode = comboBoxPartyType.SelectedValue.ToString();
                    party.Name = textBoxPartyName.Text;
                    party.Address = textBoxAddress.Text;
                    party.City = textBoxCity.Text;
                    party.Telephone = textBoxTelephoneNo.Text;

                    _party.Update(party);
                }

                buttonClear.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ButtonDelete_Click(object sender, EventArgs e)
        {
            try
            {
                var party = _party.ListAllParty()
                    .FirstOrDefault(p => p.PartyID == int.Parse(textBoxPartyId.Text));

                _party.Delete(party);

                buttonClear.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

private void ButtonAdd_Click(object sender, EventArgs e)
{
            using (var transaction = _ae.Database.BeginTransaction())
            {
                try
                {
                    AddToFinanceTransaction();
                    AddToJoural();
                    AddToLedgerDebit();
                    AddToLedgerCredit();
                    AddToCustomerStatement();

                    _ae.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }

            }
                   
        }










No comments:

Post a Comment

About

Hi, I'm Najathi.
I've started entrepreneurial company, Twin Brothers.Inc.
One is self-funded & the other is venture backed. I also send a weekly. where I share relevent, curated links.

Every Week I Publish a short post on writing, publishing, or content of IT Related

Contact Form

Name

Email *

Message *