<file_sep>﻿using Financial.Business.Models;
using Financial.Business.ServiceInterfaces;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Services
{
    public class AccountTypeSettingTypeService : IAccountTypeSettingTypeService
    {
        private IUnitOfWork _unitOfWork;

        public AccountTypeSettingTypeService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }



        public List<Business.Models.AttributeType> GetListOfActiveLinkedSettingTypes(int assetTypeId)
        {
            return _unitOfWork.SettingTypes.GetAll()// your starting point - table in the "from" statement
                .Where(r => r.IsActive)
                .ToList()
                .Join(_unitOfWork.AssetTypeSettingTypes.FindAll(r => r.IsActive), // the source table of the inner join
                st => st.Id, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
                atst => atst.Id, // Select the foreign key (the second part of the "on" clause)
                (st, atst) => new { SType = st, ATypeSType = atst }) // selection
                .Where(link => link.ATypeSType.AssetTypeId == assetTypeId)
                .Select(j => new Business.Models.AttributeType(j.SType, j.ATypeSType))
                .ToList();
        }

        public List<Business.Models.AccountType> GetListOfActiveLinkedAssetTypes(int settingTypeId)
        {
            return _unitOfWork.AssetTypes.GetAll()// your starting point - table in the "from" statement
                .Where(r => r.IsActive)
                .ToList()
                .Join(_unitOfWork.AssetTypeSettingTypes.FindAll(r => r.IsActive), // the source table of the inner join
                at => at.Id, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
                atst => atst.Id, // Select the foreign key (the second part of the "on" clause)
                (at, atst) => new { AType = at, ATypeSType = atst }) // selection
                .Where(link => link.ATypeSType.SettingTypeId == settingTypeId)
                .Select(j => new Business.Models.AccountType(j.AType, j.ATypeSType))
                .ToList();
        }

        public Business.Models.AccountType CreateLinkedSettingTypesGetModel(int assetTypeId)
        {
            var dtoAssetType = _unitOfWork.AssetTypes.Find(r => r.IsActive && r.Id == assetTypeId);
            if (dtoAssetType == null)
            {
                return null;
            }
            return new Business.Models.AccountType(dtoAssetType);
        }
        public Business.Models.AccountType EditLinkedSettingTypesGetModel(int assetTypeId)
        {
            var dtoAssetType = _unitOfWork.AssetTypes.Find(r => r.IsActive && r.Id == assetTypeId);
            if (dtoAssetType == null)
            {
                return null;
            }
            return new Business.Models.AccountType(dtoAssetType);
        }




        public int GetAssetTypeSettingTypeIdForLinkedAssetType(int assetTypeId, int settingTypeId)
        {
            // get link information
            var dbAssetTypeAttributeTypes = _unitOfWork.AssetTypeSettingTypes.GetAllActive()
                .Where(r => r.AssetTypeId == assetTypeId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);

            // validate
            if (dbAssetTypeAttributeTypes == null)
            {
                return 0;
            }

            return dbAssetTypeAttributeTypes.Id;
        }


        public List<AccountType> GetListOfLinkedAssetTypes(int settingTypeId)
        {
            // get linked setting types from db
            var dbAssetTypeAttributeTypes = _unitOfWork.AssetTypeSettingTypes.GetAll()
                .Where(r => r.IsActive)
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();

            // transfer dto to bm
            var bmAssetTypes = new List<AccountType>();
            foreach (var dtoAssetTypeSettingType in dbAssetTypeAttributeTypes)
            {
                var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAssetTypeSettingType.AssetTypeId);
                if (dtoAssetType != null)
                {
                    bmAssetTypes.Add(new AccountType(dtoAssetType, dtoAssetTypeSettingType));
                }
            }

            return bmAssetTypes;
        }

        public List<AttributeType> GetListOfLinkedSettingTypes(int assetTypeId)
        {
            // get linked setting types from db
            var dbAssetTypeSettingTypes = _unitOfWork.AssetTypeSettingTypes.GetAll()
                .Where(r => r.IsActive)
                .Where(r => r.AssetTypeId == assetTypeId)
                .ToList();

            // transfer dto to bm
            var bmSettingTypes = new List<AttributeType>();
            foreach (var dtoAssetTypeSettingType in dbAssetTypeSettingTypes)
            {
                var dtoSettingType = _unitOfWork.SettingTypes.Get(dtoAssetTypeSettingType.SettingTypeId);
                if (dtoSettingType != null)
                {
                    bmSettingTypes.Add(new AttributeType(dtoSettingType, dtoAssetTypeSettingType));
                }
            }

            return bmSettingTypes;
        }

        public List<AttributeType> GetListOfSettingTypesWithLinkedAssetType(int assetTypeId)
        {
            var bmSettingTypes = new List<AttributeType>();

            // transfer from db
            var dbSettingTypes = _unitOfWork.SettingTypes.GetAllActive();

            foreach (var dtoSettingType in dbSettingTypes)
            {
                // check for existing link
                var dtoAssetTypeSettingType = _unitOfWork.AssetTypeSettingTypes.GetAllActive()
                    .Where(r => r.AssetTypeId == assetTypeId)
                    .FirstOrDefault(r => r.SettingTypeId == dtoSettingType.Id);
                if(dtoAssetTypeSettingType == null)
                {
                    // no link found
                    dtoAssetTypeSettingType = new Core.Models.AssetTypeSettingType();
                }

                // transfer dto to bm
                bmSettingTypes.Add(new AttributeType(dtoSettingType, dtoAssetTypeSettingType));
            }

            return bmSettingTypes;
        }


    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.RelationshipType;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;

namespace Financial.WebApplication.Controllers
{
    public class RelationshipTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;


        public RelationshipTypeController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [HttpGet]
        public ViewResult Index()
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }
            if (TempData["ErrorMessage"] != null)
            {
                ViewData["ErrorMessage"] = TempData["ErrorMessage"];
            }

            // transfer dto to vm
            var vmIndex = _unitOfWork.RelationshipTypes.GetAll()
                .Select(r => new IndexViewModel(r))
                .ToList();

            // display view
            return View("Index", vmIndex);
        }

        [HttpGet]
        public ViewResult Create()
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }

            // display view
            return View("Create");
        }

        [HttpPost]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            // validation
            if(!ModelState.IsValid)
            {
                return View("Create", vmCreate);
            }

            // check for duplicate
            var count = _unitOfWork.RelationshipTypes.GetAll()
                .Count(r => r.Name == vmCreate.Name);
            if (count > 0)
            {
                // display view with message
                ViewData["ErrorMessage"] = "Record already exists";
                return View("Create", vmCreate);
            }

            // transfer vm to dto
            _unitOfWork.RelationshipTypes.Add(new RelationshipType()
            {
                Name = vmCreate.Name,
                IsActive = true
            });

            // update db
            _unitOfWork.CommitTrans();

            // display view with message
            TempData["SuccessMessage"] = "Record created";
            return RedirectToAction("Index", "RelationshipType");
        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            // transfer dto to vm
            var vmEdit = _unitOfWork.RelationshipTypes.GetAll()
                .Select(r => new EditViewModel(r))
                .FirstOrDefault(r => r.Id == id);

            // display view
            return View("Edit", vmEdit);
        }

        [HttpPost]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            // validation
            if(!ModelState.IsValid)
            {
                return View("Edit", vmEdit);
            }

            // check for duplicate
            var count = _unitOfWork.RelationshipTypes.GetAll()
                .Where(r => r.Name == vmEdit.Name)
                .Count(r => r.Id != vmEdit.Id);
            if(count > 0)
            {
                // display view with message
                ViewData["ErrorMessage"] = "Record already exists";
                return View("Edit", vmEdit);
            }

            // transfer vm to dto
            var dtoRelationshipType = _unitOfWork.RelationshipTypes.Get(vmEdit.Id);
            dtoRelationshipType.Name = vmEdit.Name;
            dtoRelationshipType.IsActive = vmEdit.IsActive;

            // update db
            _unitOfWork.CommitTrans();

            // display view with message
            TempData["SuccessMessage"] = "Record updated";
            return RedirectToAction("Index", "RelationshipType");
        }

        [HttpGet]
        public ViewResult Details(int id)
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }
            if (TempData["ErrorMessage"] != null)
            {
                ViewData["ErrorMessage"] = TempData["ErrorMessage"];
            }

            // transfer dto to vm
            var vmDetails = _unitOfWork.RelationshipTypes.GetAll()
                .Select(r => new DetailsViewModel(r))
                .FirstOrDefault(r => r.Id == id);

            // display view
            return View("Details", vmDetails);
        }
    }
}<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface ITransactionTypeRepository : IRepository<TransactionType>
    {
        IEnumerable<TransactionType> GetAllActiveOrderedByName();
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using NUnit.Framework;
using Financial.Business.Services;
using Financial.Data;
using Moq;
using Financial.Core.Models;
using Financial.Business.Models;
using Financial.Core;
using Financial.Data.Repositories;
using Financial.Tests.Mocks;

namespace Financial.Tests.Business.Services
{
    [TestFixture]
    public class AccountTransactionServiceTests
    {
        private Asset _dbAsset;
        private AssetType _dbAssetType;
        private AssetSetting _dbAssetSetting;
        private AssetTransaction _dbAssetTransaction;
        private SettingType _dbSettingType;
        private TransactionType _dbTransactionType;
        private TransactionCategory _dbTransactionCategory;
        private TransactionDescription _dbTransactionDescription;
        private AccountTransactionService _service;
        private Mock<IUnitOfWork> _mockUnitOfWork;
        private IUnitOfWork _fakeUnitOfWork;
        private FinancialDbContext _fakeDbContext;


        [SetUp]
        public void SetUp()
        {
            // setup db models
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset
            {
                Id = 2,
                AssetTypeId = _dbAssetType.Id,
                AssetType = _dbAssetType, // setup include
                Name = "b",
                IsActive = true
            };
            _dbSettingType = new SettingType { Id = 3, Name = "c", IsActive = true };
            _dbAssetSetting = new AssetSetting
            {
                Id = 4,
                AssetId = _dbAsset.Id,
                Asset = _dbAsset, // setup include
                SettingTypeId = _dbSettingType.Id,
                SettingType = _dbSettingType, // setup include
                Value = "d",
                IsActive = true
            };
            _dbTransactionType = new TransactionType { Id = 5, Name = "e", IsActive = true };
            _dbTransactionCategory = new TransactionCategory {Id = 6, Name = "f", IsActive = true};
            _dbTransactionDescription = new TransactionDescription {Id = 7, Name = "g", IsActive = true};
            _dbAssetTransaction = new AssetTransaction
            {
                Id = 8,
                AssetId = _dbAsset.Id,
                Asset = _dbAsset,  // setup include
                TransactionTypeId = _dbTransactionType.Id,
                TransactionType = _dbTransactionType, // setup include
                TransactionCategoryId = _dbTransactionCategory.Id,
                TransactionCategory = _dbTransactionCategory, // setup include
                TransactionDescriptionId = _dbTransactionDescription.Id,
                TransactionDescription = _dbTransactionDescription, // setup include
                DueDate = new DateTime(1234, 5, 6),
                ClearDate = new DateTime(1234, 7, 8),
                Amount = 1.23M,
                Note = "abc",
                IsActive = true
            };

            // setup DbContext
            Setup_FakeDbContext();

            // setup uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // setup service
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void GetListOfActiveTransactions_WhenCalled_ReturnAccountTransactionList_Test()
        {
            var result = _service.GetListOfActiveTransactions();

            Assert.That(result, Is.TypeOf<List<AccountTransaction>>());
        }

        [Test]
        public void GetListOfActiveTransactions_WhenCalled_ShouldCallOneTimeUnitOfWorkRepositoryAssetTransactionsMethodGetAllActiveByDueDate_Test()
        {
            _mockUnitOfWork = new Mock<IUnitOfWork>();
            Setup_MockUnitOfWork_AssetTransaction_GetAllActiveByDueDate();
            Setup_MockUnitOfWork_Assets_Get();
            Setup_MockUnitOfWork_AssetTypes_Get();
            Setup_MockUnitOfWork_AssetSettings_GetActive();

            _service = new AccountTransactionService(_mockUnitOfWork.Object);

            _service.GetListOfActiveTransactions();

            _mockUnitOfWork.Verify(uow => uow.AssetTransactions.GetAllActiveByDueDate(),
                Times.Once);
        }

        [Test]
        public void GetListOfActiveTransactions_WhenAccountTransactionListHasAccountTransactions_ShouldCallUnitOfWorkRepositoryAssetsMethodGet_Test()
        {
            _mockUnitOfWork = new Mock<IUnitOfWork>();
            Setup_MockUnitOfWork_AssetTransaction_GetAllActiveByDueDate();
            Setup_MockUnitOfWork_Assets_Get();
            Setup_MockUnitOfWork_AssetTypes_Get();
            Setup_MockUnitOfWork_AssetSettings_GetActive();

            _service = new AccountTransactionService(_mockUnitOfWork.Object);

            _service.GetListOfActiveTransactions();

            _mockUnitOfWork.Verify(uow => uow.Assets.Get(It.IsAny<int>()),
                Times.AtLeastOnce);
        }

        [Test]
        public void GetListOfActiveTransactions_WhenAccountTransactionListHasAccountTransactions_ShouldCallUnitOfWorkRepositoryAssetSettingsMethodGetActive_Test()
        {
            _mockUnitOfWork = new Mock<IUnitOfWork>();
            Setup_MockUnitOfWork_AssetTransaction_GetAllActiveByDueDate();
            Setup_MockUnitOfWork_Assets_Get();
            Setup_MockUnitOfWork_AssetTypes_Get();
            Setup_MockUnitOfWork_AssetSettings_GetActive();

            _service = new AccountTransactionService(_mockUnitOfWork.Object);

            _service.GetListOfActiveTransactions();

            _mockUnitOfWork.Verify(uow => uow.AssetSettings.GetActive(It.IsAny<int>(), It.IsAny<int>()),
                Times.AtLeastOnce);
        }

        [Test]
        public void GetListOfActiveTransactions_WhenAccountListHasAccount_ReturnAccountTransactionValues_Test()
        {
            var result = _service.GetListOfActiveTransactions();

            Assert.Multiple(() =>
            {
                Assert.That(result.Count, Is.EqualTo(1), "Count");
                Assert.That(result[0].AssetTransactionId, Is.EqualTo(_dbAssetTransaction.Id), "AssetTransaction Id");
                Assert.That(result[0].AssetId, Is.EqualTo(_dbAssetTransaction.AssetId), "Asset Id");
                Assert.That(result[0].AssetName, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result[0].AssetTypeId, Is.EqualTo(_dbAsset.AssetTypeId), "AssetType Id");
                Assert.That(result[0].AssetTypeName, Is.EqualTo(_dbAssetType.Name), "AssetType Name");
                Assert.That(result[0].DueDate, Is.EqualTo(_dbAssetTransaction.DueDate), "DueDate");
                Assert.That(result[0].ClearDate, Is.EqualTo(_dbAssetTransaction.ClearDate), "ClearDate");
                Assert.That(result[0].Amount, Is.EqualTo(_dbAssetTransaction.Amount), "Amount");
                Assert.That(result[0].Note, Is.EqualTo(_dbAssetTransaction.Note), "Note");
            });
        }

        [Test]
        public void GetListOfActiveTransactions_WhenAccountTypeEqualsCreditCard_ReturnNameWithAccountNumber_Test()
        {
            Setup_Service_FakeUnitOfWork_AssetType_CreditCard(assetName: "a", assetSettingValue: "1234");

            var expectedAssetName = "a (1234)";

            var result = _service.GetListOfActiveTransactions();

            Assert.That(result[0].AssetName, Is.EqualTo(expectedAssetName));
        }

        [Test]
        public void GetListOfActiveTransactions_WhenTransactionTypeEqualsIncome_ReturnPositiveAmount_Test()
        {
            Setup_Service_FakeUnitOfWork_TransactionType_Income(transactionAmount: 1.25M);

            var result = _service.GetListOfActiveTransactions();

            Assert.That(result[0].Amount, Is.EqualTo(1.25));
        }

        [Test]
        public void GetListOfActiveTransactions_WhenTransactionTypeEqualsExpense_ReturnNegativeAmount_Test()
        {
            Setup_Service_FakeUnitOfWork_TransactionType_Expense(transactionAmount: 1.25M);

            var result = _service.GetListOfActiveTransactions();

            Assert.That(result[0].Amount, Is.EqualTo(-1.25));
        }

        [Test]
        public void GetListOfActiveTransactions_WhenAccountIdEqualsZero_ReturnEmptyAccountList_Test()
        {
            _dbAssetTransaction.AssetId = 0;

            var result = _service.GetListOfActiveTransactions();

            Assert.That(result, Is.EquivalentTo(new List<AccountTransaction>()));
        }



        [Test]
        public void GetAccountForTransaction_WhenCalled_ReturnAccount_Test()
        {
            var result = _service.GetAccountForTransaction(assetId: _dbAsset.Id);

            Assert.That(result, Is.InstanceOf<Account>());
        }

        [Test]
        public void GetAccountForTransaction_WhenAssetIdEqualsNull_ReturnNull_Test()
        {
            var result = _service.GetAccountForTransaction(assetId: null);

            Assert.That(result, Is.EqualTo(null));
        }

        [Test]
        public void GetAccountForTransaction_WhenAssetIdEqualsZero_ReturnNull_Test()
        {
            var result = _service.GetAccountForTransaction(assetId: 0);

            Assert.That(result, Is.EqualTo(null));
        }

        [Test]
        public void GetAccountForTransaction_WhenAssetIdProvided_ReturnAccountValues_Test()
        {
            var result = _service.GetAccountForTransaction(_dbAsset.Id);

            Assert.Multiple(() =>
            {
                Assert.That(result.AssetId, Is.EqualTo(_dbAsset.Id), "Asset Id");
                Assert.That(result.AssetName, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result.AssetTypeId, Is.EqualTo(_dbAsset.AssetTypeId), "AssetType Id");
                Assert.That(result.AssetTypeName, Is.EqualTo(_dbAssetType.Name), "AssetType Name");
            });
        }

        [Test]
        public void GetAccountForTransaction_WhenAssetTypeEqualsCreditCard_ReturnFormattedAccountName_Test()
        {
            Setup_Service_FakeUnitOfWork_AssetType_CreditCard(assetName: "a", assetSettingValue: "1234");

            var expectedFormattedAssetName = "a (1234)";

            var result = _service.GetAccountForTransaction(assetId: _dbAsset.Id);

            Assert.That(result.AssetName, Is.EqualTo(expectedFormattedAssetName));
        }

        [Test]
        public void GetAccountForTransaction_WhenUnitOfWorkReturnsAssetEqualsNull_ReturnNull_Test()
        {
            _mockUnitOfWork = new Mock<IUnitOfWork>();
            _mockUnitOfWork.Setup(uow => uow.Assets.Get(It.IsAny<int>()));

            _service = new AccountTransactionService(_mockUnitOfWork.Object);

            var result = _service.GetAccountForTransaction(assetId: 1);

            Assert.That(result, Is.EqualTo(null));
        }




        [Test]
        public void GetAccountSelectList_WhenCalled_ReturnSelectListItems_Test()
        {
            var result = _service.GetAccountSelectList(selectedId: null);

            Assert.That(result, Is.InstanceOf<List<SelectListItem>>());
        }

        [Test]
        public void GetAccountSelectList_WhenCalled_ReturnAssetValues_Test()
        {
            var result = _service.GetAccountSelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Value, Is.EqualTo(_dbAsset.Id.ToString()));
                Assert.That(result[0].Text, Is.EqualTo(_dbAsset.Name));
            });
        }

        [Test]
        public void GetAccountSelectList_WhenAssetTypeEqualsCreditCard_ReturnFormattedAssetName_Test()
        {
            Setup_Service_FakeUnitOfWork_AssetType_CreditCard(assetName: "a", assetSettingValue: "1234");

            var expectedFormattedAssetName = "a (1234)";

            var result = _service.GetAccountSelectList(selectedId: null);

            Assert.That(result[0].Text, Is.EqualTo(expectedFormattedAssetName));
        }

        [Test]
        public void GetAccountSelectList_WhenSelectedIdProvided_ReturnSelectedIndex_Test()
        {
            var result = _service.GetAccountSelectList(selectedId: _dbAsset.Id.ToString());

            Assert.That(result[0].Selected, Is.EqualTo(true));
        }

        [Test]
        public void GetAccountSelectList_WhenMultipleAssetsFound_ReturnAssetsOrderedAscendingByName_Test()
        {
            var fakeAssetTypeList = new List<AssetType> {_dbAssetType};
            var asset1 = new Asset { Id = 1, Name = "z", AssetTypeId = _dbAssetType.Id, AssetType = _dbAssetType, IsActive = true };
            var asset2 = new Asset { Id = 2, Name = "a", AssetTypeId = _dbAssetType.Id, AssetType = _dbAssetType, IsActive = true };
            var fakeAssetList = new List<Asset> { asset1, asset2 };
            var fakeSettingTypeList = new List<SettingType> {_dbSettingType};
            var fakeAssetSettingList = new List<AssetSetting>
            {
                new AssetSetting { Id = 3, AssetId = asset1.Id, Asset = asset1, SettingTypeId = _dbSettingType.Id, SettingType = _dbSettingType, Value = "abc", IsActive = true },
                new AssetSetting { Id = 4, AssetId = asset2.Id, Asset = asset2, SettingTypeId = _dbSettingType.Id, SettingType = _dbSettingType, Value = "abc", IsActive = true },
            };

            Setup_Service_FakeUnitOfWork(fakeAssetList, fakeAssetSettingList, fakeAssetTypeList, fakeSettingTypeList);

            var result = _service.GetAccountSelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Text, Is.EqualTo("a"), "First Index");
                Assert.That(result[1].Text, Is.EqualTo("z"), "Second Index");
            });
        }



        [Test]
        public void GetTransactionTypeSelectList_WhenCalled_ReturnSelectListItems_Test()
        {
            var result = _service.GetTransactionTypeSelectList(selectedId: null);

            Assert.That(result, Is.InstanceOf<List<SelectListItem>>());
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenCalled_ReturnTransactionTypeValues_Test()
        {
            var result = _service.GetTransactionTypeSelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Value, Is.EqualTo(_dbTransactionType.Id.ToString()), "Id");
                Assert.That(result[0].Text, Is.EqualTo(_dbTransactionType.Name), "Name");
            });
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSelectedIdProvided_ReturnSelectedIndex_Test()
        {
            var result = _service.GetTransactionTypeSelectList(selectedId: _dbTransactionType.Id.ToString());

            Assert.That(result[0].Selected, Is.EqualTo(true));
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenMultipleTransactionTypesFound_ReturnOrderedAscendingByName_Test()
        {
            var fakeTransactionTypeList = new List<TransactionType> 
            {
                new TransactionType { Id = 1, Name = "z", IsActive = true },
                new TransactionType { Id = 2, Name = "a", IsActive = true },
            };

            Setup_Service_FakeUnitOfWork(fakeTransactionTypeList);

            var result = _service.GetTransactionTypeSelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Text, Is.EqualTo("a"), "First Index");
                Assert.That(result[1].Text, Is.EqualTo("z"), "Second Index");
            });
        }




        [Test]
        public void GetTransactionCategorySelectList_WhenCalled_ReturnSelectListItems_Test()
        {
            var result = _service.GetTransactionCategorySelectList(selectedId: null);

            Assert.That(result, Is.InstanceOf<List<SelectListItem>>());
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenCalled_ReturnTransactionCategoryValues_Test()
        {
            var result = _service.GetTransactionCategorySelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Value, Is.EqualTo(_dbTransactionCategory.Id.ToString()), "Id");
                Assert.That(result[0].Text, Is.EqualTo(_dbTransactionCategory.Name), "Name");
            });
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSelectedIdProvided_ReturnSelectedIndex_Test()
        {
            var result = _service.GetTransactionCategorySelectList(selectedId: _dbTransactionCategory.Id.ToString());

            Assert.That(result[0].Selected, Is.EqualTo(true));
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenMultipleTransactionCategoriesFound_ReturnOrderedAscendingByName_Test()
        {
            var fakeTransactionCategoryList = new List<TransactionCategory>
            {
                new TransactionCategory { Id = 1, Name = "z", IsActive = true },
                new TransactionCategory { Id = 2, Name = "a", IsActive = true },
            };

            Setup_Service_FakeUnitOfWork(fakeTransactionCategoryList);

            var result = _service.GetTransactionCategorySelectList(selectedId: null);

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Text, Is.EqualTo("a"), "First Index");
                Assert.That(result[1].Text, Is.EqualTo("z"), "Second Index");
            });
        }



        // private


        private void Setup_FakeDbContext()
        {
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset },
                new List<AssetSetting> { _dbAssetSetting },
                new List<AssetTransaction> { _dbAssetTransaction },
                new List<AssetType> { _dbAssetType },
                new List<SettingType> { _dbSettingType },
                new List<TransactionCategory> { _dbTransactionCategory },
                new List<TransactionDescription> { _dbTransactionDescription },
                new List<TransactionType> { _dbTransactionType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetSetting> fakeAssetSettingList,
            List<AssetTransaction> fakeAssetTransactionList,
            List<AssetType> fakeAssetTypeList,
            List<SettingType> fakeSettingTypeList,
            List<TransactionCategory> fakeTransactionCategoryList,
            List<TransactionDescription> fakeTransactionDescriptionList,
            List<TransactionType> fakeTransactionTypeList)
        {
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetSettings: fakeAssetSettingList,
                assetTransactions: fakeAssetTransactionList,
                assetTypes: fakeAssetTypeList,
                settingTypes: fakeSettingTypeList,
                transactionCategories: fakeTransactionCategoryList,
                transactionDescriptions: fakeTransactionDescriptionList,
                transactionTypes: fakeTransactionTypeList);
        }
        private void Setup_Service_FakeUnitOfWork(
            List<Asset> fakeAssets, 
            List<AssetSetting> fakeAssetSettings,
            List<AssetType> fakeAssetTypes,
            List<SettingType> fakeSettingTypes)
        {
            // setup DbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssets,
                assetSettings: fakeAssetSettings,
                assetTypes: fakeAssetTypes,
                settingTypes: fakeSettingTypes);

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_Service_FakeUnitOfWork(List<TransactionType> fakeTransactionTypes)
        {
            // setup DbContext
            _fakeDbContext = MockFinancialDbContext.Create(transactionTypes: fakeTransactionTypes);

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_Service_FakeUnitOfWork(List<TransactionCategory> fakeTransactionCategories)
        {
            // setup DbContext
            _fakeDbContext = MockFinancialDbContext.Create(transactionCategories: fakeTransactionCategories);

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_Service_FakeUnitOfWork_AssetType_CreditCard(string assetName, string assetSettingValue)
        {
            // setup fake model
            _dbAssetType.Id = AssetType.IdForCreditCard;

            _dbAsset.AssetTypeId = _dbAssetType.Id;
            _dbAsset.AssetType = _dbAssetType;
            _dbAsset.Name = assetName;

            _dbSettingType.Id = SettingType.IdForAccountNumber;

            _dbAssetSetting.SettingTypeId = _dbSettingType.Id;
            _dbAssetSetting.SettingType = _dbSettingType;
            _dbAssetSetting.Asset = _dbAsset;
            _dbAssetSetting.Value = assetSettingValue;

            _dbAssetTransaction.AssetId = _dbAsset.Id;
            _dbAssetTransaction.Asset = _dbAsset;

            // setup DbContext
            Setup_FakeDbContext();

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_Service_FakeUnitOfWork_TransactionType_Income(decimal transactionAmount)
        {
            // setup fake model
            _dbTransactionType.Id = TransactionType.IdForIncome;

            _dbAssetTransaction.TransactionTypeId = _dbTransactionType.Id;
            _dbAssetTransaction.TransactionType = _dbTransactionType;
            _dbAssetTransaction.Amount = transactionAmount;

            // setup DbContext
            Setup_FakeDbContext();

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_Service_FakeUnitOfWork_TransactionType_Expense(decimal transactionAmount)
        {
            // setup fake model
            _dbTransactionType.Id = TransactionType.IdForExpense;

            _dbAssetTransaction.TransactionTypeId = _dbTransactionType.Id;
            _dbAssetTransaction.TransactionType = _dbTransactionType;
            _dbAssetTransaction.Amount = transactionAmount;

            // setup DbContext
            Setup_FakeDbContext();

            // set up uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // set up repository
            _service = new AccountTransactionService(_fakeUnitOfWork);
        }

        private void Setup_MockUnitOfWork_Assets_Get()
        {
            _mockUnitOfWork.Setup(uow => uow.Assets.Get(_dbAsset.Id))
                .Returns(_dbAsset);
        }
        private void Setup_MockUnitOfWork_AssetTypes_Get()
        {
            _mockUnitOfWork.Setup(uow => uow.AssetTypes.Get(_dbAssetType.Id))
                .Returns(_dbAssetType);
        }
        private void Setup_MockUnitOfWork_AssetSettings_GetActive()
        {
            _mockUnitOfWork.Setup(uow => uow.AssetSettings.GetActive(_dbAssetSetting.AssetId, _dbAssetSetting.SettingTypeId))
                .Returns(_dbAssetSetting);
        }
        private void Setup_MockUnitOfWork_AssetTransaction_GetAllActiveByDueDate()
        {
            _mockUnitOfWork.Setup(uow => uow.AssetTransactions.GetAllActiveByDueDate())
                .Returns(new List<AssetTransaction> { _dbAssetTransaction });
        }
    }
}
<file_sep>using Financial.Business;
using Financial.Business.ServiceInterfaces;
using Financial.Business.Services;
using Financial.Data;
using System.Web.Mvc;
using Unity;
using Unity.Mvc5;

namespace Financial.WebApplication
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
			var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterType<IUnitOfWork, UnitOfWork>();
            container.RegisterType<IBusinessService, BusinessService>();

            container.RegisterType<IAccountTypeService, AccountTypeService>();
            container.RegisterType<IAccountTypeSettingTypeService, AccountTypeSettingTypeService>();
            container.RegisterType<IAccountTransactionService, AccountTransactionService>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryAssetRepository : InMemoryRepository<Asset>, IAssetRepository
    {
        private List<Asset> _entities = null;

        public InMemoryAssetRepository(IEnumerable<Asset> entities)
            : base(entities)
        {
            _entities = entities as List<Asset>;
        }


        public IEnumerable<Asset> GetAllActiveOrderedByName()
        {
            return _entities
                .Where(r => r.IsActive)
                .OrderBy(r => r.Name)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.ParentChildRelationshipType
{
    public class CreateViewModel
    {
        public CreateViewModel(){}

        public CreateViewModel(Core.Models.RelationshipType dtoSuppliedRelationshipType, 
            List<SelectListItem> sliRelationshipLevels, 
            List<SelectListItem> sliLinkedRelationshipTypes)
        {
            SuppliedRelationshipTypeId = dtoSuppliedRelationshipType.Id;
            SuppliedRelationshipTypeName = dtoSuppliedRelationshipType.Name;
            RelationshipLevels = sliRelationshipLevels;
            LinkedRelationshipTypes = sliLinkedRelationshipTypes;
        }

        public int SuppliedRelationshipTypeId { get; set; }
        [Display(Name = "Relationship Type")]
        public string SuppliedRelationshipTypeName { get; set; }

        [Required]
        [Display(Name = "Relationship Level")]
        public string SelectedRelationshipLevel { get; set; }
        public IEnumerable<SelectListItem> RelationshipLevels { get; set; }

        [Required]
        [Display(Name = "Linked Relationship Type")]
        public string SelectedLinkedRelationshipType { get; set; }
        public IEnumerable<SelectListItem> LinkedRelationshipTypes { get; set; }

    }
}
<file_sep>﻿using Financial.Core;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
    {
        protected readonly DbContext _context;
        private DbSet<TEntity> _entities;

        public Repository(DbContext context)
        {
            _context = context;
            _entities = _context.Set<TEntity>();
        }

        public TEntity Get(int id)
        {
            return _entities.FirstOrDefault(r => r.Id == id);
        }

        public TEntity GetActive(int id)
        {
            return _entities.Where(r => r.IsActive).FirstOrDefault(r => r.Id == id);
        }

        public IEnumerable<TEntity> GetAll()
        {
            return _entities.ToList();
        }

        public IEnumerable<TEntity> GetAllActive()
        {
            return _entities.Where(r => r.IsActive).ToList();
        }

        public TEntity Find(Expression<Func<TEntity, bool>> predicate)
        {
            return _context.Set<TEntity>().SingleOrDefault(predicate);
        }

        public IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate)
        {
            return _context.Set<TEntity>().Where(predicate);
        }

        public bool Exists(int id)
        {
            return _entities.FirstOrDefault(r => r.Id == id) != null;
        }

        public void Add(TEntity entity)
        {
            _context.Set<TEntity>().Add(entity);
        }

        public void AddRange(IEnumerable<TEntity> entities)
        {
            _context.Set<TEntity>().AddRange(entities);
        }

        public void Remove(TEntity entity)
        {
            _context.Set<TEntity>().Remove(entity);
        }

        public void RemoveRange(IEnumerable<TEntity> entities)
        {
            _context.Set<TEntity>().RemoveRange(entities);
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeParentChildRelationshipTypes
    {
        public static IEnumerable<ParentChildRelationshipType> InitialFakeParentChildRelationshipTypes()
        {
            yield return new ParentChildRelationshipType() { Id = 1, ParentRelationshipTypeId = 2, ChildRelationshipTypeId = 4, IsActive = true };
            yield return new ParentChildRelationshipType() { Id = 2, ParentRelationshipTypeId = 4, ChildRelationshipTypeId = 5, IsActive = true };
            yield return new ParentChildRelationshipType() { Id = 3, ParentRelationshipTypeId = 3, ChildRelationshipTypeId = 3, IsActive = false };
            yield return new ParentChildRelationshipType() { Id = 4, ParentRelationshipTypeId = 5, ChildRelationshipTypeId = 1, IsActive = true };
            yield return new ParentChildRelationshipType() { Id = 5, ParentRelationshipTypeId = 1, ChildRelationshipTypeId = 2, IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountAttributes")]
    public class AssetSetting : BaseEntity
    {
        [Required]
        [Column("AccountId")]
        public int AssetId { get; set; }
        [Required]
        [Column("AttributeTypeId")]
        public int SettingTypeId { get; set; }
        public string Value { get; set; }





        [ForeignKey("AssetId")]
        public Asset Asset { get; set; }

        [ForeignKey("SettingTypeId")]
        public SettingType SettingType { get; set; }

    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryAssetTypeSettingTypeRepository : InMemoryRepository<AssetTypeSettingType>, IAssetTypeSettingTypeRepository
    {
        private List<AssetTypeSettingType> _entities = null;

        public InMemoryAssetTypeSettingTypeRepository(IEnumerable<AssetTypeSettingType> entities)
            : base(entities)
        {
            _entities = entities as List<AssetTypeSettingType>;
        }






        public AssetTypeSettingType Get(int assetTypeId, int settingTypeId)
        {
            return _entities
                .Where(r => r.AssetTypeId == assetTypeId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public AssetTypeSettingType GetActive(int assetTypeId, int settingTypeId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.AssetTypeId == assetTypeId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public IEnumerable<AssetTypeSettingType> GetAllForAssetType(int assetTypeId)
        {
            return _entities
                .Where(r => r.AssetTypeId == assetTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllForSettingType(int settingTypeId)
        {
            return _entities
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllActiveForAssetType(int assetTypeId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.AssetTypeId == assetTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllActiveForSettingType(int settingTypeId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework.Internal;
using NUnit.Framework;
using Moq;

namespace Financial.Tests._DmitriNesteruk
{
    public interface ILogForMoq
    {
        bool Write(string msg);
    }


    public class BankAccountWithMoq
    {
        public int Balance { get; set; }
        private ILogForMoq _log;

        public BankAccountWithMoq(ILogForMoq log)
        {
            this._log = log;
        }

        public void Deposit(int amount)
        {
            _log.Write($"User has withdrawn {amount}");
            Balance += amount;
        }
    }

    [TestFixture]
    public class BankAccountWithMoqTests
    {
        private BankAccountWithMoq ba;

        [Test]
        public void Deposit_MockTest()
        {
            var log = new Mock<ILogForMoq>();
            ba = new BankAccountWithMoq(log.Object) {Balance = 100};
            ba.Deposit(100);

            Assert.That(ba.Balance, Is.EqualTo(200));
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class IndexLinkedAssetTypesViewModel
    {
        public IndexLinkedAssetTypesViewModel()
        {

        }

        public IndexLinkedAssetTypesViewModel(Core.Models.AssetType dtoAssetType,
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            Id = dtoAssetTypeSettingType.Id;
            SettingTypeId = dtoAssetTypeSettingType.SettingTypeId;
            IsActive = dtoAssetTypeSettingType.IsActive;
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
            AssetTypeIsActive = dtoAssetType.IsActive;
        }

        public int Id { get; set; }

        public int SettingTypeId { get; set; }

        public int AssetTypeId { get; set; }

        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }

        [Display(Name = "AssetType IsActive")]
        public bool AssetTypeIsActive { get; set; }

        [Display(Name = "AssetTypeSettingType IsActive")]
        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.Account
{
    public class IndexViewModel
    {
        public IndexViewModel() {}

        public IndexViewModel(Business.Models.Account bmAccount)
        {
            Id = bmAccount.AssetId;
            AssetName = bmAccount.AssetName;
            AssetTypeName = bmAccount.AssetTypeName;
        }


        public int Id { get; set; }
        [Display(Name = "Name")]
        public string AssetName { get; set; }
        [Display(Name = "Type")]
        public string AssetTypeName { get; set; }

    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetRepository : IRepository<Asset>
    {
        Asset GetActive(int assetId);
        IEnumerable<Asset> GetAllActiveOrderedByName();
    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using Financial.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Financial.Business.Services
{
    public class AccountTypeService : IAccountTypeService
    {
        private IUnitOfWork _unitOfWork;

        public AccountTypeService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        public Business.Models.AccountType GetAssetType(int assetTypeId)
        {
            var dtoAssetType = _unitOfWork.AssetTypes.Get(assetTypeId);
            if (dtoAssetType == null)
            {
                return null;
            }
            return new Business.Models.AccountType(dtoAssetType);
        }


        public List<Business.Models.AccountType> IndexGetModelList()
        {
            return _unitOfWork.AssetTypes.GetAll()
                .Where(r => r.IsActive)
                .OrderBy(r => r.Name)
                .Select(r => new Business.Models.AccountType(r))
                .ToList();
        }
        public int CreatePostUpdateDatabase(Business.Models.AccountType bmAssetType)
        {
            // check for existing name
            var exists = _unitOfWork.AssetTypes.GetAllActive()
                .Any(r => r.Name == bmAssetType.AssetTypeName);
            if (exists)
            {
                return 0;
            }

            // transfer bm to dto
            var dtoAssetType = new Core.Models.AssetType()
            {
                Name = bmAssetType.AssetTypeName,
                IsActive = true,
            };

            // update db
            _unitOfWork.AssetTypes.Add(dtoAssetType);
            _unitOfWork.CommitTrans();

            // return new ID
            return dtoAssetType.Id;
        }
        public Business.Models.AccountType EditGetModel(int assetTypeId)
        {
            var dtoAssetType = _unitOfWork.AssetTypes.Find(r => r.IsActive && r.Id == assetTypeId);
            if (dtoAssetType == null)
            {
                return null;
            }
            return new Business.Models.AccountType(dtoAssetType);
        }
        public string EditPostUpdateDatabase(Business.Models.AccountType bmAssetType)
        {
            // get dto
            var dtoAssetType = _unitOfWork.AssetTypes.Get(bmAssetType.AssetTypeId);
            if (dtoAssetType == null)
            {
                return "Invalid Asset Type";
            }

            // transfer bm to dto
            dtoAssetType.Name = bmAssetType.AssetTypeName;

            // update db
            _unitOfWork.CommitTrans();

            return "Success";
        }
        public Business.Models.AccountType DetailsGetModel(int assetTypeId)
        {
            var dtoAssetType = _unitOfWork.AssetTypes.Find(r => r.IsActive && r.Id == assetTypeId);
            if (dtoAssetType == null)
            {
                return null;
            }
            return new Business.Models.AccountType(dtoAssetType);
        }









        public List<SelectListItem> GetAssetTypesDropDownList(int? selectedId)
        {
            return _unitOfWork.AssetTypes.FindAll(r => r.IsActive)
                .Select(r => new SelectListItem()
                {
                    Value = r.Id.ToString(),
                    Selected = r.Id == selectedId,
                    Text = r.Name
                })
                .ToList();
        }




       


 

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountTypeAttributeTypes")]
    public class AssetTypeSettingType : BaseEntity
    {
        [Required]
        [Column("AccountTypeId")]
        public int AssetTypeId { get; set; }
        [Required]
        [Column("AttributeTypeId")]
        public int SettingTypeId { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeTransactionDescriptions
    {
        public static IEnumerable<TransactionDescription> InitialFakeTransactionDescriptions()
        {
            yield return new TransactionDescription() { Id = 1, Name = "TransactionDescription1", IsActive = true };
            yield return new TransactionDescription() { Id = 2, Name = "TransactionDescription2", IsActive = true };
            yield return new TransactionDescription() { Id = 3, Name = "TransactionDescription3", IsActive = false };
            yield return new TransactionDescription() { Id = 4, Name = "TransactionDescription4", IsActive = true };
            yield return new TransactionDescription() { Id = 5, Name = "TransactionDescription5", IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class EditLinkedAssetTypesViewModel
    {
        public EditLinkedAssetTypesViewModel()
        {
        }
        /*
        public EditLinkedAssetTypesViewModel(Core.Models.SettingType dtoSettingType, 
            List<Business.Models.BusinessModels.AssetTypeSettingType> atstLinks)
        {
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            LinkedAssetTypeSettingTypes = atstLinks;
        }
        */

        public int SettingTypeId { get; set; }

        [Display(Name = "Setting Type")]
        public string SettingTypeName { get; set; }

        public List<Business.Models.AccountTypeSettingType> LinkedAssetTypeSettingTypes { get; set; }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.AssetSetting;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;

namespace Financial.WebApplication.Controllers
{
    public class AssetSettingController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;

        public AssetSettingController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [HttpGet]
        public ActionResult Index(int assetId)
        {
            try
            {
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(assetId);
                if (dtoAsset != null)
                {
                    // get list of linked setting types
                    var dbAssetSettings = _unitOfWork.AssetSettings.GetAllActiveForAsset(dtoAsset.Id);

                    // create & transfer values to vm
                    var vmIndex = new List<IndexViewModel>();
                    foreach (var dtoAssetSetting in dbAssetSettings)
                    {
                        // transfer to dto
                        var dtoSettingType = _unitOfWork.SettingTypes.GetActive(dtoAssetSetting.SettingTypeId);

                        // validate dto & update vm
                        var vm = dtoAssetSetting == null 
                            ? new IndexViewModel(new AssetSetting(), assetId, dtoSettingType)
                            : new IndexViewModel(dtoAssetSetting, assetId, dtoSettingType);
                        vmIndex.Add(vm);
                    }
                    // display view
                    return PartialView("_Index", vmIndex);
                }
                return PartialView("_Index", new List<IndexViewModel>());
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetSetting");
            }
        }

        [HttpGet]
        public ActionResult Create(int assetId)
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }

            try
            {
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(assetId);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);

                    // transfer dto to vm
                    var vmCreate = new List<CreateViewModel>();
                    var dbAssetTypeSettingTypes = _unitOfWork.AssetTypeSettingTypes.GetAllActiveForAssetType(dtoAsset.AssetTypeId);
                    foreach(var dtoAssetTypeSettingType in dbAssetTypeSettingTypes)
                    {
                        var dtoSettingType = _unitOfWork.SettingTypes.GetActive(dtoAssetTypeSettingType.SettingTypeId);
                        if (dtoSettingType != null)
                        {
                            vmCreate.Add(new CreateViewModel(dtoAsset, dtoSettingType));
                        }
                    }

                    // display view
                    return View("Create", new CreateLinkedSettingTypesViewModel(dtoAsset, dtoAssetType, vmCreate));
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateLinkedSettingTypesViewModel vmCreate)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // validate vm 
                    if (vmCreate.CreateViewModels != null)
                    {
                        // transfer vm to dto
                        foreach (var vm in vmCreate.CreateViewModels)
                        {
                            _unitOfWork.AssetSettings.Add(new AssetSetting()
                            {
                                AssetId = vm.AssetId,
                                SettingTypeId = vm.SettingTypeId,
                                Value = vm.Value,
                                IsActive = true
                            });
                        }

                        // update db
                        _unitOfWork.CommitTrans();

                        // display view with message
                        TempData["SuccessMessage"] = "Records created";
                        return RedirectToAction("Details", "Asset", new { id = vmCreate.AssetId });
                    }
                    TempData["SuccessMessage"] = "No Linked Setting Types to Update";
                    return RedirectToAction("Details", "Asset", new { id = vmCreate.AssetId });
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpGet]
        public ActionResult Edit(int assetId)
        {
            try
            {
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(assetId);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);

                    // get list of linked setting types
                    var dbAssetTypeSettingTypes = _unitOfWork.AssetTypeSettingTypes.GetAllActiveForAssetType(dtoAsset.AssetTypeId);

                    // create & transfer values to vm
                    var vmEdit = new List<EditViewModel>();
                    foreach (var dtoAssetTypeSettingType in dbAssetTypeSettingTypes)
                    {
                        // transfer to dto
                        var dtoSettingType = _unitOfWork.SettingTypes.GetActive(dtoAssetTypeSettingType.SettingTypeId);
                        if (dtoSettingType != null)
                        {
                            var dtoAssetSetting = _unitOfWork.AssetSettings.GetActive(dtoAsset.Id, dtoSettingType.Id);
                            if (dtoAssetSetting != null)
                            {
                                vmEdit.Add(new EditViewModel(dtoAssetSetting, dtoAsset, dtoSettingType));
                            }
                        }
                    }

                    // display view
                    return View("Edit", new EditLinkedSettingTypesViewModel(dtoAsset, dtoAssetType, vmEdit));
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditLinkedSettingTypesViewModel vmEditLinkedSettingTypes)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // transfer vm to dto
                    foreach (var vmEdit in vmEditLinkedSettingTypes.EditViewModels)
                    {
                        // new entry?
                        if (vmEdit.Id == 0)
                        {
                            // YES. Create record
                            _unitOfWork.AssetSettings.Add(new AssetSetting()
                            {
                                AssetId = vmEditLinkedSettingTypes.AssetId,
                                SettingTypeId = vmEdit.SettingTypeId,
                                Value = vmEdit.Value,
                                IsActive = true
                            });
                        }
                        else
                        {
                            var dtoAssetSetting = _unitOfWork.AssetSettings.Get(vmEdit.Id);
                            dtoAssetSetting.Value = vmEdit.Value;
                        }
                    }

                    // update db
                    _unitOfWork.CommitTrans();

                    // display view with message
                    TempData["SuccessMessage"] = "Records updated";
                    return RedirectToAction("Details", "Asset", new { id = vmEditLinkedSettingTypes.AssetId });
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "Asset");
            }
        }


    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Utilities
{
    public class DataTypeUtility
    {
        public static int GetIntegerFromString(string stringValue)
        {
            int integerValue = 0;
            int.TryParse(stringValue, out integerValue);
            return integerValue;
        }

        public static string GetDateValidatedToShortDateString(DateTime? date)
        {
            var formatedDate = string.Empty;

            if (date != null)
            {
                var validDate = (DateTime)date;
                if (validDate > new DateTime(0001, 1, 1))
                {
                    formatedDate = validDate.ToString("MM/dd/yyyy");
                }
            }

            return formatedDate;
        }
    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.Business.Services
{
    public class SelectListService : ISelectListService
    {
        private IUnitOfWork _unitOfWork;

        public SelectListService()
        {
            _unitOfWork = new UnitOfWork();
        }

        public SelectListService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }



        public List<SelectListItem> TransactionCategories(string selectedId)
        {
            return _unitOfWork.TransactionCategories.GetAll()
                        .Where(r => r.IsActive)
                        .Select(r => new SelectListItem()
                        {
                            Value = r.Id.ToString(),
                            Selected = r.Id.ToString() == selectedId,
                            Text = r.Name
                        })
                        .OrderBy(r => r.Text)
                        .ToList();
        }

        public List<SelectListItem> TransactionDescriptions(string selectedId)
        {
            return _unitOfWork.TransactionDescriptions.GetAll()
                        .Where(r => r.IsActive)
                        .Select(r => new SelectListItem()
                        {
                            Value = r.Id.ToString(),
                            Selected = r.Id.ToString() == selectedId,
                            Text = r.Name
                        })
                        .ToList();
        }

        public List<SelectListItem> TransactionTypes(string selectedId)
        {
            return _unitOfWork.TransactionTypes.GetAll()
                        .Where(r => r.IsActive)
                        .Select(r => new SelectListItem()
                        {
                            Value = r.Id.ToString(),
                            Selected = r.Id.ToString() == selectedId,
                            Text = r.Name
                        })
                        .ToList();
        }


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;
using Financial.Core.Models;

namespace Financial.Business.ServiceInterfaces
{
    public interface IAccountSettingService
    {
        string GetAccountIdentificationInformation(Account bmAccount);
    }
}
<file_sep>﻿using Financial.Business.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.Business.ServiceInterfaces
{
    public interface IAccountTransactionService
    {
        List<AccountTransaction> GetListOfActiveTransactions();
        Account GetAccountForTransaction(int? assetId);
        bool AddTransaction(AccountTransaction bmAssetTransaction);
        AccountTransaction GetTransactionToEdit(int assetTransactionId);
        bool UpdateTransaction(AccountTransaction bmAssetTransaction);
        AccountTransaction GetTransactionToDelete(int assetTransactionId);
        bool DeleteTransaction(int assetTransactionId);

        List<SelectListItem> GetAccountSelectList(string selectedId);
        List<SelectListItem> GetTransactionTypeSelectList(string selectedId);
        List<SelectListItem> GetTransactionCategorySelectList(string selectedId);
    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using Financial.Business.Models;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core.Models;
using AssetType = Financial.Business.Models.AccountType;
using SettingType = Financial.Core.Models.SettingType;

namespace Financial.Business.Services
{
    public class AccountSettingService : IAccountSettingService
    {
        private IUnitOfWork _unitOfWork;

        public AccountSettingService()
        {
            _unitOfWork = new UnitOfWork();
        }

        public AccountSettingService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        public string GetAccountIdentificationInformation(Account bmAccount)
        {
            throw new NotImplementedException();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.RelationshipType
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Core.Models.RelationshipType dtoRelationshipType)
        {
            Id = dtoRelationshipType.Id;
            Name = dtoRelationshipType.Name;
            IsActive = dtoRelationshipType.IsActive;
        }


        public int Id { get; set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Display(Name = "Active")]
        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeTransactionCategories
    {
        public static IEnumerable<TransactionCategory> InitialFakeTransactionCategories()
        {
            yield return new TransactionCategory() { Id = 1, Name = "TransactionCategory1", IsActive = true };
            yield return new TransactionCategory() { Id = 2, Name = "TransactionCategory2", IsActive = true };
            yield return new TransactionCategory() { Id = 3, Name = "TransactionCategory3", IsActive = false };
            yield return new TransactionCategory() { Id = 4, Name = "TransactionCategory4", IsActive = true };
            yield return new TransactionCategory() { Id = 5, Name = "TransactionCategory5", IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeRelationshipTypes
    {
        public static IEnumerable<RelationshipType> InitialFakeRelationshipTypes()
        {
            yield return new RelationshipType() { Id = 1, Name = "RelationshipTypeName1", IsActive = true };
            yield return new RelationshipType() { Id = 2, Name = "RelationshipTypeName2", IsActive = true };
            yield return new RelationshipType() { Id = 3, Name = "RelationshipTypeName3", IsActive = false };
            yield return new RelationshipType() { Id = 4, Name = "RelationshipTypeName4", IsActive = true };
            yield return new RelationshipType() { Id = 5, Name = "RelationshipTypeName5", IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
    {
        private List<TEntity> _entities;

        public InMemoryRepository(IEnumerable<TEntity> entities)
        {
            _entities = entities as List<TEntity>;
        }

        public TEntity Get(int id)
        {
            return _entities.FirstOrDefault(r => r.Id == id);
        }

        public TEntity GetActive(int id)
        {
            return _entities.Where(r => r.IsActive).FirstOrDefault(r => r.Id == id);
        }

        public IEnumerable<TEntity> GetAll()
        {
            return _entities.ToList();
        }

        public IEnumerable<TEntity> GetAllActive()
        {
            return _entities.Where(r => r.IsActive).ToList();
        }

        public TEntity Find(Expression<Func<TEntity, bool>> predicate)
        {
            return _entities.AsQueryable().FirstOrDefault(predicate);
        }

        public IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate)
        {
            return _entities.AsQueryable().Where(predicate);
        }

        public bool Exists(int id)
        {
            return _entities.FirstOrDefault(r => r.Id == id) == null ? false : true;
        }

        public void Add(TEntity entity)
        {
            // database sets following values
            entity.Id = _entities.Count + 1;

            _entities.Add(entity);
        }

        public void AddRange(IEnumerable<TEntity> entities)
        {
            _entities.AddRange(entities);
        }

        public void Update(TEntity entity)
        {
            TEntity oldEntity = _entities.FirstOrDefault(r => r.Id == entity.Id);
            _entities.Remove(oldEntity);
            _entities.Add(entity);
        }

        public void Remove(TEntity entity)
        {
            _entities.Remove(entity);
        }

        public void RemoveRange(IEnumerable<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                _entities.Remove(entity);
            }
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class CreateViewModel
    {
        public CreateViewModel()
        {

        }

        public CreateViewModel(int assetTypeId, Core.Models.SettingType dtoSettingType)
        {
            AssetTypeId = assetTypeId;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            IsActive = false;
        }

        public CreateViewModel(int settingTypeId, Core.Models.AssetType dtoAssetType)
        {
            SettingTypeId = settingTypeId;
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
            IsActive = false;
        }


        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }

        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }

        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using Financial.Business.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.ServiceInterfaces
{
    public interface ISettingTypeService
    {
        AttributeType GetSettingType(int settingTypeId);
        List<AttributeType> GetListOfSettingTypes();
        int AddSettingType(AttributeType bmSettingType);
        bool EditSettingType(AttributeType bmSettingType);

    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public static class FakeAssets
    {
        public static IEnumerable<Asset> InitialFakeAssets()
        {
            yield return new Asset() { Id = 1, AssetTypeId = 2, Name = "AssetTypeName1", IsActive = true };
            yield return new Asset() { Id = 2, AssetTypeId = 1, Name = "AssetTypeName2", IsActive = true };
            yield return new Asset() { Id = 3, AssetTypeId = 2, Name = "AssetTypeName3", IsActive = false };
            yield return new Asset() { Id = 4, AssetTypeId = 2, Name = "AssetTypeName4", IsActive = true };
            yield return new Asset() { Id = 5, AssetTypeId = 2, Name = "AssetTypeName5", IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class EditLinkedSettingTypesViewModel
    {
        public EditLinkedSettingTypesViewModel()
        {
        }

        public EditLinkedSettingTypesViewModel(Business.Models.AccountType bmAssetType)
        {
            AssetTypeId = bmAssetType.AssetTypeId;
            AssetTypeName = bmAssetType.AssetTypeName;
        }


        public int AssetTypeId { get; set; }

        [Display(Name = "Name")]
        public string AssetTypeName { get; set; }

        [Display(Name = "Active")]
        public bool IsActive { get; set; }

        public List<Business.Models.AttributeType> SettingTypes { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Financial.Data;
using Financial.WebApplication.Controllers;
using Moq;
using Financial.Business;
using Financial.Business.Models;
using Financial.WebApplication.Models.ViewModels.AccountTransaction;
using System.Web.Mvc;
using Financial.Core.Models;
using Financial.Tests.Mocks;
using Financial.Core;

namespace Financial.Tests.WebApplication.Controllers
{
    [TestFixture]
    public class AccountTransactionControllerTests
    {
        private Asset _dbAsset;
        private AssetSetting _dbAssetSetting;
        private AssetTransaction _dbAssetTransaction;
        private AssetType _dbAssetType;
        private SettingType _dbSettingType;
        private TransactionCategory _dbTransactionCategory;
        private TransactionDescription _dbTransactionDescription;
        private TransactionType _dbTransactionType;
        private FinancialDbContext _fakeDbContext;
        private IUnitOfWork _fakeUnitOfWork;

        private Account _bmAccount;
        private AccountTransaction _bmAccountTransaction;
        private Mock<IBusinessService> _mockBusinessService;
        private IBusinessService _fakeBusinessService;
        private AccountTransactionController _controller;



        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _bmAccount = new Account
            {
                AssetId = 1,
                AssetName = "a",
                AssetTypeId = 2,
                AssetTypeName = "b",
            };
            _bmAccountTransaction = new AccountTransaction
            {
                AssetTransactionId = 3,
                AssetId = _bmAccount.AssetId,
                AssetName = _bmAccount.AssetName,
                AssetTypeId = _bmAccount.AssetTypeId,
                AssetTypeName = _bmAccount.AssetTypeName,
                DueDate = new DateTime(2018, 1, 2),
                ClearDate = new DateTime(2018, 3, 4),
                Amount = 123.45M,
                Note = "abc",
            };

            // setup DbContext
            Setup_FakeDbContext();

            // setup uow
            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);

            // setup Service
            _fakeBusinessService = new BusinessService(_fakeUnitOfWork);

            // setup controller
            _controller = new AccountTransactionController(_fakeBusinessService);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void Index_WhenCalled_ReturnIndexView_Test()
        {
            var result = _controller.Index();

            Assert.That(result.ViewName, Is.EqualTo("Index"));
        }

        [Test]
        public void Index_WhenCalled_ReturnsIndexViewModelList_Test()
        {
            var result = _controller.Index();

            Assert.That(result.ViewData.Model, Is.TypeOf<List<IndexViewModel>>());
        }

        [Test]
        public void Index_WhenCalled_ShouldCallOneTimeAccountTransactionServiceMethodGetListOfActiveTransactions_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetListOfActiveTransactions())
                .Returns(It.IsAny<List<AccountTransaction>>);

            _controller = new AccountTransactionController(_mockBusinessService.Object);

            _controller.Index();

            _mockBusinessService.Verify(bs => bs.AccountTransactionService.GetListOfActiveTransactions(),
                Times.Once);
        }

        [Test]
        public void Index_WhenAccountTransactionsFound_ReturnAccountTransactionsOrderedDescendingByDueDate_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();

            var olderDueDate = new DateTime(2018, 1, 2);
            var newerDueDate = new DateTime(2018, 3, 4);
            SetUp_Service_AccountTransactions_OrderedAscendingByDueDate(olderDueDate, newerDueDate);

            var result = _controller.Index();

            var vmActual = (List<IndexViewModel>)result.Model;

            Assert.Multiple(() =>
            {
                Assert.That(vmActual.Count, Is.EqualTo(2), "Count");
                Assert.That(vmActual[0].DueDate, Is.EqualTo(newerDueDate), "First Index");
                Assert.That(vmActual[1].DueDate, Is.EqualTo(olderDueDate), "Second Index");
            });
        }

        [Test]
        public void Index_WhenTempDataSuccessMessageIsNotNull_ReturnViewDataSuccessMessage_Test()
        {
            var expectedMessage = "test message";
            _controller.TempData["SuccessMessage"] = expectedMessage;

            var result = _controller.Index();

            var vResult = (ViewResult)result;

            Assert.That(vResult.ViewData["SuccessMessage"].ToString(), Is.EqualTo(expectedMessage));
        }

        [Test]
        public void Index_WhenTempDataErrorMessageIsNotNull_ReturnViewDataErrorMessage_Test()
        {
            var expectedMessage = "test message";
            _controller.TempData["ErrorMessage"] = expectedMessage;

            var result = _controller.Index();

            var vResult = (ViewResult)result;

            Assert.That(vResult.ViewData["ErrorMessage"].ToString(), Is.EqualTo(expectedMessage));
        }



        // Create

        [Test]
        public void Create_WhenCalled_ReturnCreateView_Test()
        {
            var result = (ViewResult)_controller.Create(assetId: null);

            Assert.That(result.ViewName, Is.EqualTo("Create"));
        }

        [Test]
        public void Create_WhenCalled_ReturnCreateViewModel_Test()
        {
            var result = (ViewResult)_controller.Create(assetId: null);

            Assert.That(result.Model, Is.InstanceOf<CreateViewModel>());
        }

        [Test]
        public void Create_WhenCalled_ShouldCallOneTimeGetAccountForTransaction_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetAccountForTransaction(null))
                .Returns(It.IsAny<Account>());

            _controller = new AccountTransactionController(_mockBusinessService.Object);

            _controller.Create(assetId: null);

            _mockBusinessService.Verify(bs => bs.AccountTransactionService.GetAccountForTransaction(It.IsAny<int?>()),
                Times.Once);
        }

        [Test]
        public void Create_WhenCalled_ShouldCallOneTimeGetAccountSelectList_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetAccountSelectList(null))
                .Returns(It.IsAny<List<SelectListItem>>());

            _controller = new AccountTransactionController(_mockBusinessService.Object);

            _controller.Create(assetId: null);

            _mockBusinessService.Verify(bs => bs.AccountTransactionService.GetAccountSelectList(It.IsAny<string>()),
                Times.Once);
        }

        [Test]
        public void Create_WhenCalled_ReturnAccountSelectList_Test()
        {
            Setup_FakeService();

            _controller = new AccountTransactionController(_fakeBusinessService);

            var result = (ViewResult)_controller.Create(assetId: null);

            var vmResult = (CreateViewModel)result.ViewData.Model;

            Assert.That(vmResult.Accounts.Count(), Is.Not.EqualTo(null));
        }

        [Test]
        public void Create_WhenCalled_ShouldCallOneTimeGetTransactionTypeSelectList_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetTransactionTypeSelectList(null))
                .Returns(It.IsAny<List<SelectListItem>>());

            _controller = new AccountTransactionController(_mockBusinessService.Object);

            _controller.Create(assetId: null);

            _mockBusinessService.Verify(bs => bs.AccountTransactionService.GetTransactionTypeSelectList(It.IsAny<string>()),
                Times.Once);
        }

        [Test]
        public void Create_WhenCalled_ReturnTransactionTypeSelectList_Test()
        {
            Setup_FakeService();

            _controller = new AccountTransactionController(_fakeBusinessService);

            var result = (ViewResult)_controller.Create(assetId: null);

            var vmResult = (CreateViewModel)result.ViewData.Model;

            Assert.That(vmResult.TransactionTypes.Count(), Is.Not.EqualTo(null));
        }

        [Test]
        public void Create_WhenCalled_ShouldCallOneTimeGetTransactionCategorySelectList_Test()
        {
            _mockBusinessService = new Mock<IBusinessService>();
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetTransactionCategorySelectList(null))
                .Returns(It.IsAny<List<SelectListItem>>());

            _controller = new AccountTransactionController(_mockBusinessService.Object);

            _controller.Create(assetId: null);

            _mockBusinessService.Verify(bs => bs.AccountTransactionService.GetTransactionCategorySelectList(It.IsAny<string>()),
                Times.Once);
        }

        [Test]
        public void Create_WhenCalled_ReturnTransactionCategorySelectList_Test()
        {
            Setup_FakeService();

            _controller = new AccountTransactionController(_fakeBusinessService);

            var result = (ViewResult)_controller.Create(assetId: null);

            var vmResult = (CreateViewModel)result.ViewData.Model;

            Assert.That(vmResult.TransactionCategories, Is.Not.EqualTo(null));
        }



        // private


        private void Setup_FakeDb()
        {
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset { Id = 2, AssetTypeId = _dbAssetType.Id, Name = "b", IsActive = true };
            _dbSettingType = new SettingType { Id = 3, Name = "c", IsActive = true };
            _dbAssetSetting = new AssetSetting { Id = 4, AssetId = _dbAsset.Id, SettingTypeId = _dbSettingType.Id, Value = "d", IsActive = true };
            _dbTransactionCategory = new TransactionCategory { Id = 5, Name = "e", IsActive = true };
            _dbTransactionDescription = new TransactionDescription { Id = 6, Name = "f", IsActive = true };
            _dbTransactionType = new TransactionType { Id = 7, Name = "g", IsActive = true };
            _dbAssetTransaction = new AssetTransaction
            {
                Id = 8,
                TransactionCategoryId = _dbTransactionCategory.Id,
                TransactionDescriptionId = _dbTransactionDescription.Id,
                TransactionTypeId = _dbTransactionType.Id,
                CheckNumber = "123",
                DueDate = new DateTime(1234, 5, 6),
                ClearDate = new DateTime(1234, 7, 8),
                Amount = 123.45M,
                Note = "abcdef",
                IsActive = true
            };
        }

        private void Setup_FakeDbContext()
        {
            // setup db
            Setup_FakeDb();

            // setup dbContext
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset },
                new List<AssetSetting> { _dbAssetSetting },
                new List<AssetTransaction> { _dbAssetTransaction },
                new List<AssetType> { _dbAssetType },
                new List<SettingType> { _dbSettingType },
                new List<TransactionCategory> { _dbTransactionCategory },
                new List<TransactionDescription> { _dbTransactionDescription },
                new List<TransactionType> { _dbTransactionType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetSetting> fakeAssetSettingList,
            List<AssetTransaction> fakeAssetTransactionList,
            List<AssetType> fakeAssetTypeList,
            List<SettingType> fakeSettingTypeList,
            List<TransactionCategory> fakeTransactionCategoryList,
            List<TransactionDescription> fakeTransactionDescriptionList,
            List<TransactionType> fakeTransactionTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetSettings: fakeAssetSettingList,
                assetTransactions: fakeAssetTransactionList,
                assetTypes: fakeAssetTypeList,
                settingTypes: fakeSettingTypeList,
                transactionCategories: fakeTransactionCategoryList,
                transactionDescriptions: fakeTransactionDescriptionList,
                transactionTypes: fakeTransactionTypeList);
        }

        private void Setup_FakeUnitOfWork()
        {
            Setup_FakeDbContext();

            _fakeUnitOfWork = new UnitOfWork(_fakeDbContext);
        }

        private void Setup_FakeService()
        {
            Setup_FakeUnitOfWork();

            _fakeBusinessService = new BusinessService(_fakeUnitOfWork);
        }

        private void SetUp_Service_AccountTransactions_OrderedAscendingByDueDate(DateTime olderDueDate, DateTime newerDueDate)
        {
            _mockBusinessService.Setup(bs => bs.AccountTransactionService.GetListOfActiveTransactions())
                .Returns(new List<AccountTransaction>
                {
                    new AccountTransaction
                    {
                        AssetTransactionId = 1, AssetId = 2, AssetName = "a", AssetTypeId = 3, AssetTypeName = "b",
                        DueDate = olderDueDate, ClearDate = new DateTime(2018, 5, 6), Amount = 123.45M, Note = "abc",
                    },
                    new AccountTransaction
                    {
                        AssetTransactionId = 1, AssetId = 2, AssetName = "a", AssetTypeId = 3, AssetTypeName = "b",
                        DueDate = newerDueDate, ClearDate = new DateTime(2018, 5, 6), Amount = 123.45M, Note = "abc",
                    },
                });

            _controller = new AccountTransactionController(_mockBusinessService.Object);
        }
    }
}
<file_sep>﻿using Financial.Business.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.Business.Models
{
    public class AccountTransaction
    {
        public AccountTransaction()
        {

        }

        public AccountTransaction(Core.Models.Asset dbAsset)
        {
            AssetId = dbAsset.Id;
            AssetName = dbAsset.Name;
        }

        public AccountTransaction(Core.Models.Asset dbAsset, string assetNameFormatted)
        {
            AssetId = dbAsset.Id;
            AssetName = assetNameFormatted;
        }

        public AccountTransaction(Core.Models.AssetTransaction dbAssetTransaction, 
            Core.Models.Asset dbAsset)
        {
            AssetTransactionId = dbAssetTransaction.Id;
            AssetId = dbAsset.Id;
            AssetName = dbAsset.Name;
            AssetTypeId = dbAsset.AssetTypeId;
            AssetTypeName = dbAsset.AssetType.Name;
            DueDate = dbAssetTransaction.DueDate;
            ClearDate = dbAssetTransaction.ClearDate;
            Amount = dbAssetTransaction.Amount;
            Note = dbAssetTransaction.Note;
        }

        public AccountTransaction(Core.Models.AssetTransaction dbAssetTransaction,
            Core.Models.Asset dbAsset,
            Core.Models.AssetType dbAssetType,
            string assetNameFormatted)
        {
            AssetTransactionId = dbAssetTransaction.Id;
            Amount = dbAssetTransaction.Amount;
            CheckNumber = dbAssetTransaction.CheckNumber;
            ClearDate = dbAssetTransaction.ClearDate;
            DueDate = dbAssetTransaction.DueDate;
            Note = dbAssetTransaction.Note;
            AssetId = dbAsset.Id;
            AssetName = assetNameFormatted;
            AssetTypeId = dbAssetType.Id;
            AssetTypeName = dbAssetType.Name;
            SelectedTransactionCategoryId = dbAssetTransaction.TransactionCategoryId.ToString();
        }

        public AccountTransaction(Core.Models.AssetTransaction dbAssetTransaction,
            Core.Models.Asset dbAsset,
            Core.Models.AssetType dbAssetType,
            Core.Models.TransactionType dbTransactionType,
            Core.Models.TransactionCategory dbTransactionCategory,
            string assetNameFormatted)
        {
            AssetTransactionId = dbAssetTransaction.Id;
            Amount = dbAssetTransaction.Amount;
            CheckNumber = dbAssetTransaction.CheckNumber;
            ClearDate = dbAssetTransaction.ClearDate;
            DueDate = dbAssetTransaction.DueDate;
            Note = dbAssetTransaction.Note;
            AssetId = dbAsset.Id;
            AssetName = assetNameFormatted;
            AssetTypeId = dbAssetType.Id;
            AssetTypeName = dbAssetType.Name;
            TransactionTypeName = dbTransactionType.Name;
            TransactionCategoryName = dbTransactionCategory.Name;
        }


        public int AssetTransactionId { get; set; }

        public int AssetId { get; set; }
        public string AssetName { get; set; }
        //public List<SelectListItem> AssetSelectList { get; set; }
        //public string SelectedAssetId { get; set; }

        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }

        public int TransactionTypeId { get; set; }
        public string TransactionTypeName { get; set; }
        //public List<SelectListItem> TransactionTypeSelectList { get; set; }
        //public string SelectedTransactionTypeId { get; set; }

        public int TransactionCategoryId { get; set; }
        public string TransactionCategoryName { get; set; }
        //public List<SelectListItem> TransactionCategorySelectList { get; set; }
        public string SelectedTransactionCategoryId { get; set; }

        public string CheckNumber { get; set; }
        public DateTime DueDate { get; set; }
        public DateTime ClearDate { get; set; }
        public decimal Amount { get; set; }
        public string Note { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace Financial.Tests._DmitriNesteruk
{
    public class BankAccount
    {
        public int Balance { get; private set; }

        public BankAccount(int startingBalance)
        {
            Balance = startingBalance;
        }

        public void Deposit(int amount)
        {
            if (amount <= 0)
                throw new ArgumentException(
                    "Deposit amount must be positive",
                    nameof(amount));

            Balance += amount;
        }

        public bool Withdraw(int amount)
        {
            if (Balance >= amount)
            {
                Balance -= amount;
                return true;
            }

            return false;
        }
    }


    [TestFixture]
    public class BankAccountTests
    {
        private BankAccount ba;

        [SetUp]
        public void SetUp()
        {
            // https://github.com/nunit
            ba = new BankAccount(100);
        }

        [Test]
        public void WhenWarn_ReturnWarningMessages()
        {
            Warn.If(2 + 2 != 5);
            Warn.If(2 + 2, Is.Not.EqualTo(5));
            Warn.If(() => 2 + 2, Is.Not.EqualTo(5).After(2000));

            Warn.Unless(2 + 2 == 5);
            Warn.Unless(2 + 2, Is.EqualTo(5));
            Warn.Unless(() => 2 + 2, Is.EqualTo(5).After(2000));

            Assert.Warn("This is a warning");
        }

        [Test]
        public void WhenMultipleAsserts_ReturnAllFailedMessages()
        {
            Assert.Multiple(() =>
            {
                Assert.That(2 + 2, Is.EqualTo(4));
                Assert.That(3 + 3, Is.EqualTo(6));
            });
        }

        [Test]
        public void Deposit_WhenAmountIsPositiveNumber_BalanceIncreases()
        {
            ba.Deposit(100);

            Assert.That(ba.Balance, Is.EqualTo(200));
        }

        [Test]
        public void Deposit_WhenAmountIsNotPositive_ThrowArgumentException()
        {
            var ex = Assert.Throws<ArgumentException>(
                () => ba.Deposit(-1)
                );
            StringAssert.StartsWith("Deposit amount must be positive",
                ex.Message);
        }

        [Test]
        [TestCase(50, true, 50)]
        [TestCase(100, true, 0)]
        [TestCase(1000, false, 100)]
        public void Withdraw_WhenAmountToWithdrawShouldSucceed_UpdateBalance(
            int amountToWithdraw, bool shouldSucceed, int expectedBalance)
        {
            var result = ba.Withdraw(amountToWithdraw);
            
            Assert.Multiple(() =>
            {
                Assert.That(result, Is.EqualTo(shouldSucceed));
                Assert.That(expectedBalance, Is.EqualTo(ba.Balance));
            });
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("Accounts")]
    public class Asset : BaseEntity
    {
        [Required]
        [Display(Name = "AssetType ID")]
        [Column("AccountTypeId")]
        public int AssetTypeId { get; set; }

        [Required]
        public string Name { get; set; }


        [ForeignKey("AssetTypeId")]
        public AssetType AssetType { get; set; }

        //public ICollection<AssetSetting> AssetSettings { get; set; }
        //public ICollection<AssetTransaction> AssetTransactions { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetSetting
{
    public class IndexViewModel
    {
        public IndexViewModel() { }

        public IndexViewModel(Core.Models.AssetSetting dtoAssetSetting, int assetId,
            Core.Models.SettingType dtoSettingType )
        {
            Id = dtoAssetSetting.Id;
            AssetId = assetId;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            AssetSettingValue = dtoAssetSetting.Value;
        }


        public int Id { get; set; }
        public int AssetId { get; set; }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }
        public string AssetSettingValue { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.Account
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Core.Models.Asset dtoAsset, List<SelectListItem> sliAssetTypes)
        {
            Id = dtoAsset.Id;
            Name = dtoAsset.Name;
            SelectedAssetTypeId = dtoAsset.AssetTypeId.ToString();
            AssetTypes = sliAssetTypes;
        }


        public int Id { get; set; }
        public string Name { get; set; }
        [Required]
        [Display(Name = "Type")]
        public string SelectedAssetTypeId { get; set; }
        public IEnumerable<SelectListItem> AssetTypes { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetTypeSettingTypeRepository : IRepository<AssetTypeSettingType>
    {
        AssetTypeSettingType Get(int assetTypeId, int settingTypeId);
        AssetTypeSettingType GetActive(int assetTypeId, int settingTypeId);
        IEnumerable<AssetTypeSettingType> GetAllForAssetType(int assetTypeId);
        IEnumerable<AssetTypeSettingType> GetAllForSettingType(int settingTypeId);
        IEnumerable<AssetTypeSettingType> GetAllActiveForAssetType(int assetTypeId);
        IEnumerable<AssetTypeSettingType> GetAllActiveForSettingType(int settingTypeId);
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class IndexViewModel
    {
        public IndexViewModel() { }

        public IndexViewModel(Business.Models.AccountTransaction bmAssetTransaction)
        {
            Id = bmAssetTransaction.AssetTransactionId;
            AssetId = bmAssetTransaction.AssetId;
            AssetName = bmAssetTransaction.AssetName;
            DueDate = bmAssetTransaction.DueDate;
            ClearDate = bmAssetTransaction.ClearDate;
            TransactionType = bmAssetTransaction.TransactionTypeName;
            Amount = bmAssetTransaction.Amount;
            Note = bmAssetTransaction.Note;
        }

        public int Index { get; set; }
        public int Id { get; set; }
        public int AssetId { get; set; }
        [Display(Name = "Asset Name")]
        public string AssetName { get; set; }
        [Required]
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime ClearDate { get; set; }
        public string TransactionType { get; set; }
        public string Income { get; set; }
        public string Expense { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
        public decimal Amount { get; set; }
        [Display(Name = "Balance")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
        public decimal Total { get; set; }
        public string Note { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Financial.Business.Models;
using Financial.Business.ServiceInterfaces;
using Financial.Business.Utilities;
using Financial.Data;
using Financial.Core.Models;

namespace Financial.Business.Services
{
    public class AccountTransactionService : IAccountTransactionService
    {
        private IUnitOfWork _unitOfWork;

        public AccountTransactionService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        // Index


        public List<AccountTransaction> GetListOfActiveTransactions()
        {
            // create object to return
            var bmAssetTransactionList = new List<AccountTransaction>();

            // get active transactions
            var dbAssetTransactionList = _unitOfWork.AssetTransactions.GetAllActiveByDueDate().ToList();

            // transfer dto to bm
            foreach (var dbAssetTransaction in dbAssetTransactionList)
            {
                // account information
                var dbAsset = _unitOfWork.Assets.Get(dbAssetTransaction.AssetId);
                if (dbAsset == null)
                    return new List<AccountTransaction>();

                // format values
                dbAsset.Name = GetAssetNameWithAccountNumber(dbAsset);
                dbAssetTransaction.Amount = TransactionUtility.FormatAmount(
                    dbAssetTransaction.TransactionTypeId, 
                    dbAssetTransaction.Amount);

                // transfer to bm
                bmAssetTransactionList.Add(new AccountTransaction(
                    dbAssetTransaction,
                    dbAsset));
            }

            return bmAssetTransactionList;
        }


        // Create


        public Account GetAccountForTransaction(int? assetId)
        {
            if (assetId == null || assetId == 0)
                return null;

            var dbAsset = _unitOfWork.Assets.Get((int)assetId);
            if (dbAsset == null)
                return null;

            dbAsset.Name = GetAssetNameWithAccountNumber(dbAsset);

            return new Account(dbAsset);
        }
        /*
        public AccountTransaction GetTransactionOptions(int? assetId)
        {
            var intAssetId = DataTypeUtility.GetIntegerFromString(assetId.ToString());

            // get asset information
            var dtoAsset = GetAssetFromDatabase(intAssetId);
            if (dtoAsset == null)
            {
                throw new ArgumentNullException();
                //return new Business.Models.AssetTransaction();
            }

            // asset name with additional information
            var formattedAssetName = GetAssetNameWithAccountNumber(dtoAsset);

            // transfer dto to bm
            var bmAssetTransaction = new AccountTransaction(dtoAsset, formattedAssetName);

            // get sli
            //bmAssetTransaction.AssetSelectList = GetAssetSelectList(intAssetId.ToString());
            //bmAssetTransaction.TransactionTypeSelectList = GetTransactionTypeSelectList(null);
            //bmAssetTransaction.TransactionCategorySelectList = GetTransactionCategorySelectList(null);

            // valid asset information
            return bmAssetTransaction;
        }
        */
        /*
        private Core.Models.Asset GetAssetFromDatabase(int assetId)
        {
            return _unitOfWork.Assets.Get(assetId);
        }
        */
        private string GetAssetNameWithAccountNumber(Asset dbAsset)
        {
            var dbAssetSetting = _unitOfWork.AssetSettings.GetActive(dbAsset.Id, SettingType.IdForAccountNumber);
            if (dbAssetSetting == null)
                return dbAsset.Name;

            return AccountUtility.FormatAccountName(dbAsset.Name, dbAsset.AssetTypeId, dbAssetSetting.Value);
        }
        public List<SelectListItem> GetAccountSelectList(string selectedId)
        {
            return _unitOfWork.Assets.GetAllActiveOrderedByName()
                .Select(r => new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = GetAssetNameWithAccountNumber(r),
                    Selected = r.Id.ToString() == selectedId
                })
                .ToList();
        }
        public List<SelectListItem> GetTransactionTypeSelectList(string selectedId)
        {
            return _unitOfWork.TransactionTypes.GetAllActiveOrderedByName()
                .Select(r => new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Name,
                    Selected = r.Id.ToString() == selectedId,
                })
                .ToList();
        }
        public List<SelectListItem> GetTransactionCategorySelectList(string selectedId)
        {
            return _unitOfWork.TransactionCategories.GetAllActiveOrderedByName()
                .Select(r => new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Name,
                    Selected = r.Id.ToString() == selectedId,
                })
                .ToList();
            /*
            return _unitOfWork.TransactionCategories.GetAll()
                .Where(r => r.IsActive)
                .Select(r => new SelectListItem()
                {
                    Value = r.Id.ToString(),
                    Selected = r.Id.ToString() == selectedId,
                    Text = r.Name
                })
                .OrderBy(r => r.Text)
                .ToList();
            */
        }


        public bool AddTransaction(Business.Models.AccountTransaction bmAssetTransaction)
        {
            // validate input
            if(bmAssetTransaction == null)
            {
                return false;
            }

            // validate ID
            if (_unitOfWork.Assets.Get(bmAssetTransaction.AssetId) == null)
            {
                return false;
            }
            if (_unitOfWork.TransactionTypes.Get(bmAssetTransaction.TransactionTypeId) == null)
            {
                return false;
            }
            if (_unitOfWork.TransactionCategories.Get(bmAssetTransaction.TransactionCategoryId) == null)
            {
                return false;
            }

            // transfer vm to dto
            _unitOfWork.AssetTransactions.Add(new Core.Models.AssetTransaction()
            {
                AssetId = bmAssetTransaction.AssetId,
                TransactionTypeId = bmAssetTransaction.TransactionTypeId,
                TransactionCategoryId = bmAssetTransaction.TransactionCategoryId,
                CheckNumber = bmAssetTransaction.CheckNumber,
                DueDate = bmAssetTransaction.DueDate,
                ClearDate = bmAssetTransaction.ClearDate,
                Amount = bmAssetTransaction.Amount,
                Note = bmAssetTransaction.Note,
                IsActive = true
            });

            // update db
            _unitOfWork.CommitTrans();

            return true;
        }


        // Edit


        public Business.Models.AccountTransaction GetTransactionToEdit(int assetTransactionId)
        {
            var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(assetTransactionId);
            if (dtoAssetTransaction != null)
            {
                var dtoAsset = _unitOfWork.Assets.Get(dtoAssetTransaction.AssetId);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);
                    if (dtoAssetType != null)
                    {
                        // add additional identifying info to asset title
                        var assetNameFormatted = GetAssetIdentificationInformation(dtoAsset);

                        // transfer dto to sli
                        var sliTransactionTypes = GetTransactionTypeSelectList(dtoAssetTransaction.TransactionTypeId.ToString());
                        var sliTransactionCategories = GetTransactionCategorySelectList(dtoAssetTransaction.TransactionCategoryId.ToString());

                        return new Business.Models.AccountTransaction(dtoAssetTransaction,
                            dtoAsset,
                            dtoAssetType,
                            assetNameFormatted
                            //sliTransactionTypes,
                            //sliTransactionCategories
                            );
                    }
                }
            }

            return null;
        }
        public string GetAssetIdentificationInformation(Core.Models.Asset dtoAsset)
        {
            // validate input
            if(dtoAsset == null)
            {
                return string.Empty;
            }

            // get additional information
            var dtoAssetSetting = _unitOfWork.AssetSettings.GetAll()
                .Where(r => r.IsActive)
                .FirstOrDefault(r => r.AssetId == dtoAsset.Id);
            if(dtoAssetSetting != null)
            {
                return AccountUtility.FormatAccountName(dtoAsset.Name, dtoAsset.AssetTypeId, dtoAssetSetting.Value);
            }

            // get standard information
            return dtoAsset.Name;
        }
 

        public bool UpdateTransaction(Business.Models.AccountTransaction bmAssetTransaction)
        {
            // validate input
            if(bmAssetTransaction == null)
            {
                return false;
            }

            // validate Id
            if (_unitOfWork.Assets.Get(bmAssetTransaction.AssetId) == null ||
                _unitOfWork.TransactionTypes.Get(bmAssetTransaction.TransactionTypeId) == null ||
                _unitOfWork.TransactionCategories.Get(bmAssetTransaction.TransactionCategoryId) == null)
            {
                return false;
            }

            // get dto
            var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(bmAssetTransaction.AssetTransactionId);
            if(dtoAssetTransaction == null)
            {
                return false;
            }

            // update dto
            dtoAssetTransaction.TransactionTypeId = bmAssetTransaction.TransactionTypeId;
            dtoAssetTransaction.TransactionCategoryId = bmAssetTransaction.TransactionCategoryId;
            dtoAssetTransaction.CheckNumber = bmAssetTransaction.CheckNumber;
            dtoAssetTransaction.DueDate = bmAssetTransaction.DueDate;
            dtoAssetTransaction.ClearDate = bmAssetTransaction.ClearDate;
            dtoAssetTransaction.Amount = bmAssetTransaction.Amount;
            dtoAssetTransaction.Note = bmAssetTransaction.Note;

            // update db
            _unitOfWork.CommitTrans();

            return true;
        }


        // Delete


        public AccountTransaction GetTransactionToDelete(int assetTransactionId)
        {
            var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(assetTransactionId);
            if (dtoAssetTransaction != null)
            {
                var dtoAsset = _unitOfWork.Assets.Get(dtoAssetTransaction.AssetId);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);
                    if (dtoAssetType != null)
                    {
                        var dtoTransactionType = _unitOfWork.TransactionTypes.Get(dtoAssetTransaction.TransactionTypeId);
                        if(dtoTransactionType != null)
                        {
                            var dtoTransactionCategory = _unitOfWork.TransactionCategories.Get(dtoAssetTransaction.TransactionCategoryId);
                            if (dtoTransactionCategory != null)
                            {
                                // add additional identifying info to asset name
                                dtoAsset.Name = GetAssetIdentificationInformation(dtoAsset);

                                return new AccountTransaction(dtoAssetTransaction, dtoAsset);
                            }
                        }
                    }
                }
            }

            return null;
        }


        public bool DeleteTransaction(int assetTransactionId)
        {
            // get dto
            var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(assetTransactionId);
            if (dtoAssetTransaction == null)
            {
                return false;
            }

            // update dto
            dtoAssetTransaction.IsActive = false;
            
            // update db
            _unitOfWork.CommitTrans();

            return true;
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.Account
{
    public class DetailsViewModel
    {
        public DetailsViewModel() { }

        public DetailsViewModel(Core.Models.Asset dtoAsset, Core.Models.AssetType dtoAssetType)
        {
            Id = dtoAsset.Id;
            Name = dtoAsset.Name;
            AssetTypeName = dtoAssetType.Name;
        }


        public int Id { get; set; }
        public string Name { get; set; }
        [Display(Name = "Type")]
        public string AssetTypeName { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetTransactionRepository : IRepository<AssetTransaction>
    {
        IEnumerable<AssetTransaction> GetAllActiveByDueDate();
        IEnumerable<AssetTransaction> GetAllActiveByDescendingDueDate(int assetId);
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core.Models;

namespace Financial.Business.Tests.Fakes.Database
{
    public static class FakeAssetTypes
    {
        public static IEnumerable<AssetType> InitialFakeAssetTypes()
        {
            yield return new AssetType() { Id = 1, Name = "AssetTypeName1", IsActive = true };
            yield return new AssetType() { Id = 2, Name = "AssetTypeName2", IsActive = true };
            yield return new AssetType() { Id = 3, Name = "AssetTypeName3", IsActive = false };
            yield return new AssetType() { Id = 4, Name = "AssetTypeName4", IsActive = true };
            yield return new AssetType() { Id = 5, Name = "AssetTypeName5", IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.AssetType;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;
using Financial.Business.ServiceInterfaces;

namespace Financial.WebApplication.Controllers
{
    public class AssetTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IAccountTypeService _assetTypeService;

        
        public AssetTypeController(IUnitOfWork unitOfWork, IAccountTypeService assetTypeService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _assetTypeService = assetTypeService;
        }

        [HttpGet]
        public ViewResult Index()
        {
            try
            {   
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // transfer bm to vm
                var vmIndex = _assetTypeService.IndexGetModelList()
                    .Select(r => new IndexViewModel(r))
                    .ToList();

                return View("Index", vmIndex);
            }
            catch(Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return View("Index", new List<IndexViewModel>());
            }
        }

        [HttpGet]
        public ActionResult Create()
        {
            try
            {
                return View("Create");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return RedirectToAction("Index", "AssetType");
                }

                // transfer vm to bm
                var bmAssetType = new Business.Models.AccountType()
                {
                    AssetTypeName = vmCreate.Name,
                };

                // update db
                bmAssetType.AssetTypeId = _assetTypeService.CreatePostUpdateDatabase(bmAssetType);
                if(bmAssetType.AssetTypeId == 0)
                {
                    ViewData["ErrorMessage"] = "Name already exists";
                    return View("Create", vmCreate);
                }

                // display View with message
                TempData["SuccessMessage"] = "Asset Type Created";
                return RedirectToAction("CreateLinkedSettingTypes", "AssetTypeSettingType", new { assetTypeId = bmAssetType.AssetTypeId });
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            try
            {
                // get bm
                var bmAssetType = _assetTypeService.EditGetModel(id);
                if(bmAssetType == null)
                {
                    TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                    return RedirectToAction("Index", "AssetType");
                }

                // transfer bm to vm
                return View("Edit", new EditViewModel(bmAssetType));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return RedirectToAction("Index", "AssetType");
                }

                // transfer vm to bm
                var bmAssetType = new Business.Models.AccountType()
                {
                    AssetTypeId = vmEdit.Id,
                    AssetTypeName = vmEdit.Name,
                };

                // update db
                var message = _assetTypeService.EditPostUpdateDatabase(bmAssetType);
                if(message != "Success")
                {
                    TempData["ErrorMessage"] = message;
                    return RedirectToAction("Index", "AssetType");
                }

                TempData["SuccessMessage"] = "Record updated.";
                return RedirectToAction("Index", "AssetType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpGet]
        public ActionResult Details(int id)
        {
            try
            {
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // transfer bm to vm
                var bmAssetType = _assetTypeService.DetailsGetModel(id);
                if(bmAssetType == null)
                {
                    TempData["ErrorMessage"] = "Unable to display record. Try again.";
                    return RedirectToAction("Index", "AssetType");
                }

                return View("Details", new DetailsViewModel(bmAssetType));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }

        }
    }
}<file_sep>﻿using Financial.Business.Utilities;
using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.SettingType;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;

namespace Financial.WebApplication.Controllers
{
    public class SettingTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;


        public SettingTypeController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [HttpGet]
        public ViewResult Index()
        {
            try
            {
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // transfer bm to vm
                var vmIndex = _businessService.SettingTypeService.GetListOfSettingTypes()
                    .OrderBy(r => r.SettingTypeName)
                    .Select(r => new IndexViewModel(r))
                    .ToList();

                return View("Index", vmIndex);
            }
            catch(Exception)
            {
                ViewData["ErrorMessage"] = "Encountered problem";
                return View("Index", new List<IndexViewModel>());
            }
        }

        [HttpGet]
        public ActionResult Create()
        {
            try
            {
                return View("Create");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return RedirectToAction("Index", "SettingType");
                }

                // transfer vm to bm
                var bmSettingType = new Business.Models.AttributeType()
                {
                    SettingTypeName = vmCreate.Name,
                };

                // update db
                bmSettingType.SettingTypeId = _businessService.SettingTypeService.AddSettingType(bmSettingType);
                if (bmSettingType.SettingTypeId == 0)
                {
                    ViewData["ErrorMessage"] = "Name already exists";
                    return View("Create", vmCreate);
                }

                // display View with message
                TempData["SuccessMessage"] = "Setting Type Created";
                return RedirectToAction("CreateLinkedAssetTypes", "AssetTypeSettingType", new { settingTypeId = bmSettingType.SettingTypeId });
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            try
            {
                // get bm
                var bmSettingType = _businessService.SettingTypeService.GetSettingType(id);
                if (bmSettingType == null)
                {
                    TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                    return RedirectToAction("Index", "SettingType");
                }

                // transfer bm to vm
                return View("Edit", new EditViewModel(bmSettingType));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return RedirectToAction("Index", "SettingType");
                }

                // transfer vm to bm
                var bmSettingType = new Business.Models.AttributeType()
                {
                    SettingTypeId = vmEdit.Id,
                    SettingTypeName = vmEdit.Name,
                };

                // update db
                var updated = _businessService.SettingTypeService.EditSettingType(bmSettingType);
                if (!updated)
                {
                    TempData["ErrorMessage"] = "Problem updating record. Try again.";
                    return RedirectToAction("Index", "SettingType");
                }

                TempData["SuccessMessage"] = "Record updated.";
                return RedirectToAction("Index", "SettingType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpGet]
        public ActionResult Details(int id)
        {
            try
            {
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // transfer bm to vm
                var bmSettingType = _businessService.SettingTypeService.GetSettingType(id);
                if (bmSettingType == null)
                {
                    TempData["ErrorMessage"] = "Unable to display record. Try again.";
                    return RedirectToAction("Index", "SettingType");
                }

                return View("Details", new DetailsViewModel(bmSettingType));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }


    }
}<file_sep>﻿using Financial.Business;
using Financial.Core;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Financial.WebApplication.Controllers
{
    public class BaseController : Controller
    {
        public BaseController()
        {
        }

    }
}<file_sep>﻿using Financial.Business.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.Business.ServiceInterfaces
{
    public interface IAccountTypeService
    {
        List<Business.Models.AccountType> IndexGetModelList();
        int CreatePostUpdateDatabase(AccountType bmAssetType);
        Business.Models.AccountType EditGetModel(int assetTypeId);
        string EditPostUpdateDatabase(Business.Models.AccountType bmAssetType);
        Business.Models.AccountType DetailsGetModel(int assetTypeId);



        List<SelectListItem> GetAssetTypesDropDownList(int? selectedId);

        

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AttributeTypes")]
    public class SettingType : BaseEntity
    {
        [Required]
        public string Name { get; set; }


        public ICollection<AssetSetting> AssetSettings { get; set; }



        public static readonly int IdForAccountNumber = 1;
    }
}
<file_sep>﻿using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data
{
    public interface IUnitOfWork : IDisposable
    {
        IAssetSettingRepository AssetSettings { get; }
        IAssetRelationshipRepository AssetRelationships { get; }
        IAssetRepository Assets { get; }
        IAssetTransactionRepository AssetTransactions { get; }
        IAssetTypeSettingTypeRepository AssetTypeSettingTypes { get; }
        IAssetTypeRelationshipTypeRepository AssetTypeRelationshipTypes { get; }
        IAssetTypeRepository AssetTypes { get; }
        IParentChildRelationshipTypeRepository ParentChildRelationshipTypes { get; set; }
        IRelationshipTypeRepository RelationshipTypes { get; }
        ISettingTypeRepository SettingTypes { get; }
        ITransactionCategoryRepository TransactionCategories { get; }
        ITransactionDescriptionRepository TransactionDescriptions { get; }
        ITransactionTypeRepository TransactionTypes { get; }

        void BeginTrans();
        void CommitTrans();
        void RollBackTrans();
        void Complete();
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class AssetTypeSettingTypeRepository : Repository<AssetTypeSettingType>, IAssetTypeSettingTypeRepository
    {
        public AssetTypeSettingTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }



        public AssetTypeSettingType Get(int assetTypeId, int settingTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.AssetTypeId == assetTypeId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public AssetTypeSettingType GetActive(int assetTypeId, int settingTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.IsActive)
                .Where(r => r.AssetTypeId == assetTypeId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public IEnumerable<AssetTypeSettingType> GetAllForAssetType(int assetTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.AssetTypeId == assetTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllForSettingType(int settingTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllActiveForAssetType(int assetTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.IsActive)
                .Where(r => r.AssetTypeId == assetTypeId)
                .ToList();
        }

        public IEnumerable<AssetTypeSettingType> GetAllActiveForSettingType(int settingTypeId)
        {
            return FinancialDbContext.AssetTypesSettingTypes
                .Where(r => r.IsActive)
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System.Collections.Generic;
using System.Linq;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryAssetTransactionRepository : InMemoryRepository<AssetTransaction>, IAssetTransactionRepository
    {
        private List<AssetTransaction> _entities = null;

        public InMemoryAssetTransactionRepository(IEnumerable<AssetTransaction> entities)
            : base(entities)
        {
            _entities = entities as List<AssetTransaction>;
        }



        public IEnumerable<AssetTransaction> GetAllActiveByDescendingDueDate(int assetId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .OrderByDescending(r => r.DueDate)
                .ToList();
        }

        public IEnumerable<AssetTransaction> GetAllActiveByDueDate()
        {
            return _entities
                .Where(r => r.IsActive)
                .OrderBy(r => r.DueDate)
                .ToList();
        }


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class DisplayForAssetViewModel
    {
        public DisplayForAssetViewModel() { }

        public DisplayForAssetViewModel(Core.Models.AssetTransaction dtoAssetTransaction, 
            string clearDate, Core.Models.TransactionCategory dtoTransactionCategory)
        {
            Id = dtoAssetTransaction.Id;
            DueDate = dtoAssetTransaction.DueDate.ToString("MM/dd/yyyy");
            ClearDate = clearDate;
            Category = dtoTransactionCategory.Name;
            Amount = dtoAssetTransaction.Amount;
            Note = dtoAssetTransaction.Note;
        }


        public int Id { get; set; }
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public string DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public string ClearDate { get; set; }
        public string Category { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
        public decimal Amount { get; set; }
        public string Note { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class IndexLinkedSettingTypesViewModel
    {
        public IndexLinkedSettingTypesViewModel()
        {

        }
        public IndexLinkedSettingTypesViewModel(Business.Models.AttributeType bmSettingType)
        {
            Id = bmSettingType.AssetTypeSettingTypeId;
            //AssetTypeId = dtoAssetTypeSettingType.AssetTypeId;
            //IsActive = dtoAssetTypeSettingType.IsActive;
            SettingTypeId = bmSettingType.SettingTypeId;
            SettingTypeName = bmSettingType.SettingTypeName;
            //SettingTypeIsActive = dtoSettingType.IsActive;
        }
        public IndexLinkedSettingTypesViewModel(Business.Models.AccountType bmAssetType)
        {
            Id = bmAssetType.AssetTypeSettingTypeId;
            //AssetTypeId = dtoAssetTypeSettingType.AssetTypeId;
            //IsActive = dtoAssetTypeSettingType.IsActive;
            AssetTypeId = bmAssetType.AssetTypeId;
            AssetTypeName = bmAssetType.AssetTypeName;
            //SettingTypeIsActive = dtoSettingType.IsActive;
        }
        public IndexLinkedSettingTypesViewModel(Core.Models.SettingType dtoSettingType,
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            Id = dtoAssetTypeSettingType.Id;
            AssetTypeId = dtoAssetTypeSettingType.AssetTypeId;
            IsActive = dtoAssetTypeSettingType.IsActive;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            SettingTypeIsActive = dtoSettingType.IsActive;
        }

        public int Id { get; set; }

        public int AssetTypeId { get; set; }

        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }

        public int SettingTypeId { get; set; }

        [Display(Name = "Setting Type")]
        public string SettingTypeName { get; set; }

        [Display(Name = "SettingType IsActive")]
        public bool SettingTypeIsActive { get; set; }

        [Display(Name = "AssetTypeSettingType IsActive")]
        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryParentChildRelationshipTypeRepository : InMemoryRepository<ParentChildRelationshipType>, IParentChildRelationshipTypeRepository
    {
        private List<ParentChildRelationshipType> _entities = null;

        public InMemoryParentChildRelationshipTypeRepository(IEnumerable<ParentChildRelationshipType> entities)
            : base(entities)
        {
            _entities = entities as List<ParentChildRelationshipType>;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.Business.ServiceInterfaces
{
    public interface ISelectListService
    {
        List<SelectListItem> TransactionCategories(string selectedId);
        List<SelectListItem> TransactionDescriptions(string selectedId);
        List<SelectListItem> TransactionTypes(string selectedId);
    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryAssetSettingRepository : InMemoryRepository<AssetSetting>, IAssetSettingRepository
    {
        private List<AssetSetting> _entities = null;

        public InMemoryAssetSettingRepository(IEnumerable<AssetSetting> entities)
            : base(entities)
        {
            _entities = entities as List<AssetSetting>;
        }




        public AssetSetting GetActive(int assetId, int settingTypeId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public IEnumerable<AssetSetting> GetAllActiveForAsset(int assetId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .ToList();
        }


        public IEnumerable<AssetSetting> GetAllActiveForSettingType(int settingTypeId)
        {
            return _entities
                .Where(r => r.IsActive)
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.ParentChildRelationshipType
{
    public class DeleteViewModel
    {
        public DeleteViewModel() { }

        public DeleteViewModel(Core.Models.ParentChildRelationshipType dtoParentChildRelationshipType,
            Core.Models.RelationshipType dtoRelationshipType,
            Core.Models.RelationshipType dtoParentRelationshipType, 
            Core.Models.RelationshipType dtoChildRelationshipType)
        {
            Id = dtoParentChildRelationshipType.Id;
            RelationshipTypeId = dtoRelationshipType.Id;
            RelationshipTypeName = dtoRelationshipType.Name;
            ParentRelationshipTypeName = dtoParentRelationshipType.Name;
            ChildRelationshipTypeName = dtoChildRelationshipType.Name;
        }


        public int Id { get; set; }
        public int RelationshipTypeId { get; set; }
        public string RelationshipTypeName { get; set; }
        [Display(Name = "Parent")]
        public string ParentRelationshipTypeName { get; set; }
        [Display(Name = "Child")]
        public string ChildRelationshipTypeName { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemorySettingTypeRepository : InMemoryRepository<SettingType>, ISettingTypeRepository
    {
        private List<SettingType> _entities = null;

        public InMemorySettingTypeRepository(IEnumerable<SettingType> entities)
            : base(entities)
        {
            _entities = entities as List<SettingType>;
        }



        public IEnumerable<SettingType> GetAllOrderedByName()
        {
            return _entities
                .OrderBy(r => r.Name)
                .ToList();
        }

        public int CountMatching(string name)
        {
            return _entities
                .Count(r => r.Name == name);
        }

        public int CountMatching(int excludeId, string name)
        {
            return _entities
                .Where(r => r.Id != excludeId)
                .Count(r => r.Name == name);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountTypeRelationshipTypes")]
    public class AssetTypeRelationshipType : BaseEntity
    {
        [Required]
        [Display(Name = "ParentAssetType ID")]
        [Column("ParentAccountTypeId")]
        public int ParentAssetTypeId { get; set; }
        [Display(Name = "ChildAssetType ID")]
        [Column("ChildAccountTypeId")]
        public int ChildAssetTypeId { get; set; }
        [Required]
        [Display(Name = "ParentChildRelationshipType ID")]
        public int ParentChildRelationshipTypeId { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Models
{
    public class AccountTypeSettingType
    {
        public AccountTypeSettingType() { }
        /*
        public AssetTypeSettingType(AssetType assetType, Core.Models.SettingType settingType)
        {
            AssetTypeId = assetType.Id;
            AssetTypeName = assetType.Name;
            SettingTypeId = settingType.Id;
            SettingTypeName = settingType.Name;
        }
        */
        /*
        public AssetTypeSettingType(Core.Models.AssetTypeSettingType assetTypeSettingType, 
            AssetType assetType, 
            Core.Models.SettingType settingType)
        {
            AssetTypeSettingTypeId = assetTypeSettingType.Id;
            AssetTypeId = assetType.Id;
            AssetTypeName = assetType.Name;
            SettingTypeId = settingType.Id;
            SettingTypeName = settingType.Name;
            //IsActive = assetTypeSettingType.IsActive;
        }
        */
        public int AssetTypeSettingTypeId { get; set; }
        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core;
using Financial.Core.Models;

namespace Financial.Tests.Mocks
{
    
    public static class MockFinancialDbContext
    {
        public static FinancialDbContext Create(
            List<Asset> assets = null,
            List<AssetSetting> assetSettings = null,
            List<AssetTransaction> assetTransactions = null,
            List<AssetType> assetTypes = null,
            List<SettingType> settingTypes = null,
            List<TransactionCategory> transactionCategories = null,
            List<TransactionDescription> transactionDescriptions = null,
            List<TransactionType> transactionTypes = null)
        {
            // setup dbContext
            return new FinancialDbContext
            {
                Assets = MockDbSet.Create<Asset>(assets),
                AssetSettings = MockDbSet.Create<AssetSetting>(assetSettings),
                AssetTransactions = MockDbSet.Create<AssetTransaction>(assetTransactions),
                AssetTypes = MockDbSet.Create<AssetType>(assetTypes),
                SettingTypes = MockDbSet.Create<SettingType>(settingTypes),
                TransactionCategories = MockDbSet.Create<TransactionCategory>(transactionCategories),
                TransactionDescriptions = MockDbSet.Create<TransactionDescription>(transactionDescriptions),
                TransactionTypes = MockDbSet.Create<TransactionType>(transactionTypes),
            };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace Financial.Tests.Business.Services
{
    [TestFixture]
    public class AccountSettingServiceTests
    {
        [SetUp]
        public void SetUp()
        {

        }

        [TearDown]
        public void TearDown()
        {

        }

        [Test]
        public void GetAccountIdentificationInformation_Test()
        {

        }
    }
}
<file_sep>﻿using Financial.Business;
using Financial.Data;
using Financial.WebApplication.Models.ViewModels.TransactionCategory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Financial.WebApplication.Controllers
{
    public class TransactionCategoryController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;


        public TransactionCategoryController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }


        [HttpGet]
        public ActionResult Index()
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }
            if (TempData["ErrorMessage"] != null)
            {
                ViewData["ErrorMessage"] = TempData["ErrorMessage"];
            }

            // transfer dto to vm
            var vmIndex = _unitOfWork.TransactionCategories.GetAll()
                .Where(r => r.IsActive)
                .Select(r => new IndexViewModel(r))
                .OrderBy(r => r.Name)
                .ToList();

            // display view
            return View("Index", vmIndex);
        }

        [HttpGet]
        public ActionResult Create()
        {
            // display view
            return View("Create");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            if(!ModelState.IsValid)
            {
                return View("Create", vmCreate);
            }

            // transfer vm to dto
            _unitOfWork.TransactionCategories.Add(new Core.Models.TransactionCategory()
            {
                Name = vmCreate.Name,
                IsActive = true
            });

            // update db
            _unitOfWork.CommitTrans();

            // display view with message
            TempData["SuccessMessage"] = "New Category Added";
            return RedirectToAction("Index", "TransactionCategory");
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            // transfer id to dto 
            var dtoTransactionCategory = _unitOfWork.TransactionCategories.Get(id);

            // validate dto
            if(dtoTransactionCategory == null)
            {
                TempData["ErrorMessage"] = "Encountered problem updated transaction category. Try again.";
                return RedirectToAction("Index", "TransactionCategory");
            }

            // display view
            return View("Edit", new EditViewModel(dtoTransactionCategory));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            // transfer vm to dto
            var dtoTransactionCategory = _unitOfWork.TransactionCategories.Get(vmEdit.Id);
            dtoTransactionCategory.Name = vmEdit.Name;

            // update db
            _unitOfWork.CommitTrans();

            // display view with message
            TempData["SuccessMessage"] = "Record updated.";
            return RedirectToAction("Index", "TransactionCategory");
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class CreateViewModel
    {
        public CreateViewModel() { }

        public CreateViewModel(List<SelectListItem> sliAccount, List<SelectListItem> sliTransactionType, List<SelectListItem> sliTransactionCategory)
        {
            Accounts = sliAccount;
            TransactionTypes = sliTransactionType;
            TransactionCategories = sliTransactionCategory;
        }
        /*
        public CreateViewModel(Core.Models.Asset dtoAsset,string assetNameAdditionalInformaiton,
            Core.Models.AssetType dtoAssetType, DateTime date,
            List<SelectListItem> sliTransactionTypes, List<SelectListItem> sliTransactionCategories)
        {
            AssetId = dtoAsset.Id;
            AssetName = dtoAsset.Name + assetNameAdditionalInformaiton;
            AssetTypeName = dtoAssetType.Name;
            DueDate = date.ToString("MM/dd/yyyy");
            TransactionTypes = sliTransactionTypes;
            TransactionCategories = sliTransactionCategories;
        }*/
        public CreateViewModel(Business.Models.AccountTransaction bmAssetTransaction)
        {
            AssetId = bmAssetTransaction.AssetId;
            AccountName = bmAssetTransaction.AssetName;
            //Assets = bmAssetTransaction.AssetSelectList;
            AssetTypeName = bmAssetTransaction.AssetTypeName;
            //TransactionTypes = bmAssetTransaction.TransactionTypeSelectList;
            SelectedTransactionTypeId = bmAssetTransaction.TransactionTypeId.ToString();
            //TransactionCategories = bmAssetTransaction.TransactionCategorySelectList;
            SelectedTransactionCategoryId = bmAssetTransaction.TransactionCategoryId.ToString();
        }

        public int AssetId { get; set; }
        [Display(Name = "Account Name")]
        public string AccountName { get; set; }
        [Display(Name = "Account Type")]
        public string AssetTypeName { get; set; }
        [Display(Name = "Check Number")]
        public string CheckNumber { get; set; }
        [Required]
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime ClearDate { get; set; }
        [Required]
        public decimal Amount { get; set; }
        public string Note { get; set; }
        [Required]
        [Display(Name = "Asset")]
        public string SelectedAccountId { get; set; }
        public IEnumerable<SelectListItem> Accounts { get; set; }
        [Required]
        [Display(Name = "Type")]
        public string SelectedTransactionTypeId { get; set; }
        public IEnumerable<SelectListItem> TransactionTypes { get; set; }
        [Required]
        [Display(Name = "Category")]
        public string SelectedTransactionCategoryId { get; set; }
        public IEnumerable<SelectListItem> TransactionCategories { get; set; }
        //[Required]
        //[Display(Name = "Description")]
        //public string SelectedTransactionDescriptionId { get; set; }
        //public IEnumerable<SelectListItem> TransactionDescriptions { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetTypeRepository : IRepository<AssetType>
    {
        AssetType GetActive(int id);
        IEnumerable<AssetType> GetAllOrderedByName();
        IEnumerable<AssetType> GetAllActiveOrderedByName();
        int CountMatching(string name);
        int CountMatching(int excludeId, string name);
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class EditViewModel
    {
        public EditViewModel()
        {
        }

        public EditViewModel(Core.Models.SettingType dtoSettingType,
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            Id = dtoAssetTypeSettingType.Id;
            AssetTypeId = dtoAssetTypeSettingType.AssetTypeId;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            IsActive = dtoAssetTypeSettingType.IsActive;
        }

        public EditViewModel(Core.Models.AssetType dtoAssetType,
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            Id = dtoAssetTypeSettingType.Id;
            SettingTypeId = dtoAssetTypeSettingType.SettingTypeId;
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
            IsActive = dtoAssetTypeSettingType.IsActive;
        }

        public int Id { get; set; }

        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }

        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }

        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryTransactionCategoryRepository : InMemoryRepository<TransactionCategory>, ITransactionCategoryRepository
    {
        private List<TransactionCategory> _entities = null;

        public InMemoryTransactionCategoryRepository(IEnumerable<TransactionCategory> entities)
            : base(entities)
        {
            _entities = entities as List<TransactionCategory>;
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("TransactionCategories")]
    public class TransactionCategory : BaseEntity
    {
        [Required]
        public string Name { get; set; }



        public ICollection<AssetTransaction> AssetTransactions { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Core.Models.AssetTypeRelationshipType dtoAssetTypeRelationshipType,
            Core.Models.AssetType dtoAssetType, List<SelectListItem> sliRelationshipLevels, 
            string selectedRelationshipLevel, string selectedParentChildRelationshipTypeId,
            List<SelectListItem> sliLinkAssetTypes, string selectedLinkedAssetType)
        {
            Id = dtoAssetTypeRelationshipType.Id;
            SuppliedAssetTypeId = dtoAssetType.Id;
            SuppliedAssetTypeName = dtoAssetType.Name;
            RelationshipLevels = sliRelationshipLevels;
            SelectedRelationshipLevel = selectedRelationshipLevel;
            SelectedParentChildRelationshipTypeId = selectedParentChildRelationshipTypeId;
            LinkAssetTypes = sliLinkAssetTypes;
            SelectedLinkedAssetTypeId = selectedLinkedAssetType;
        }

        public int Id { get; set; }

        public int SuppliedAssetTypeId { get; set; }
        [Display(Name = "Asset Type")]
        public string SuppliedAssetTypeName { get; set; }

        [Required]
        [Display(Name = "Relationship Level")]
        public string SelectedRelationshipLevel { get; set; }
        public IEnumerable<SelectListItem> RelationshipLevels { get; set; }


        [Required]
        [Display(Name = "Relationship Type")]
        public string SelectedParentChildRelationshipTypeId { get; set; }
        public IEnumerable<SelectListItem> ParentChildRelationshipTypes { get; set; }

        [Required]
        [Display(Name = "Link Asset Type")]
        public string SelectedLinkedAssetTypeId { get; set; }
        public IEnumerable<SelectListItem> LinkAssetTypes { get; set; }


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using NUnit.Framework;

namespace Financial.Tests._DmitriNesteruk
{
    public class Bar : IEquatable<Bar>
    {
        public bool Equals(Bar other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return string.Equals(Name, other.Name);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Bar) obj);
        }

        public override int GetHashCode()
        {
            return (Name != null ? Name.GetHashCode() : 0);
        }

        public static bool operator ==(Bar left, Bar right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(Bar left, Bar right)
        {
            return !Equals(left, right);
        }

        public string Name { get; set; }
    }

    public interface IBaz
    {
        string Name { get; }
    }

    public interface IFooWithMoq
    {
        bool DoSomething(string value);
        string ProcessString(string value);
        bool TryParse(string value, out string outputValue);
        bool Submit(ref Bar bar);
        int GetCount();
        bool Add(int amount);

        string Name { get; set; }
        IBaz SomeBaz { get; }
        int SomeOtherProperty { get; set; }
    }
    public class FooWithMoq
    {
    }

    public delegate void AlienAbductionEventHandler(int galaxy, bool returned);
    public interface IAnimal
    {
        event EventHandler FallsIll;
        void Stumble();
        event AlienAbductionEventHandler AbductedByAliens;
    }
    public class Doctor
    {
        public int TimesCured;
        public int AbductionsObserved;

        public Doctor(IAnimal animal)
        {
            animal.FallsIll += (sender, args) =>
            {
                Console.WriteLine("I will cure you!");
                TimesCured++;
            };

            animal.AbductedByAliens += (galaxy, returned) => ++AbductionsObserved;
        }
    }

    public class Consumer
    {
        private IFooWithMoq foo;

        public Consumer(IFooWithMoq foo)
        {
            this.foo = foo;
        }

        public void Hello()
        {
            foo.DoSomething("ping");
            var name = foo.Name;
            foo.SomeOtherProperty = 123;
        }
    }

    public abstract class Person
    {
        protected int SSN { get; set; }
        protected abstract void Execute(string cmd);
    }

    

    [TestFixture]
    public class FooWithMoqTests
    {



        // METHODS




        [Test]
        public void SetUpMockMethod_WhenCheckingForStringValue_ReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.DoSomething("ping"))
                .Returns(true);

            Assert.IsTrue(mock.Object.DoSomething("ping"));
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForStringValue_ReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.DoSomething("pong"))
                .Returns(false);

            Assert.IsFalse(mock.Object.DoSomething("pong"));
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForMultipleStringValues_ReturnFalseForEachValue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.DoSomething(It.IsIn("foo", "bar")))
                .Returns(false);

            Assert.Multiple(() =>
            {
                Assert.IsFalse(mock.Object.DoSomething("foo"));
                Assert.IsFalse(mock.Object.DoSomething("bar"));
            });
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForAnyStringInput_ReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
                .Returns(true);

            Assert.IsTrue(mock.Object.DoSomething("abc")); 
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForAnyNumericInput_ReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.DoSomething(It.IsRegex("[0-9]+")))
                .Returns(false);

            Assert.IsFalse(mock.Object.DoSomething("123")); 
        }

        [Test]
        public void SetUpMockMethod_WhenNumberIsEven_ReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.Add(It.Is<int>(x => x % 2 == 0)))
                .Returns(true);

            Assert.IsTrue(mock.Object.Add(2));
        }

        [Test]
        public void SetUpMockMethod_WhenNumberIsOdd_ReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.Add(It.Is<int>(x => x % 2 == 0)))
                .Returns(true);

            Assert.IsFalse(mock.Object.Add(3)); 
        }

        [Test]
        public void SetUpMockMethod_WhenNumberIsWithinRange_ReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.Add(It.IsInRange<int>(1, 10, Range.Inclusive)))
                .Returns(true);

            Assert.IsTrue(mock.Object.Add(3));
        }

        [Test]
        public void SetUpMockMethod_WhenNumberIsOutsideOfRange_ReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(foo => foo.Add(It.IsInRange<int>(1, 10, Range.Inclusive)))
                .Returns(true);

            Assert.IsFalse(mock.Object.Add(11));
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForStringValue_SetOutArgumentAndReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var requiredOutput = "ok";
            mock.Setup(foo => foo.TryParse("ping", out requiredOutput))
                .Returns(true);

            string result;
            Assert.Multiple(() =>
            {
                Assert.IsTrue(mock.Object.TryParse("ping", out result));
                Assert.That(result, Is.EqualTo(requiredOutput));
            });
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingForInvalidStringValue_SetOutArgumentToNullAndReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var requiredOutput = "ok";
            mock.Setup(foo => foo.TryParse("ping", out requiredOutput))
                .Returns(true);

            string result;
            Assert.Multiple(() =>
            {
                Assert.IsFalse(mock.Object.TryParse("pong", out result));
                Assert.That(result, Is.EqualTo(null));
            });
        }

        [Test]
        public void SetUpMockMethod_WhenCheckingMultipleStringValuesWithSameOutArgument_ProblemSettingOutArgument_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var requiredOutput = "ok";
            mock.Setup(foo => foo.TryParse("ping", out requiredOutput))
                .Returns(true);

            string result;
            Assert.Multiple(() =>
            {
                Assert.IsTrue(mock.Object.TryParse("ping", out result));
                Assert.That(result, Is.EqualTo(requiredOutput));

                Assert.IsFalse(mock.Object.TryParse("pong", out result));
                //Assert.That(result, Is.Not.EqualTo(requiredOutput));
                Assert.Warn($"Using the same result field for both [ping] & [pong] can have unexpected results. " +
                            $"[pong] result should be [string.empty] but instead equals [{result}]");
            });
        }

        [Test]
        public void SetupMockMethod_WhenReferenceArgumentIsValid_ReturnTrue_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var bar = new Bar() {Name="abc"};
            mock.Setup(foo => foo.Submit(ref bar))
                .Returns(true);

            Assert.That(mock.Object.Submit(ref bar), Is.EqualTo(true));
        }

        [Test]
        public void SetupMockMethod_WhenReferenceArgumentIsNotValid_ReturnFalse_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var bar = new Bar() { Name = "abc" };
            mock.Setup(foo => foo.Submit(ref bar))
                .Returns(true);
            var anotherBar = new Bar() { Name = "def" };

            Assert.IsFalse(mock.Object.Submit(ref anotherBar));
        }

        [Test]
        public void SetupMockMethod_WhenCheckingTwoDifferentReferenceArgumentWithSameName_ProblemReturningUnexpectedBoolean_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var bar = new Bar() { Name = "abc" };
            mock.Setup(foo => foo.Submit(ref bar))
                .Returns(true);

            var anotherBar = new Bar() { Name = "abc" };
            Assert.Warn("compares reference location, " +
                        "names are the same but for two different reference objects");
            Assert.IsFalse(mock.Object.Submit(ref anotherBar));
        }

        [Test]
        public void SetUpMockMethod_WhenAnyStringValueProvided_ReturnLowerCaseString()
        {
            var mock = new Mock<IFooWithMoq>();

            // setup method that takes input string, formats and returns new string 
            mock.Setup(foo => foo.ProcessString(It.IsAny<string>()))
                .Returns((string s) => s.ToLowerInvariant());

            Assert.That(mock.Object.ProcessString("ABC"),
                Is.EqualTo("abc"));
        }

        [Test]
        public void SetupMockMethod_WhenNoInputsProvidedAndMethodIsCalled_IncrementAndReturnCount_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            // setup method to increment calls when no inputs provided
            var calls = 0;
            mock.Setup(foo => foo.GetCount())
                .Returns(() => calls)
                .Callback(() => ++calls);

            // increment calls
            mock.Object.GetCount();
            mock.Object.GetCount();
            
            Assert.That(mock.Object.GetCount(), Is.EqualTo(2));
        }

        [Test]
        public void SetupMockMethod_WhenStringValueProvided_ReturnException_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            // setup method to throw an exception for input value
            var calls = 0;
            mock.Setup(foo => foo.DoSomething("kill"))
                .Throws<InvalidOperationException>();

            Assert.Throws<InvalidOperationException>(
                    ()=> mock.Object.DoSomething("kill")
                );
        }

        [Test]
        public void SetupMockMethod_WhenStringValueProvidedEqualsNull_ReturnException_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            // setup method to throw an exception for input value
            var calls = 0;
            mock.Setup(foo => foo.DoSomething(null))
                .Throws(new ArgumentException("cmd"));

            Assert.Throws<ArgumentException>(
                () =>
                {
                    mock.Object.DoSomething(null);

                }, "cmd");
        }



        // PROPERTIES



        [Test]
        public void SetupMockProperty_SetNameValue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(Foo => Foo.Name)
                .Returns("bar");

            Assert.That(mock.Object.Name, Is.EqualTo("bar"));
        }

        [Test]
        public void SetupMockProperty_WrongWayToSetNameValue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Object.Name = "invalid bar";

            Assert.Warn("Name is not set this way, setter not setup yet");
            Assert.That(mock.Object.Name, Is.Not.EqualTo("invalid bar"));
        }

        [Test]
        public void SetupMockProperty_SetPropertyOfAPropertyNameValue_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            mock.Setup(Foo => Foo.SomeBaz.Name)
                .Returns("hello");

            Assert.That(mock.Object.SomeBaz.Name, Is.EqualTo("hello"));
        }
        
        /*
        [Test]
        public void SetupMockProperty_SetPropertySetter_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            var setterCalled = false;
            mock.SetupSet(foo =>
                {
                    foo.Name = It.IsAny<string>();
                })
                .Callback<string>(value =>
                {
                    setterCalled = true;
                });

            IFooWithMoq fooWithMoq = mock.Object;
            fooWithMoq.Name = "def";

            mock.VerifySet(foo =>
            {
                foo.Name = "def";
            }, Times.AtLeastOnce);

            Assert.Multiple(() =>
            {
                Assert.That(mock.Object.Name, Is.EqualTo("def"));
                Assert.IsTrue(setterCalled);
            });
        }
        */

        [Test]
        public void SetupMockProperty_SetUpAllProperties_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            mock.SetupAllProperties();
            IFooWithMoq foo = mock.Object;
            foo.Name = "def";
            foo.SomeOtherProperty = 123;

            Assert.That(mock.Object.Name, Is.EqualTo("def"));
            Assert.That(mock.Object.SomeOtherProperty, Is.EqualTo(123));
        }

        [Test]
        public void SetupMockProperty_SetUpSingleProperty_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            mock.SetupProperty(f => f.Name);
            IFooWithMoq foo = mock.Object;
            foo.Name = "def";
            foo.SomeOtherProperty = 123;

            Assert.That(mock.Object.Name, Is.EqualTo("def"));
            Assert.That(mock.Object.SomeOtherProperty, Is.Not.EqualTo(123));
        }



        // EVENTS



        [Test]
        public void SetupMockEvents_WhenEventRaised_Test()
        {
            var mock = new Mock<IAnimal>();
            var doctor = new Doctor(mock.Object);

            mock.Raise(
                a => a.FallsIll += null, // event action/subscription
                new EventArgs()
            );

            Assert.That(doctor.TimesCured, Is.EqualTo(1));
        }

        [Test]
        public void SetupMockEvents_WhenCalledMethodRaisesEvent_Test()
        {
            var mock = new Mock<IAnimal>();
            var doctor = new Doctor(mock.Object);

            mock.Setup(a => a.Stumble())
                .Raises(a => a.FallsIll += null,
                new EventArgs()
            );

            mock.Object.Stumble();

            Assert.That(doctor.TimesCured, Is.EqualTo(1));
        }

        [Test]
        public void SetupMockEvents_WhenCustomEventRaised_Test()
        {
            var mock = new Mock<IAnimal>();
            var doctor = new Doctor(mock.Object);

            mock.Raise(a => a.AbductedByAliens += null,
                    42, true
                );

            Assert.That(doctor.AbductionsObserved, Is.EqualTo(1));
        }



        // CALLBACKS


        [Test]
        public void CallBack_WhenMethodCalledIncrementCount_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            int x = 0;
            mock.Setup(foo => foo.DoSomething("ping"))
                .Returns(true)
                .Callback(() => x++);
            mock.Object.DoSomething("ping");
            Assert.That(x, Is.EqualTo(1));
        }

        [Test]
        public void CallBack_WhenMethodCalledManipulateArgument_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            int x = 0;
            mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
                .Returns(true)
                .Callback((string s) => x+= s.Length);
            mock.Object.DoSomething("ping");
            Assert.That(x, Is.EqualTo(4));
        }

        [Test]
        public void CallBack_WhenMethodCalledManipulateArgumentWithGenericOverLoad_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            int x = 0;
            mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
                .Returns(true)
                .Callback<string>(s => x += s.Length);
            mock.Object.DoSomething("ping");
            Assert.That(x, Is.EqualTo(4));
        }

        [Test]
        public void CallBack_BeforeInvocationOfMethod_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            int x = 0;
            mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
                .Callback(() => Console.WriteLine("before ping"))
                .Returns(true);
        }

        [Test]
        public void CallBack_AfterInvocationOfMethod_Test()
        {
            var mock = new Mock<IFooWithMoq>();

            int x = 0;
            mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
                .Returns(true)
                .Callback(() => Console.WriteLine("after ping"));
        }


        // VERIFICATION


        [Test]
        public void Verification_VerifyMethodInvoked_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var consumer = new Consumer(mock.Object);

            consumer.Hello();

            mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce);
        }

        [Test]
        public void Verification_VerifyMethodNotInvoked_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var consumer = new Consumer(mock.Object);

            consumer.Hello();

            mock.Verify(foo => foo.DoSomething("pong"), Times.Never);
        }

        [Test]
        public void Verification_VerifyGetterUsedToAccessVariable_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var consumer = new Consumer(mock.Object);

            consumer.Hello();

            mock.VerifyGet(foo => foo.Name);
        }

        [Test]
        public void Verification_VerifySetterCalledWithSpecificValue_Test()
        {
            var mock = new Mock<IFooWithMoq>();
            var consumer = new Consumer(mock.Object);

            consumer.Hello();

            mock.VerifySet(foo => foo.SomeOtherProperty = It.IsInRange(100, 200, Range.Inclusive));
        }



        // BEHAVIOR


        [Test]
        public void Behavior_SetupAllInvocationsOnTheMock_Test()
        {
            var mock = new Mock<IFooWithMoq>(MockBehavior.Strict);

            mock.Setup(f => f.DoSomething("abc"))
                .Returns(true);

            mock.Object.DoSomething("abc");
        }

        [Test]
        public void Behavior_AutomaticRecursiveMocking_Test()
        {
            var mock = new Mock<IFooWithMoq>()
            {
                DefaultValue = DefaultValue.Mock
            };

            var baz = mock.Object.SomeBaz;
            var bazMock = Mock.Get(baz);
            bazMock.SetupGet(f => f.Name)
                .Returns("abc");
        }

        [Test]
        public void Behavior_MockRepository_Test()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict)
            {
                DefaultValue = DefaultValue.Mock
            };

            var fooMock = mockRepository.Create<IFooWithMoq>();
            var otherMock = mockRepository.Create<IBaz>(MockBehavior.Loose);

            mockRepository.Verify();
        }



        // PROTECTED MEMBERS



        [Test]
        public void ProtectedMembers_SetupProtectedPropertyToReturnSpecifiedValue_Test()
        {
            var mock = new Mock<Person>();
            /*
            mock.Protected()
                .SetupGet<int>("SSN") // can not use nameof(Person.SSN)
                .Returns(42);
            */
        }

        [Test]
        public void ProtectedMembers_SetupProtectedPropertyWithGenericArgument_Test()
        {
            var mock = new Mock<Person>();
            /*
            mock.Protected()
                .Setup<string>("Execute", ItExpr.IsAny<string>()); // can not use It.IsAny
            */
        }
    }
}
<file_sep>﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using Financial.Business.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Utilities
{
    public static class AccountUtilityObjectMother
    {
        public static int AssetTypeIdForCreditCard = 3;
    }


    [TestClass()]
    public class AccountUtilityTests
    {
        [TestMethod()]
        public void FormatAccountName_WhenProvidedValidInput_ReturnValue_Test()
        {
            // Arrange
            var assetName = "name";
            int assetTypeId = 1;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
        }

        [TestMethod()]
        public void FormatAccountName_WhenProvidedValidInputForCreditCard_ReturnValue_Test()
        {
            // Arrange
            var assetName = "name";
            int assetTypeId = AccountUtilityObjectMother.AssetTypeIdForCreditCard;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
            Assert.AreEqual("name (value)", result, "Result");
        }

        [TestMethod()]
        public void FormatAccountName_WhenProvidedValidInputNotCreditCard_ReturnValue_Test()
        {
            // Arrange
            var assetName = "name";
            int assetTypeId = 1;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
            Assert.AreEqual("name", result, "Result");
        }

        [TestMethod()]
        public void FormatAccountName_WhenProvidedInvalidInputAssetName_ReturnValue_Test()
        {
            // Arrange
            var assetName = string.Empty;
            int assetTypeId = 1;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
            Assert.AreEqual(string.Empty, result, "Result");
        }

        [TestMethod()]
        public void FormatAccountName_WhenProvidedInvalidInputAssetTypeId_ReturnValue_Test()
        {
            // Arrange
            var assetName = "name";
            int assetTypeId = 0;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
            Assert.AreEqual(string.Empty, result, "Result");
        }

        [TestMethod()]
        public void FormatAccountName_WhenProvidedInvalidInputAssetSettingValue_ReturnValue_Test()
        {
            // Arrange
            var assetName = "name";
            int assetTypeId = 1;
            var assetSettingValue = "value";

            // Act
            var result = AccountUtility.FormatAccountName(assetName, assetTypeId, assetSettingValue);

            // Assert
            Assert.IsInstanceOfType(result, typeof(string), "Result Type");
            Assert.AreEqual("name", result, "Result");
        }

    }
}<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetTypeRelationshipTypeRepository : IRepository<AssetTypeRelationshipType>
    {
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;

namespace Financial.WebApplication.Controllers
{
    public class AssetTypeRelationshipTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;

        public AssetTypeRelationshipTypeController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [ChildActionOnly]
        public ActionResult Index(int assetTypeId)
        {
            // transfer supplied Id to dto
            var dtoSuppliedAssetType = _unitOfWork.AssetTypes.Get(assetTypeId);

            // transfer dto to vm for supplied asset type id == child
            var vmIndex = _unitOfWork.AssetTypes.FindAll(r => r.IsActive)
                .Join(_unitOfWork.AssetTypeRelationshipTypes.FindAll(r => r.IsActive),
                    at => at.Id, atrt => atrt.ParentAssetTypeId,
                    (at, atrt) => new { at, atrt })
                .Where(j => j.atrt.ChildAssetTypeId == dtoSuppliedAssetType.Id)
                .ToList()
                .Join(_unitOfWork.ParentChildRelationshipTypes.FindAll(r => r.IsActive),
                    j => j.atrt.ParentChildRelationshipTypeId, pcrt => pcrt.Id,
                    (j, pcrt) => new { j, pcrt })
                .ToList()
                .Join(_unitOfWork.RelationshipTypes.FindAll(r => r.IsActive),
                    j2 => j2.pcrt.ChildRelationshipTypeId, rt => rt.Id,
                    (j2, rt) => new IndexViewModel(j2.j.atrt, dtoSuppliedAssetType, j2.j.at, rt))
                .OrderBy(r => r.LinkedAssetTypeName)
                .ToList();

            // transfer dto to vm for supplied asset type id == parent
            var vmIndexParent = _unitOfWork.AssetTypes.FindAll(r => r.IsActive)
                .Join(_unitOfWork.AssetTypeRelationshipTypes.FindAll(r => r.IsActive),
                    at => at.Id, atrt => atrt.ChildAssetTypeId,
                    (at, atrt) => new { at, atrt })
                .Where(j => j.atrt.ParentAssetTypeId == dtoSuppliedAssetType.Id)
                .ToList()
                .Join(_unitOfWork.ParentChildRelationshipTypes.FindAll(r => r.IsActive),
                    j => j.atrt.ParentChildRelationshipTypeId, pcrt => pcrt.Id,
                    (j, pcrt) => new { j, pcrt })
                .ToList()
                .Join(_unitOfWork.RelationshipTypes.FindAll(r => r.IsActive),
                    j2 => j2.pcrt.ParentRelationshipTypeId, rt => rt.Id,
                    (j2, rt) => new IndexViewModel(j2.j.atrt, dtoSuppliedAssetType, j2.j.at, rt))
                .OrderBy(r => r.LinkedAssetTypeName)
                .ToList();
            foreach(var vmParent in vmIndexParent)
            {
                vmIndex.Add(vmParent);
            }

            return PartialView("_Index", vmIndex);
        }

        [HttpGet]
        public ViewResult Create(int assetTypeId)
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }

            // transfer id to dto
            var dtoSuppliedAssetType = _unitOfWork.AssetTypes.Get(assetTypeId);

            // get drop down lists
            List<SelectListItem> sliRelationshipLevels = GetRelationshipLevels(null);
            List<SelectListItem> sliLinkAssetTypes = GetAssetTypes(assetTypeId, null, null, null);

            // display view
            return View("Create", new CreateViewModel(dtoSuppliedAssetType, sliRelationshipLevels, sliLinkAssetTypes, null, null));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            // validation
            if (!ModelState.IsValid)
            {
                return View("Create", vmCreate);
            }

            // count existing link
            int id = 0;
            int count = CountExistingLinks(id, vmCreate.SuppliedAssetTypeId, vmCreate.SelectedLinkedAssetTypeId, vmCreate.SelectedParentChildRelationshipTypeId);

            // links found
            if (count > 0)
            {
                // YES. get drop down lists
                vmCreate.RelationshipLevels = GetRelationshipLevels(null);

                // redisplay view with message
                ViewData["ErrorMessage"] = "Link already exists";
                return View("Create", vmCreate);
            }

            // transfer vm to dto
            if (vmCreate.SelectedRelationshipLevel == "Parent")
            {
                _unitOfWork.AssetTypeRelationshipTypes.Add(new AssetTypeRelationshipType
                {
                    ParentAssetTypeId = vmCreate.SuppliedAssetTypeId,
                    ChildAssetTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedAssetTypeId.ToString()),
                    ParentChildRelationshipTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedParentChildRelationshipTypeId),
                    IsActive = true
                });
            }
            else // supplied AssetType == Child
            {
                _unitOfWork.AssetTypeRelationshipTypes.Add(new AssetTypeRelationshipType
                {
                    ParentAssetTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedAssetTypeId),
                    ChildAssetTypeId = vmCreate.SuppliedAssetTypeId,
                    ParentChildRelationshipTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedParentChildRelationshipTypeId),
                    IsActive = true
                });
            }

            // update db
            _unitOfWork.CommitTrans();

            // return view with message
            TempData["SuccessMessage"] = "Parent-Child link created.";
            return RedirectToAction("Details", "AssetType", new { id = vmCreate.SuppliedAssetTypeId });
        }

        private int CountExistingLinks(int id, int suppliedAssetTypeId, string selectedAssetTypeId, string selectedParentChildRelationshipType)
        {
            var countParent = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                .Where(r => r.Id != id)
                .Where(r => r.ParentAssetTypeId == suppliedAssetTypeId)
                .Where(r => r.ChildAssetTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(selectedAssetTypeId))
                .Where(r => r.ParentChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(selectedParentChildRelationshipType))
                .Count(r => r.IsActive);
            var countChild = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                .Where(r => r.Id != id)
                .Where(r => r.ParentAssetTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(selectedAssetTypeId))
                .Where(r => r.ChildAssetTypeId == suppliedAssetTypeId)
                .Where(r => r.ParentChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(selectedParentChildRelationshipType))
                .Count(r => r.IsActive);

            return countParent + countChild;
        }

        [HttpGet]
        public ActionResult DisplayParentChildRelationshipTypes(int suppliedAssetTypeId, string selectedRelationshipLevelId, int? selectedParentChildRelationshipTypeId)
        {
            // get filtered list to display
            List<SelectListItem> sliParentChildRelationshipTypes = GetParentChildRelationshipTypes(suppliedAssetTypeId, selectedRelationshipLevelId, selectedParentChildRelationshipTypeId);
            
            // display view
            return PartialView("_DisplayParentChildRelationshipTypes", new DisplayParentChildRelationshipTypesViewModel(sliParentChildRelationshipTypes, selectedParentChildRelationshipTypeId.ToString()));
        }
        
        [HttpGet]
        public ViewResult Edit(int id, int suppliedAssetTypeId)
        {
            // get dto for supplied id
            var dtoSuppliedAssetType = _unitOfWork.AssetTypes.Get(suppliedAssetTypeId);
            var dtoAssetTypeRelationshipType = _unitOfWork.AssetTypeRelationshipTypes.Get(id);

            // Selected values
            var selectedRelationshipLevelId = dtoAssetTypeRelationshipType.ParentAssetTypeId == dtoSuppliedAssetType.Id ?
                "Parent" : "Child";
            var selectedParentChildRelationshipTypeId = dtoAssetTypeRelationshipType.ParentChildRelationshipTypeId;
            var selectedLinkedAssetTypeId = dtoAssetTypeRelationshipType.ParentAssetTypeId == dtoSuppliedAssetType.Id ?
                dtoAssetTypeRelationshipType.ChildAssetTypeId : dtoAssetTypeRelationshipType.ParentAssetTypeId;

            // get drop down lists
            List<SelectListItem> sliRelationshipLevels = GetRelationshipLevels(selectedRelationshipLevelId);
            List<SelectListItem> sliLinkAssetTypes = GetAssetTypes(suppliedAssetTypeId, selectedRelationshipLevelId, 
                dtoAssetTypeRelationshipType.ParentChildRelationshipTypeId.ToString(), selectedLinkedAssetTypeId);

            // display view
            return View("Edit", new EditViewModel(dtoAssetTypeRelationshipType, dtoSuppliedAssetType, sliRelationshipLevels, selectedRelationshipLevelId,
                selectedParentChildRelationshipTypeId.ToString(), sliLinkAssetTypes, selectedLinkedAssetTypeId.ToString()));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            // validation
            if (!ModelState.IsValid)
            {
                return View("Edit", vmEdit);
            }

            // count existing link
            int count = CountExistingLinks(vmEdit.Id, vmEdit.SuppliedAssetTypeId, vmEdit.SelectedLinkedAssetTypeId, vmEdit.SelectedParentChildRelationshipTypeId);

            // links found
            if (count > 0)
            {
                // YES. get drop down lists
                vmEdit.RelationshipLevels = GetRelationshipLevels(vmEdit.SelectedRelationshipLevel);

                // redisplay view with message
                ViewData["ErrorMessage"] = "Link already exists";
                return View("Edit", vmEdit);
            }

            // check for identical record
            var countParentRelationship = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                .Where(r => r.Id == vmEdit.Id)
                .Where(r => r.ParentAssetTypeId == vmEdit.SuppliedAssetTypeId)
                .Where(r => r.ChildAssetTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedLinkedAssetTypeId))
                .Where(r => r.ParentChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedParentChildRelationshipTypeId))
                .Count(r => r.IsActive);
            var countChildRelationship = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                .Where(r => r.Id == vmEdit.Id)
                .Where(r => r.ParentAssetTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedLinkedAssetTypeId))
                .Where(r => r.ChildAssetTypeId == vmEdit.SuppliedAssetTypeId)
                .Where(r => r.ParentChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedParentChildRelationshipTypeId))
                .Count(r => r.IsActive);

            // record changed?
            if (countParentRelationship + countChildRelationship == 0)
            {
                // transfer vm to dto
                var dtoAssetTypeRelationshipType = _unitOfWork.AssetTypeRelationshipTypes.Get(vmEdit.Id);


                // transfer vm to dto
                dtoAssetTypeRelationshipType.ParentChildRelationshipTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedParentChildRelationshipTypeId);
                if (vmEdit.SelectedRelationshipLevel == "Parent")
                {
                    dtoAssetTypeRelationshipType.ParentAssetTypeId = vmEdit.SuppliedAssetTypeId;
                    dtoAssetTypeRelationshipType.ChildAssetTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedLinkedAssetTypeId);
                }
                else
                {
                    dtoAssetTypeRelationshipType.ParentAssetTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedLinkedAssetTypeId);
                    dtoAssetTypeRelationshipType.ChildAssetTypeId = vmEdit.SuppliedAssetTypeId;
                }

                // update db
                _unitOfWork.CommitTrans();
            }

            // display view with message
            TempData["SuccessMessage"] = "Parent-Child link updated.";
            return RedirectToAction("Details", "AssetType", new { id = vmEdit.SuppliedAssetTypeId });
        }

        [HttpGet]
        public ViewResult Delete(int id, int suppliedAssetTypeId)
        {
            // transfer values to dto
            var dtoAssetTypeRelationshipType = _unitOfWork.AssetTypeRelationshipTypes.Get(id);
            var dtoSuppliedAssetType = _unitOfWork.AssetTypes.Get(suppliedAssetTypeId);
            var dtoParentChildRelationshipType = _unitOfWork.ParentChildRelationshipTypes.Get(dtoAssetTypeRelationshipType.ParentChildRelationshipTypeId);
            var dtoLinkedAssetType = new AssetType();
            var dtoRelationshipType = new RelationshipType();

            // transfer Parent or Child info to dto
            if(dtoAssetTypeRelationshipType.ParentAssetTypeId == dtoSuppliedAssetType.Id)
            {
                dtoLinkedAssetType = _unitOfWork.AssetTypes.Get(dtoAssetTypeRelationshipType.ChildAssetTypeId);
                dtoRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ParentRelationshipTypeId);
            }
            else if (dtoAssetTypeRelationshipType.ChildAssetTypeId == dtoSuppliedAssetType.Id)
            {
                dtoLinkedAssetType = _unitOfWork.AssetTypes.Get(dtoAssetTypeRelationshipType.ParentAssetTypeId);
                dtoRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ChildRelationshipTypeId);
            }

            // display view
            return View("Delete", new DeleteViewModel(dtoAssetTypeRelationshipType, dtoSuppliedAssetType, dtoLinkedAssetType, dtoRelationshipType));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(DeleteViewModel vmDelete)
        {
            // transfer vm to dto
            var dtoAssetTypeRelationshipType = _unitOfWork.AssetTypeRelationshipTypes.Get(vmDelete.Id);
            dtoAssetTypeRelationshipType.IsActive = false;

            // update db
            _unitOfWork.CommitTrans();

            // display view with message
            TempData["SuccessMessage"] = "Relationship deleted.";
            return RedirectToAction("Details", "AssetType", new { id = vmDelete.SuppliedAssetTypeId });
        }

        private List<SelectListItem> GetAssetTypes(int suppliedAssetTypeId, string selectedRelationshipLevelId, string selectedParentChildRelationshipTypeId, int? selectedAssetTypeId)
        {
            // create sli
            List<SelectListItem> sliAssetTypes = new List<SelectListItem>();

            // store all available asset types
            var dbAssetTypes = _unitOfWork.AssetTypes.FindAll(r => r.IsActive);

            // add to sli if link does NOT exist
            foreach(var dtoAssetType in dbAssetTypes)
            {
                // check for matching Parent-Child link
                var countParentLinks = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                    .Where(r => r.ParentAssetTypeId == suppliedAssetTypeId)
                    .Where(r => r.ChildAssetTypeId == dtoAssetType.Id)
                    .Where(r => r.ChildAssetTypeId != selectedAssetTypeId)
                    .Count(r => r.IsActive);

                // check for matching Child-Parent link
                var countChildLinks = _unitOfWork.AssetTypeRelationshipTypes.GetAll()
                    .Where(r => r.ParentAssetTypeId == dtoAssetType.Id)
                    .Where(r => r.ParentAssetTypeId != selectedAssetTypeId)
                    .Where(r => r.ChildAssetTypeId == suppliedAssetTypeId)
                    .Count(r => r.IsActive);

                // add if link not found
                if(countParentLinks + countChildLinks == 0)
                {
                    sliAssetTypes.Add(new SelectListItem()
                    {
                        Value = dtoAssetType.Id.ToString(),
                        Selected = dtoAssetType.Id == selectedAssetTypeId,
                        Text = dtoAssetType.Name
                    });
                }
            }

            return sliAssetTypes;
        }

        private List<SelectListItem> GetParentChildRelationshipTypes(int suppliedAssetTypeId, string selectedRelationshipLevelId, int? selectedParentChildRelationshipTypeId)
        {
            // get list based on relationship level
            if (selectedRelationshipLevelId == "Parent")
            {
                // display list of all child relationship types
                return _unitOfWork.RelationshipTypes.GetAll()
                    .Where(r => r.IsActive)
                    .Join(_unitOfWork.ParentChildRelationshipTypes.FindAll(r => r.IsActive),
                        rt => rt.Id, pcrt => pcrt.ParentRelationshipTypeId,
                        (rt, pcrt) => new SelectListItem()
                        {
                            Value = pcrt.Id.ToString(),
                            Selected = pcrt.Id == selectedParentChildRelationshipTypeId,
                            Text = rt.Name
                        })
                    .ToList();
            }
            else if (selectedRelationshipLevelId == "Child")
            {
                // display list of all parent relationship types
                return _unitOfWork.RelationshipTypes.GetAll()
                    .Where(r => r.IsActive)
                    .Join(_unitOfWork.ParentChildRelationshipTypes.FindAll(r => r.IsActive),
                        rt => rt.Id, pcrt => pcrt.ChildRelationshipTypeId,
                        (rt, pcrt) => new SelectListItem()
                        {
                            Value = pcrt.Id.ToString(),
                            Selected = pcrt.Id == selectedParentChildRelationshipTypeId,
                            Text = rt.Name
                        })
                    .ToList();
            }

            // default empty list
            return new List<SelectListItem>();
        }

        private static List<SelectListItem> GetRelationshipLevels(string selectedValue)
        {
            // create sli
            List<SelectListItem> sliRelationshipLevel = new List<SelectListItem>();

            // transfer values to sli
            sliRelationshipLevel.Add(new SelectListItem()
            {
                Value = "Parent",
                Selected = "Parent" == selectedValue,
                Text = "Parent"
            });
            sliRelationshipLevel.Add(new SelectListItem()
            {
                Value = "Child",
                Selected = "Child" == selectedValue,
                Text = "Child"
            });

            return sliRelationshipLevel;
        }

    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Financial.Business.Models;

namespace Financial.Business.ServiceInterfaces
{
    public interface IAccountService
    {
        List<Account> GetListOfAccounts();
        List<SelectListItem> GetSelectListOfAccounts(int? selectedId);

    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class RelationshipTypeRepository : Repository<RelationshipType>, IRelationshipTypeRepository
    {
        public RelationshipTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }
    }
}
<file_sep>﻿using Financial.Business.Tests.Fakes;
using Financial.Business.Tests.Fakes.Database;
using Financial.Business.Tests.Fakes.Repositories;
using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Services
{
    public class ServiceTestsBase
    {
        public ServiceTestsBase()
        {
            // Fake Data
            _dataAssets = FakeAssets.InitialFakeAssets().ToList();
            _dataAssetAttributes = FakeAssetSettings.InitialFakeAssetSettings().ToList();
            _dataAssetTransactions = FakeAssetTransactions.InitialFakeAssetTransactions().ToList();
            _dataAssetTypes = FakeAssetTypes.InitialFakeAssetTypes().ToList();
            //_dataAssetTypesRelationsihpTypes = FakeAssetTypesRelationshipTypes.InitialFakeAssetTypesRelationshipTypes().ToList();
            //_dataAssetTypesSettingTypes = FakeAssetTypesSettingTypes.InitialFakeAssetTypesSettingTypes().ToList();
            //_dataParentChildRelationshipTypes = FakeParentChildRelationshipTypes.InitialFakeParentChildRelationshipTypes().ToList();
            //_dataRelationshipTypes = FakeRelationshipTypes.InitialFakeRelationshipTypes().ToList();
            //_dataSettingTypes = FakeSettingTypes.InitialFakeSettingTypes().ToList();
            _dataTransactionCategories = FakeTransactionCategories.InitialFakeTransactionCategories().ToList();
            //_dataTransactionDescriptions = FakeTransactionDescriptions.InitialFakeTransactionDescriptions().ToList();
            _dataTransactionTypes = FakeTransactionTypes.InitialFakeTransactionTypes().ToList();

            // Fake Repositories
            _repositoryAsset = new InMemoryAssetRepository(_dataAssets);
            _repositoryAssetSetting = new InMemoryAssetSettingRepository(_dataAssetAttributes);
            _repositoryAssetTransaction = new InMemoryAssetTransactionRepository(_dataAssetTransactions);
            _repositoryAssetType = new InMemoryAssetTypeRepository(_dataAssetTypes);
            //_repositoryAssetTypeRelationshipType = new InMemoryAssetTypeRelationshipTypeRepository(_dataAssetTypesRelationsihpTypes);
            //_repositoryAssetTypeSettingType = new InMemoryAssetTypeSettingTypeRepository(_dataAssetTypesSettingTypes);
            //_repositoryParentChildRelationshipType = new InMemoryParentChildRelationshipTypeRepository(_dataParentChildRelationshipTypes);
            //_repositoryRelationshipType = new InMemoryRelationshipTypeRepository(_dataRelationshipTypes);
            //_repositorySettingType = new InMemorySettingTypeRepository(_dataSettingTypes);
            _repositoryTransactionCategory = new InMemoryTransactionCategoryRepository(_dataTransactionCategories);
            //_repositoryTransactionDescription = new InMemoryTransactionDescriptionRepository(_dataTransactionDescriptions);
            _repositoryTransactionType = new InMemoryTransactionTypeRepository(_dataTransactionTypes);

            // Fake Unit of Work
            ResetUnitOfWork();
        }


        // Fake Data
        protected IList<Asset> _dataAssets;
        protected IList<AssetSetting> _dataAssetAttributes;
        protected IList<AssetTransaction> _dataAssetTransactions;
        protected IList<AssetType> _dataAssetTypes;
        protected IList<AssetTypeRelationshipType> _dataAssetTypesRelationshipTypes;
        protected IList<AssetTypeSettingType> _dataAssetTypesAttributeTypes;
        protected IList<ParentChildRelationshipType> _dataParentChildRelationshipTypes;
        protected IList<RelationshipType> _dataRelationshipTypes;
        protected IList<SettingType> _dataAttributeTypes;
        protected IList<TransactionCategory> _dataTransactionCategories;
        //protected IList<TransactionDescription> _dataTransactionDescriptions;
        protected IList<TransactionType> _dataTransactionTypes;

        // Fake Repositories
        protected InMemoryAssetRepository _repositoryAsset;
        protected InMemoryAssetSettingRepository _repositoryAssetSetting;
        protected InMemoryAssetTransactionRepository _repositoryAssetTransaction;
        protected InMemoryAssetTypeRepository _repositoryAssetType;
        //protected InMemoryAssetTypeRelationshipTypeRepository _repositoryAssetTypeRelationshipType;
        //protected InMemoryAssetTypeSettingTypeRepository _repositoryAssetTypeSettingType;
        //protected InMemoryParentChildRelationshipTypeRepository _repositoryParentChildRelationshipType;
        //protected InMemoryRelationshipTypeRepository _repositoryRelationshipType;
        //protected InMemorySettingTypeRepository _repositorySettingType;
        protected InMemoryTransactionCategoryRepository _repositoryTransactionCategory;
        //protected InMemoryTransactionDescriptionRepository _repositoryTransactionDescription;
        protected InMemoryTransactionTypeRepository _repositoryTransactionType;
        
        // Fake UOW
        protected InMemoryUnitOfWork _unitOfWork;

        public void ResetUnitOfWork()
        {
            _unitOfWork = new InMemoryUnitOfWork()
            {
                Assets = _repositoryAsset,
                AssetSettings = _repositoryAssetSetting,
                AssetTransactions = _repositoryAssetTransaction,
                AssetTypes = _repositoryAssetType,
                //AssetTypesRelationshipTypes = _repositoryAssetTypeRelationshipType,
                //AssetTypesSettingTypes = _repositoryAssetTypeSettingType,
                //ParentChildRelationshipTypes = _repositoryParentChildRelationshipType,
                //RelationshipTypes = _repositoryRelationshipType,
                //SettingTypes = _repositorySettingType,
                TransactionCategories = _repositoryTransactionCategory,
                //TransactionDescriptions = _repositoryTransactionDescription,
                TransactionTypes = _repositoryTransactionType
            };
        }

    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using Financial.Business.Services;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business
{
    public class BusinessService : IBusinessService
    {
        public BusinessService(IUnitOfWork unitOfWork)
        {
            SetServices(unitOfWork);
        }

        private void SetServices(IUnitOfWork unitOfWork)
        {
            AccountSettingService = new AccountSettingService(unitOfWork);

            AccountService = new AccountService(unitOfWork, AccountSettingService);
            AccountTransactionService = new AccountTransactionService(unitOfWork);
            AccountTypeService = new AccountTypeService(unitOfWork);
            AccountTypeSettingTypeService = new AccountTypeSettingTypeService(unitOfWork);
            SettingTypeService = new SettingTypeService(unitOfWork);
        }


        public IAccountService AccountService { get; private set; }
        public IAccountSettingService AccountSettingService { get; private set; }
        public IAccountTransactionService AccountTransactionService { get; private set; }
        public IAccountTypeService AccountTypeService { get; private set; }
        public IAccountTypeSettingTypeService AccountTypeSettingTypeService { get; private set; }
        public ISettingTypeService SettingTypeService { get; private set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.ParentChildRelationshipType
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Core.Models.ParentChildRelationshipType dtoSuppliedParentChildRelationshipType,
            Core.Models.RelationshipType dtoSuppliedRelationshipType, 
            List<SelectListItem> sliRelationshipLevels, string selectedRelationshipLevelId,
            List<SelectListItem> sliRelationshipTypes, int selectedRelationshipTypeId)
        {
            Id = dtoSuppliedParentChildRelationshipType.Id;
            RelationshipTypeId = dtoSuppliedRelationshipType.Id;
            RelationshipTypeName = dtoSuppliedRelationshipType.Name;
            SelectedRelationshipLevel = selectedRelationshipLevelId;
            RelationshipLevels = sliRelationshipLevels;
            SelectedRelationshipType = selectedRelationshipTypeId.ToString();
            RelationshipTypes = sliRelationshipTypes;
        }

        public int Id { get; set; }

        public int RelationshipTypeId { get; set; }
        [Display(Name = "Relationship Type")]
        public string RelationshipTypeName { get; set; }

        [Required]
        [Display(Name = "Relationship Level")]
        public string SelectedRelationshipLevel { get; set; }
        public IEnumerable<SelectListItem> RelationshipLevels { get; set; }

        [Required]
        [Display(Name = "Linked Relationship Type")]
        public string SelectedRelationshipType { get; set; }
        public IEnumerable<SelectListItem> RelationshipTypes { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AssetSetting
{
    public class CreateViewModel
    {
        public CreateViewModel()
        {

        }

        public CreateViewModel(Core.Models.Asset dtoAsset, Core.Models.SettingType dtoSettingType)
        {
            AssetId = dtoAsset.Id;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
        }


        public int AssetId { get; set; }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }
        public string Value { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("ParentChildRelationshipTypes")]
    public class ParentChildRelationshipType : BaseEntity
    {
        [Required]
        [Display(Name = "ParentRelationshipType ID")]
        public int ParentRelationshipTypeId { get; set; }
        [Required]
        [Display(Name = "ChildRelationshipType ID")]
        public int ChildRelationshipTypeId { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType
{
    public class DisplayParentChildRelationshipTypesViewModel
    {
        public DisplayParentChildRelationshipTypesViewModel() { }

        public DisplayParentChildRelationshipTypesViewModel(List<SelectListItem> sliParentChildRelationshipTypes, 
            string selectedParentChildRelationshipTypeId)
        {
            ParentChildRelationshipTypes = sliParentChildRelationshipTypes;
            SelectedParentChildRelationshipTypeId = selectedParentChildRelationshipTypeId;
        }


        [Required]
        [Display(Name = "Relationship Type")]
        public string SelectedParentChildRelationshipTypeId { get; set; }
        public IEnumerable<SelectListItem> ParentChildRelationshipTypes { get; set; }

    }
}
<file_sep>﻿using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Data.RepositoryInterfaces;

namespace Financial.Business.Tests.Fakes
{
    public class InMemoryUnitOfWork : IUnitOfWork
    {
        private bool _trans;

        public InMemoryUnitOfWork()
        {
            Committed = false;
        }

        public bool Committed { get; set; }

        public IAssetSettingRepository AssetSettings { get; set; }
        public IAssetRelationshipRepository AssetRelationships { get; set; }
        public IAssetRepository Assets { get; set; }
        public IAssetTransactionRepository AssetTransactions { get; set; }
        public IAssetTypeSettingTypeRepository AssetTypeSettingTypes { get; set; }
        public IAssetTypeRelationshipTypeRepository AssetTypeRelationshipTypes { get; set; }
        public IAssetTypeRepository AssetTypes { get; set; }
        public IParentChildRelationshipTypeRepository ParentChildRelationshipTypes { get; set; }
        public IRelationshipTypeRepository RelationshipTypes { get; set; }
        public ISettingTypeRepository SettingTypes { get; set; }
        public ITransactionCategoryRepository TransactionCategories { get; set; }
        public ITransactionDescriptionRepository TransactionDescriptions { get; set; }
        public ITransactionTypeRepository TransactionTypes { get; set; }


        public void BeginTrans()
        {
        }
        public void CommitTrans()
        {
            Complete();
        }
        public void RollBackTrans()
        {
        }
        public void Complete()
        {
            if (!_trans)
            {
                //_context.SaveChanges();
                Committed = true;
            }
        }
        public void Dispose()
        {
            //_context.Dispose();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.TransactionCategory
{
    public class IndexViewModel
    {
        public IndexViewModel() { }
        public IndexViewModel(Core.Models.TransactionCategory dtoTransactionCategory)
        {
            Id = dtoTransactionCategory.Id;
            Name = dtoTransactionCategory.Name;
        }

        public int Id { get; set; }
        public string Name { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("TransactionDescriptions")]
    public class TransactionDescription : BaseEntity
    {
        [Required]
        public string Name { get; set; }



        public ICollection<AssetTransaction> AssetTransactions { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Models
{
    public class AccountType
    {
        public AccountType() { }
        public AccountType(Core.Models.AssetType dtoAssetType)
        {
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
        }
        public AccountType(Core.Models.AssetType dtoAssetType,
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
            AssetTypeSettingTypeId = dtoAssetTypeSettingType.Id;
        }

        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }
        public int AssetTypeSettingTypeId { get; set; }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class TransactionTypeRepository : Repository<TransactionType>, ITransactionTypeRepository
    {
        public TransactionTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }





        public IEnumerable<TransactionType> GetAllActiveOrderedByName()
        {
            return FinancialDbContext.TransactionTypes
                .Where(r => r.IsActive)
                .OrderBy(r => r.Name)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Financial.Core.Models;
using System.Data.Entity;
using Moq;
using Financial.Core;
using Financial.Data.Repositories;
using Financial.Tests.Mocks;

namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class AssetTransactionRepositoryTests
    {
        private Asset _dbAsset;
        private AssetSetting _dbAssetSetting;
        private AssetTransaction _dbAssetTransaction;
        private AssetType _dbAssetType;
        private SettingType _dbSettingType;
        private TransactionCategory _dbTransactionCategory;
        private TransactionDescription _dbTransactionDescription;
        private TransactionType _dbTransactionType;
        private DbSet<AssetTransaction> _mockAssetTransactionDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private AssetTransactionRepository _repository;

        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset { Id = 2, AssetTypeId = _dbAssetType.Id, Name = "b", IsActive = true };
            _dbSettingType = new SettingType { Id = 3, Name = "c", IsActive = true };
            _dbAssetSetting = new AssetSetting { Id = 4, AssetId = _dbAsset.Id, SettingTypeId = _dbSettingType.Id, Value = "d", IsActive = true };
            _dbTransactionCategory = new TransactionCategory { Id = 5, Name = "e", IsActive = true };
            _dbTransactionDescription = new TransactionDescription { Id = 6, Name = "f", IsActive = true };
            _dbTransactionType = new TransactionType { Id = 7, Name = "g", IsActive = true };
            _dbAssetTransaction = new AssetTransaction
            {
                Id = 8,
                TransactionCategoryId = _dbTransactionCategory.Id,
                TransactionDescriptionId = _dbTransactionDescription.Id,
                TransactionTypeId = _dbTransactionType.Id,
                CheckNumber = "123",
                DueDate = new DateTime(1234, 5, 6),
                ClearDate = new DateTime(1234, 7, 8),
                Amount = 123.45M,
                Note = "abcdef",
                IsActive = true
            };

            // setup DbContext
            Setup_FakeDbContext();

            // set up repository
            _repository = new AssetTransactionRepository(_fakeDbContext);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void GetActive_WhenCalled_ReturnAssetTransaction_Test()
        {
            var result = _repository.GetAllActiveByDueDate();

            Assert.That(result, Is.InstanceOf<List<AssetTransaction>>());
        }



        // private methods


        private void Setup_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset },
                new List<AssetSetting> { _dbAssetSetting },
                new List<AssetTransaction> { _dbAssetTransaction },
                new List<AssetType> { _dbAssetType },
                new List<SettingType> { _dbSettingType },
                new List<TransactionCategory> { _dbTransactionCategory },
                new List<TransactionDescription> { _dbTransactionDescription },
                new List<TransactionType> { _dbTransactionType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetSetting> fakeAssetSettingList,
            List<AssetTransaction> fakeAssetTransactionList,
            List<AssetType> fakeAssetTypeList,
            List<SettingType> fakeSettingTypeList,
            List<TransactionCategory> fakeTransactionCategoryList,
            List<TransactionDescription> fakeTransactionDescriptionList,
            List<TransactionType> fakeTransactionTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetSettings: fakeAssetSettingList,
                assetTransactions: fakeAssetTransactionList,
                assetTypes: fakeAssetTypeList,
                settingTypes: fakeSettingTypeList,
                transactionCategories: fakeTransactionCategoryList,
                transactionDescriptions: fakeTransactionDescriptionList,
                transactionTypes: fakeTransactionTypeList);
        }

    }
}<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeTransactionTypes
    {
        public static IEnumerable<TransactionType> InitialFakeTransactionTypes()
        {
            yield return new TransactionType() { Id = 1, Name = "TransactionType1", IsActive = true };
            yield return new TransactionType() { Id = 2, Name = "TransactionType2", IsActive = true };
            yield return new TransactionType() { Id = 3, Name = "TransactionType3", IsActive = false };
            yield return new TransactionType() { Id = 4, Name = "TransactionType4", IsActive = true };
            yield return new TransactionType() { Id = 5, Name = "TransactionType5", IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IRelationshipTypeRepository : IRepository<RelationshipType>
    {
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountTransactions")]
    public class AssetTransaction : BaseEntity
    {
        [Required]
        [Display(Name = "Asset ID")]
        [Column("AccountId")]
        public int AssetId { get; set; }
        [Required]
        public int TransactionTypeId { get; set; }
        [Required]
        public int TransactionCategoryId { get; set; }
        [Required]
        public int TransactionDescriptionId { get; set; }
        [Display(Name = "Check Number")]
        public string CheckNumber { get; set; }
        [Required]
        [Display(Name = "Due")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
        public DateTime DueDate { get; set; }
        [Required]
        [Display(Name = "Cleared")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
        public DateTime ClearDate { get; set; }
        [Required]
        public decimal Amount { get; set; }
        public string Note { get; set; }





        [ForeignKey("AssetId")]
        public Asset Asset { get; set; }

        [ForeignKey("TransactionTypeId")]
        public TransactionType TransactionType { get; set; }

        [ForeignKey("TransactionCategoryId")]
        public TransactionCategory TransactionCategory { get; set; }

        [ForeignKey("TransactionDescriptionId")]
        public TransactionDescription TransactionDescription { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Financial.Core.Models;
using System.Data.Entity;
using Financial.Core;
using Moq;
using Financial.Data.Repositories;
using Financial.Tests.Mocks;

namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class TransactionCategoryRepositoryTests
    {
        private TransactionCategory _dbTransactionCategory;
        private DbSet<TransactionCategory> _mockTransactionTypeDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private TransactionCategoryRepository _repository;

        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _dbTransactionCategory = new TransactionCategory { Id = 1, Name = "a", IsActive = true };

            // setup DbContext
            Setup_FakeDbContext();

            // set up repository
            _repository = new TransactionCategoryRepository(_fakeDbContext);
        }

        [TearDown]
        public void TearDown()
        {

        }





        [Test]
        public void GetAllActiveOrderedByName_WhenCalled_ReturnTransactionCategoryIEnumerable_Test()
        {
            var result = _repository.GetAllActiveOrderedByName();

            Assert.That(result, Is.InstanceOf<IEnumerable<TransactionCategory>>());
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenCalled_ReturnTransactionCategoryValues_Test()
        {
            var result = _repository.GetAllActiveOrderedByName().ToList();

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Id, Is.EqualTo(_dbTransactionCategory.Id), "Id");
                Assert.That(result[0].Name, Is.EqualTo(_dbTransactionCategory.Name), "Name");
                Assert.That(result[0].IsActive, Is.EqualTo(_dbTransactionCategory.IsActive), "IsActive");
            });
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenMultipleTransactionCategoriesFound_ReturnListSortedAscendingByName_Test()
        {
            var fakeTransactionCategories = new List<TransactionCategory>
            {
                new TransactionCategory { Id = 1, Name = "z", IsActive = true },
                new TransactionCategory { Id = 2, Name = "a", IsActive = true }
            };

            Setup_Repository_FakeDbContext(fakeTransactionCategories);

            var result = _repository.GetAllActiveOrderedByName().ToList();

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Name, Is.EqualTo("a"), "First Index");
                Assert.That(result[1].Name, Is.EqualTo("z"), "Second Index");
            });
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenIsActiveEqualsFalse_DoNotReturnRecord_Test()
        {
            _dbTransactionCategory.IsActive = false;

            Setup_Repository_FakeDbContext();

            var result = _repository.GetAllActiveOrderedByName();

            Assert.That(result.Count(), Is.EqualTo(0));
        }





        // private methods


        private void Setup_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext(new List<TransactionCategory> {_dbTransactionCategory});
        }

        private void Setup_FakeDbContext(List<TransactionCategory> fakeTransactionCategoryList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(transactionCategories: fakeTransactionCategoryList);
        }

        private void Setup_Repository_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext();

            // set up repository
            _repository = new TransactionCategoryRepository(_fakeDbContext);
        }

        private void Setup_Repository_FakeDbContext(List<TransactionCategory> fakeTransactionCategoryList)
        {
            // setup dbContext
            Setup_FakeDbContext(fakeTransactionCategoryList);

            // set up repository
            _repository = new TransactionCategoryRepository(_fakeDbContext);
        }

    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace Financial.Core
{
    public class FinancialDbContext : DbContext, IFinancialDbContext
    {
        public virtual DbSet<Asset> Assets { get; set; }
        public virtual DbSet<AssetSetting> AssetSettings { get; set; }
        public virtual DbSet<AssetRelationship> AssetRelationships { get; set; }
        public virtual DbSet<AssetTransaction> AssetTransactions { get; set; }
        public virtual DbSet<AssetType> AssetTypes { get; set; }
        public virtual DbSet<AssetTypeSettingType> AssetTypesSettingTypes { get; set; }
        public virtual DbSet<AssetTypeRelationshipType> AssetTypesRelationshipTypes { get; set; }
        public virtual DbSet<ParentChildRelationshipType> ParentChildRelationshipTypes { get; set; }
        public virtual DbSet<RelationshipType> RelationshipTypes { get; set; }
        public virtual DbSet<SettingType> SettingTypes { get; set; }
        public virtual DbSet<TransactionCategory> TransactionCategories { get; set; }
        public virtual DbSet<TransactionDescription> TransactionDescriptions { get; set; }
        public virtual DbSet<TransactionType> TransactionTypes { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core.Models;

namespace Financial.Business.Utilities
{
    public static class AccountUtility
    {
        public static string FormatAccountName(string assetName, int assetTypeId, string assetAttributeValue)
        {
            // validate input
            if (string.IsNullOrEmpty(assetName))
                return string.Empty;

            // validate additional information
            if(string.IsNullOrEmpty(assetAttributeValue))
                return assetName;

            // (Credit Card)
            if (assetTypeId == AssetType.IdForCreditCard)
                return $"{assetName} ({assetAttributeValue})";

            return assetName;
        }


    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.Business.Services
{
    public class SettingTypeService : ISettingTypeService
    {
        private IUnitOfWork _unitOfWork;

        public SettingTypeService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        public AttributeType GetSettingType(int settingTypeId)
        {
            var dtoSettingType = _unitOfWork.SettingTypes.Get(settingTypeId);
            if (dtoSettingType == null)
            {
                return null;
            }
            return new AttributeType(dtoSettingType);
        }

        public List<AttributeType> GetListOfSettingTypes()
        {
            // get all active setting types from db
            return _unitOfWork.SettingTypes.GetAllActive()
                .Select(r => new AttributeType(r))
                .ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bmSettingType"></param>
        /// <returns>
        /// positive integer = record added.
        /// zero integer = name already exists.
        /// </returns>
        public int AddSettingType(AttributeType bmSettingType)
        {
            // check for existing name
            var exists = _unitOfWork.SettingTypes.GetAllActive()
                .Any(r => r.Name == bmSettingType.SettingTypeName);
            if (exists)
            {
                return 0;
            }

            // transfer bm to dto
            var dtoSettingType = new Core.Models.SettingType()
            {
                Name = bmSettingType.SettingTypeName,
                IsActive = true,
            };

            // update db
            _unitOfWork.SettingTypes.Add(dtoSettingType);
            _unitOfWork.CommitTrans();

            // return new ID
            return dtoSettingType.Id;
        }

        public bool EditSettingType(AttributeType bmSettingType)
        {
            // get dto
            var dtoSettingType = _unitOfWork.SettingTypes.Get(bmSettingType.SettingTypeId);
            if (dtoSettingType == null)
            {
                return false;
            }

            // transfer bm to dto
            dtoSettingType.Name = bmSettingType.SettingTypeName;

            // update db
            _unitOfWork.CommitTrans();

            return true;
        }


    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class AssetSettingRepository : Repository<AssetSetting>, IAssetSettingRepository
    {
        public AssetSettingRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }


        public AssetSetting GetActive(int assetId, int settingTypeId)
        {
            return FinancialDbContext.AssetSettings
                .Include(r => r.Asset)
                .Include(r => r.Asset.AssetType)
                .Include(r => r.SettingType)
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .FirstOrDefault(r => r.SettingTypeId == settingTypeId);
        }

        public IEnumerable<AssetSetting> GetAllActiveForAsset(int assetId)
        {
            return FinancialDbContext.AssetSettings
                .Include(r => r.Asset)
                .Include(r => r.SettingType)
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .ToList();
        }

        public IEnumerable<AssetSetting> GetAllActiveForSettingType(int settingTypeId)
        {
            return FinancialDbContext.AssetSettings
                .Include(r => r.Asset)
                .Include(r => r.SettingType)
                .Where(r => r.IsActive)
                .Where(r => r.SettingTypeId == settingTypeId)
                .ToList();
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType
{
    public class DeleteViewModel
    {
        public DeleteViewModel() { }

        public DeleteViewModel(Core.Models.AssetTypeRelationshipType dtoAssetTypeRelationshipType,
            Core.Models.AssetType dtoSuppliedAssetType,
            Core.Models.AssetType dtoLinkedAssetType, 
            Core.Models.RelationshipType dtoRelationshipType)
        {
            Id = dtoAssetTypeRelationshipType.Id;
            SuppliedAssetTypeId = dtoSuppliedAssetType.Id;
            SuppliedAssetTypeName = dtoSuppliedAssetType.Name;
            LinkedAssetTypeName = dtoLinkedAssetType.Name;
            RelationshipTypeName = dtoRelationshipType.Name;
        }


        public int Id { get; set; }
        public int SuppliedAssetTypeId { get; set; }
        [Display(Name = "Asset Type")]
        public string SuppliedAssetTypeName { get; set; }
        [Display(Name = "Relationship")]
        public string RelationshipTypeName { get; set; }
        [Display(Name = "Linked Asset Type")]
        public string LinkedAssetTypeName { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.Account
{
    public class CreateViewModel
    {
        public CreateViewModel()
        {
        }

        public CreateViewModel(List<SelectListItem> sliAssetTypes)
        {
            AssetTypes = sliAssetTypes;
        }

        public int Id { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string AssetName { get; set; }

        [Required]
        [Display(Name = "Type")]
        public string SelectedAssetTypeId { get; set; }
        public IEnumerable<SelectListItem> AssetTypes { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("RelationshipTypes")]
    public class RelationshipType : BaseEntity
    {
        [Required]
        public string Name { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Moq;
using System.Web.Mvc;
using System.Web.Razor.Generator;
using Financial;
using Financial.Business.Models;
using Financial.Business.Services;
using Financial.Business.ServiceInterfaces;
using Financial.Core.Models;
using Financial.Data;
using Financial.Data.RepositoryInterfaces;

namespace Financial.Tests.Business.Services
{
    [TestFixture]
    public class AccountServiceTests
    {
        private AccountService _service;
        private Mock<IUnitOfWork> _unitOfWork;
        private Mock<IAccountSettingService> _accountSettingService;
        private Asset _dbAsset;
        private AssetType _dbAssetType;
        private SettingType _dbSettingType;
        private AssetTypeSettingType _dbAssetTypeSettingType;

        [SetUp]
        public void SetUp()
        {
            _dbAsset = new Asset() { Id = 1, AssetTypeId = 2, Name = "a", IsActive = true };
            _dbAssetType = new AssetType() { Id = 2, Name = "b", IsActive = true };
            _dbSettingType = new Core.Models.SettingType() { Id = 3, Name = "c", IsActive = true };
            _dbAssetTypeSettingType = new AssetTypeSettingType() { AssetTypeId = 2, SettingTypeId = 3, IsActive = true };

            _unitOfWork = new Mock<IUnitOfWork>();
            _unitOfWork.Setup(uow => uow.Assets.GetAllActiveOrderedByName())
                .Returns(new List<Asset> { _dbAsset });
            _unitOfWork.Setup(uow => uow.AssetTypes.Get(_dbAsset.AssetTypeId))
                .Returns(_dbAssetType);

            _accountSettingService = new Mock<IAccountSettingService>();

            _service = new AccountService(
                _unitOfWork.Object, 
                _accountSettingService.Object);
        }

        [TearDown]
        public void TearDown()
        {

        }




        [Test]
        public void GetListOfAccounts_WhenCalled_ReturnAccountList_Test()
        {
            var result = _service.GetListOfAccounts();

            Assert.That(result, Is.TypeOf<List<Account>>());
        }

        [Test]
        public void GetListOfAccounts_WhenCalled_ShouldCallOneTimeUnitOfWorkRepositoryAssetsMethodGetAllActiveOrderedByName_Test()
        {
            _service.GetListOfAccounts();

            _unitOfWork.Verify(uow => uow.Assets.GetAllActiveOrderedByName(),
                Times.Once);
        }

        [Test]
        public void GetListOfAccounts_WhenAccountListHasAccounts_ShouldCallUnitOfWorkRepositoryAssetTypesMethodGet_Test()
        {
            _service.GetListOfAccounts();

            _unitOfWork.Verify(uow => uow.AssetTypes.Get(_dbAsset.AssetTypeId),
                Times.AtLeastOnce);
        }

        [Test]
        public void GetListOfAccounts_WhenAccountListHasAccount_ReturnAccountValues_Test()
        {
            var result = _service.GetListOfAccounts();

            Assert.Multiple(() =>
            {
                Assert.That(result.Count, Is.EqualTo(1), "Count");
                Assert.That(result[0].AssetId, Is.EqualTo(_dbAsset.Id), "Asset Id");
                Assert.That(result[0].AssetName, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result[0].AssetTypeId, Is.EqualTo(_dbAsset.AssetTypeId), "AssetType Id");
                Assert.That(result[0].AssetTypeName, Is.EqualTo(_dbAssetType.Name), "AssetType Name");
            });
        }

        [Test]
        public void GetListOfAccounts_WhenAccountTypeEqualsCreditCard_ReturnNameWithAccountNumber_Test()
        {
            SetUpForOneAccountWithAccountSettingEqualsCreditCard(accountName: "a", accountSettingValue: "1234");
            var expectedAssetName = "a (1234)";

            var result = (List<Account>)_service.GetListOfAccounts();

            Assert.That(result[0].AssetName, Is.EqualTo(expectedAssetName));
        }

        [Test]
        public void GetListOfAccounts_WhenAccountTypeIdEqualsZero_ReturnEmptyAccountList_Test()
        {
            _dbAsset.AssetTypeId = 0;

            var result = _service.GetListOfAccounts();

            Assert.That(result, Is.EquivalentTo(new List<Account>()));
        }

        [Test]
        public void GetListOfAccounts_WhenAccountListIsEmpty_ReturnEmptyAccountList_Test()
        {
            _unitOfWork.Setup(uow => uow.Assets.GetAllActiveOrderedByName())
                .Returns(new List<Financial.Core.Models.Asset>());

            _service = new AccountService(
                _unitOfWork.Object,
                _accountSettingService.Object);

            var result = _service.GetListOfAccounts();

            Assert.That(result.Count, Is.EqualTo(0));
        }






        [Test]
        public void GetSelectListOfAccounts_WhenCalled_ReturnSelectListItemList_Test()
        {
            var result = _service.GetSelectListOfAccounts(selectedId: null);

            Assert.That(result, Is.TypeOf<List<SelectListItem>>());
        }

        [Test]
        public void GetSelectListOfAccounts_WhenAssetFound_ShouldCallOneTimeAssetSettingServiceMethodGetAccountIdentificationInformation_Test()
        {
            _service.GetSelectListOfAccounts(_dbAsset.Id);

            _accountSettingService.Verify(
                asSvc => asSvc.GetAccountIdentificationInformation(new Account(_dbAsset)),
                Times.Once);
        }

        [Test]
        public void GetSelectListOfAccounts_WhenSelectedAssetIdProvided_ReturnListWithAccountSelected_Test()
        {
            var result = _service.GetSelectListOfAccounts(_dbAsset.Id);

            Assert.IsTrue(result.Any(r => r.Selected));
        }



        // private


        private void SetUpForOneAccountWithAccountSettingEqualsCreditCard(string accountName, string accountSettingValue)
        {
            var assetId = 1;
            var assetSettingId = 2;
            var assetTypeId = AssetType.IdForCreditCard;
            var settingTypeId = Core.Models.SettingType.IdForAccountNumber;

            _unitOfWork.Setup(uow => uow.Assets.GetAllActiveOrderedByName())
                .Returns(new List<Asset> { new Asset { Id = assetId, Name = accountName, AssetTypeId = assetTypeId, IsActive = true } });
            _unitOfWork.Setup(uow => uow.AssetTypes.Get(assetTypeId))
                .Returns(new AssetType { Id = assetTypeId, Name = "b", IsActive = true });
            _unitOfWork.Setup(uow => uow.AssetSettings.GetActive(assetId, settingTypeId))
                .Returns(new AssetSetting { Id = assetSettingId, AssetId = assetId, SettingTypeId = assetTypeId, Value = accountSettingValue, IsActive = true });

            _service = new AccountService(
                _unitOfWork.Object,
                _accountSettingService.Object);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetSetting
{
    public class EditLinkedSettingTypesViewModel
    {
        public EditLinkedSettingTypesViewModel() { }

        public EditLinkedSettingTypesViewModel(Core.Models.Asset dtoAsset,
            Core.Models.AssetType dtoAssetType, List<EditViewModel> vmEdit)
        {
            AssetId = dtoAsset.Id;
            AssetName = dtoAsset.Name;
            AssetTypeName = dtoAssetType.Name;
            EditViewModels = vmEdit;
        }

        public int AssetId { get; set; }
        [Display(Name = "Name")]
        public string AssetName { get; set; }
        [Display(Name = "Type")]
        public string AssetTypeName { get; set; }
        public List<EditViewModel> EditViewModels { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Financial.Core.Models;
using System.Data.Entity;
using Moq;
using Financial.Core;
using Financial.Data.Repositories;
using Financial.Tests.Mocks;

namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class AssetSettingRepositoryTests
    {
        private Asset _dbAsset;
        private AssetSetting _dbAssetSetting;
        private AssetType _dbAssetType;
        private SettingType _dbSettingType;
        private DbSet<AssetSetting> _mockAssetSettingDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private AssetSettingRepository _repository;

        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset
            {
                Id = 2,
                AssetTypeId = _dbAssetType.Id,
                AssetType = _dbAssetType, // setup include
                Name = "b",
                IsActive = true
            };
            _dbSettingType = new SettingType { Id = 3, Name = "c", IsActive = true };
            _dbAssetSetting = new AssetSetting
            {
                Id = 4,
                AssetId = _dbAsset.Id,
                Asset = _dbAsset, // setup include
                SettingTypeId = _dbSettingType.Id,
                SettingType = _dbSettingType, // setup include
                Value = "d",
                IsActive = true
            };

            // setup DbContext
            Setup_FakeDbContext();

            // setup repository
            _repository = new AssetSettingRepository(_fakeDbContext);
        }

        [TearDown]
        public void TearDown()
        {

        }




        [Test]
        public void GetActive_WhenCalled_ReturnAssetSetting_Test()
        {           
            var result = _repository.GetActive(_dbAssetSetting.AssetId, _dbAssetSetting.SettingTypeId);

            Assert.That(result, Is.InstanceOf<AssetSetting>());
        }

        [Test]
        public void GetActive_WhenCalled_ReturnAssetSettingValues_Test()
        {
            var result = _repository.GetActive(_dbAssetSetting.AssetId, _dbAssetSetting.SettingTypeId);

            Assert.Multiple(() =>
            {
                Assert.That(result.Id, Is.EqualTo(_dbAssetSetting.Id), "AssetSetting Id");
                Assert.That(result.AssetId, Is.EqualTo(_dbAssetSetting.AssetId), "Asset Id");
                Assert.That(result.Asset.Name, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result.SettingTypeId, Is.EqualTo(_dbAssetSetting.SettingTypeId), "SettingType Id");
                Assert.That(result.SettingType.Name, Is.EqualTo(_dbSettingType.Name), "SettingType Name");
                Assert.That(result.Value, Is.EqualTo(_dbAssetSetting.Value), "AssetSetting Value");
                Assert.That(result.IsActive, Is.EqualTo(_dbAssetSetting.IsActive), "IsActive");
            });
        }



        // private methods



        private void Setup_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset },
                new List<AssetType> { _dbAssetType },
                new List<AssetSetting> { _dbAssetSetting },
                new List<SettingType> { _dbSettingType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetType> fakeAssetTypeList,
            List<AssetSetting> fakeAssetSettingList,
            List<SettingType> fakeSettingTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetTypes: fakeAssetTypeList,
                assetSettings: fakeAssetSettingList,
                settingTypes: fakeSettingTypeList);
        }

    }
}
<file_sep>﻿using Financial.Business.ServiceInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business
{
    public interface IBusinessService
    {
        IAccountService AccountService { get; }
        IAccountSettingService AccountSettingService { get; }
        IAccountTransactionService AccountTransactionService { get; }
        IAccountTypeService AccountTypeService { get; }
        IAccountTypeSettingTypeService AccountTypeSettingTypeService { get; }
        ISettingTypeService SettingTypeService { get; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core;
using NUnit.Framework;
using Moq;
using Financial.Data.Repositories;
using System.Data.Entity;
using Financial.Core.Models;
using Financial.Tests.Mocks;

namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class RepositoryTests
    {
        private BaseEntity _baseEntity;
        private DbSet<BaseEntity> _mockDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private Repository<BaseEntity> _repository;



        [SetUp]
        public void SetUp()
        {
            // setup fake db
            var fakeAssets = new List<BaseEntity>();

            SetupMockWithNewFakeDb(fakeAssets);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void Get_WhenIdIsValid_ReturnEntity_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity {Id = 1, IsActive = true};

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.Get(id: 1);

            // Assert
            Assert.That(result, Is.EqualTo(fakeEntity));
        }

        [Test]
        public void Get_WhenIdIsNotValid_ReturnNull_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity { Id = 1, IsActive = true };

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.Get(id: 2);

            // Assert
            Assert.That(result, Is.EqualTo(null));
        }



        [Test]
        public void GetActive_WhenEntityIsActiveEqualsTrue_ReturnEntity_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity { Id = 1, IsActive = true };

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.GetActive(id: 1);

            // Assert
            Assert.That(result, Is.EqualTo(fakeEntity));
        }

        [Test]
        public void GetActive_WhenEntityIsActiveEqualsFalse_ReturnNull_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity { Id = 1, IsActive = false };

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.GetActive(id: 1);

            // Assert
            Assert.That(result, Is.EqualTo(null));
        }



        [Test]
        public void GetAll_WhenCalled_ReturnAllEntities_Test()
        {
            // Arrange
            var fakeEntities = new List<BaseEntity>
            {
                new BaseEntity { Id = 1, IsActive = true },
                new BaseEntity { Id = 2, IsActive = true }
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.GetAll();

            // Assert
            Assert.That(result.Count(), Is.EqualTo(2));
        }



        [Test]
        public void GetAllActive_WhenCalled_ReturnEntitiesThatIsActiveEqualsTrue_Test()
        {
            // Arrange
            var fakeEntities = new List<BaseEntity>
            {
                new BaseEntity { Id = 1, IsActive = true },
                new BaseEntity { Id = 2, IsActive = false }
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.GetAllActive();

            // Assert
            Assert.That(result.Count(), Is.EqualTo(1));
        }



        [Test]
        public void Exists_WhenIdIsValid_ReturnTrue_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity { Id = 1, IsActive = true };

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.Exists(id: 1);

            // Assert
            Assert.That(result, Is.EqualTo(true));
        }

        [Test]
        public void Exists_WhenIdIsNotValid_ReturnFalse_Test()
        {
            // Arrange
            var fakeEntity = new BaseEntity { Id = 1, IsActive = true };

            var fakeEntities = new List<BaseEntity>
            {
                fakeEntity,
            };

            SetupMockWithNewFakeDb(fakeEntities);

            // Act
            var result = _repository.Exists(id: 2);

            // Assert
            Assert.That(result, Is.EqualTo(false));
        }



        [Test]
        public void Add_WhenEntityProvided_CallDbContextAddProperty_Test()
        {
            // Arrange
            var newEntity = new BaseEntity { /*Id = 1,*/ IsActive = true };
            var count = 0;
            _mockDbContext.Setup(a => a.Set<BaseEntity>().Add(It.IsAny<BaseEntity>()))
                .Callback(() => count++);

            // Act
            _repository.Add(newEntity);

            // Assert
            Assert.That(count, Is.EqualTo(1));
        }

        [Test]
        public void Add_WhenEntityProvided_UpdateDbContextWithEntity_Test()
        {
            // Arrange
            var newEntity = new BaseEntity { /*Id = 1,*/ IsActive = true };
            var count = 0;
            _mockDbContext.Setup(a => a.Set<BaseEntity>().Add(It.IsAny<BaseEntity>()))
                .Callback(() => count++);

            // Act
            _repository.Add(newEntity);

            // Assert
            Assert.That(count, Is.EqualTo(1));
        }



        [Test]
        public void AddRange_WhenEntitiesProvided_CallDbContextAddRangeProperty_Test()
        {
            // Arrange
            var newEntities = new List<BaseEntity>
            {
                new BaseEntity { /*Id = 1,*/ IsActive = true },
                new BaseEntity { /*Id = 2,*/ IsActive = true },
            };
            var count = 0;
            _mockDbContext.Setup(a => a.Set<BaseEntity>().AddRange(It.IsAny<List<BaseEntity>>()))
                .Callback(() => count++);

            // Act
            _repository.AddRange(newEntities);

            // Assert
            Assert.That(count, Is.EqualTo(1));
        }



        [Test]
        public void Remove_WhenEntityProvided_CallDbContextRemoveProperty_Test()
        {
            // Arrange
            var newEntity = new BaseEntity { /*Id = 1,*/ IsActive = true };
            var count = 0;
            _mockDbContext.Setup(a => a.Set<BaseEntity>().Remove(It.IsAny<BaseEntity>()))
                .Callback(() => count++);

            // Act
            _repository.Remove(newEntity);

            // Assert
            Assert.That(count, Is.EqualTo(1));
        }



        [Test]
        public void RemoveRange_WhenEntitiesProvided_CallDbContextRemoveProperty_Test()
        {
            // Arrange
            var newEntities = new List<BaseEntity>
            {
                new BaseEntity { /*Id = 1,*/ IsActive = true },
                new BaseEntity { /*Id = 2,*/ IsActive = true },
            };
            var count = 0;
            _mockDbContext.Setup(a => a.Set<BaseEntity>().RemoveRange(It.IsAny<List<BaseEntity>>()))
                .Callback(() => count++);

            // Act
            _repository.RemoveRange(newEntities);

            // Assert
            Assert.That(count, Is.EqualTo(1));
        }





        // private methods



        private void SetupMockWithNewFakeDb(List<BaseEntity> fakeBaseEntities)
        {
            // setup DbSet
            _mockDbSet = MockDbSet.Create<BaseEntity>(fakeBaseEntities);

            // setup DbContext
            _mockDbContext = new Mock<FinancialDbContext>();
            _mockDbContext.Setup(c => c.Set<BaseEntity>())
                .Returns(_mockDbSet);

            // set up repository
            _repository = new Repository<BaseEntity>(_mockDbContext.Object);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class IndexSettingTypesForAssetTypeViewModel
    {
        public IndexSettingTypesForAssetTypeViewModel() { }
        public IndexSettingTypesForAssetTypeViewModel(Business.Models.AttributeType bmSettingType, Business.Models.AccountTypeSettingType bmAssetTypeSettingType)
        {
            AssetTypeSettingTypeId = bmAssetTypeSettingType.AssetTypeSettingTypeId;
            AssetTypeId = bmAssetTypeSettingType.AssetTypeId;
            SettingTypeId = bmSettingType.SettingTypeId;
            SettingTypeName = bmSettingType.SettingTypeName;
            IsLinked = bmAssetTypeSettingType.AssetTypeId > 0;
        }
        public IndexSettingTypesForAssetTypeViewModel(int assetTypeId, Business.Models.AttributeType bmSettingTypeLinked)
        {
            AssetTypeSettingTypeId = bmSettingTypeLinked.AssetTypeSettingTypeId;
            AssetTypeId = assetTypeId;
            SettingTypeId = bmSettingTypeLinked.SettingTypeId;
            SettingTypeName = bmSettingTypeLinked.SettingTypeName;
            IsLinked = bmSettingTypeLinked.AssetTypeSettingTypeId > 0;
        }

        public int AssetTypeId { get; set; }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }
        public int AssetTypeSettingTypeId { get; set; }
        public bool IsLinked { get; set; }
    }
}<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class AssetTypeRelationshipTypeRepository : Repository<AssetTypeRelationshipType>, IAssetTypeRelationshipTypeRepository
    {
        public AssetTypeRelationshipTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using NUnit.Framework;
using Moq;
using Financial;
using Financial.Business;
using Financial.Business.Models;
using Financial.Core;
using Financial.Data;
using Financial.WebApplication.Controllers;
using Financial.WebApplication.Models.ViewModels.Account;

namespace Financial.Tests.WebApplication.Controllers
{
    [TestFixture]
    public class AccountControllerTests
    {
        private AccountController _controller;
        private Mock<IUnitOfWork> _unitOfWork;
        private Mock<IBusinessService> _businessService;
        private Account _account;
        private Financial.Core.Models.Asset _asset;
        private SelectListItem _sliAsset;


        [SetUp]
        public void SetUp()
        {
            _asset = new Financial.Core.Models.Asset { Id = 1, AssetTypeId = 2, Name = "a", IsActive = true };
            _sliAsset = new SelectListItem { Value = _asset.Id.ToString(), Text = _asset.Name, Selected = false };
            _account = new Account{ AssetId = 1, AssetName = "a", AssetTypeId = 2 };

            _unitOfWork = new Mock<IUnitOfWork>();
            _unitOfWork.SetupAllProperties();

            _businessService = new Mock<IBusinessService>();
            _businessService.Setup(bs => bs.AccountService.GetListOfAccounts())
                .Returns(new List<Account> { _account });

            _controller = new AccountController(_unitOfWork.Object, _businessService.Object);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void Index_WhenCalled_ReturnsIndexView_Test()
        {
            var result = _controller.Index();

            Assert.That(result.ViewName, Is.EqualTo("Index"));
        }

        [Test]
        public void Index_WhenCalled_ReturnsIndexViewModelList_Test()
        {
            var result = _controller.Index();

            Assert.That(result.ViewData.Model, Is.TypeOf<List<IndexViewModel>>());
        }

        [Test]
        public void Index_WhenCalled_ShouldCallOneTimeAccountServiceMethodGetListOfAccounts_Test()
        {
            _controller.Index();

            _businessService.Verify(bs => bs.AccountService.GetListOfAccounts(),
                Times.Once);
        }

        [Test]
        public void Index_WhenAccountsFound_ReturnAccountsOrderedAscendingByName_Test()
        {
            var alphaFirstAssetName = "a";
            var alphaLastAssetName = "z";
            SetUpAccountsOrderedDescendingByAssetName(alphaFirstAssetName, alphaLastAssetName);

            var result = _controller.Index();

            var vmActual = (List<IndexViewModel>) result.Model;

            Assert.Multiple(() =>
            {
                Assert.That(vmActual.Count, Is.EqualTo(2), "Count");
                Assert.That(vmActual[0].AssetName, Is.EqualTo(alphaFirstAssetName), "First Index");
                Assert.That(vmActual[1].AssetName, Is.EqualTo(alphaLastAssetName), "Second Index");
            });
        }

        [Test]
        public void Index_WhenTempDataSuccessMessageIsNotNull_ReturnViewDataSuccessMessage_Test()
        {
            var expectedMessage = "test message";
            _controller.TempData["SuccessMessage"] = expectedMessage;

            var result = _controller.Index();

            var vResult = (ViewResult) result;

            Assert.That(vResult.ViewData["SuccessMessage"].ToString(), Is.EqualTo(expectedMessage));
        }

        [Test]
        public void Index_WhenTempDataErrorMessageIsNotNull_ReturnViewDataErrorMessage_Test()
        {
            var expectedMessage = "test message";
            _controller.TempData["ErrorMessage"] = expectedMessage;

            var result = _controller.Index();

            var vResult = (ViewResult)result;

            Assert.That(vResult.ViewData["ErrorMessage"].ToString(), Is.EqualTo(expectedMessage));
        }

        [Test]
        public void Index_WhenAccountListEqualsNull_ReturnEmptyViewModelList_Test()
        {
            _businessService.Setup(bs => bs.AccountService.GetListOfAccounts());

            _controller = new AccountController(_unitOfWork.Object, _businessService.Object);

            var result = _controller.Index();

            var vmActual = (List<IndexViewModel>)result.Model;

            Assert.That(vmActual.Count, Is.EqualTo(0));
        }



        // private

        private void SetUpAccountsOrderedDescendingByAssetName(string alphaFirstAssetName, string alphaLastAssetName)
        {
            _businessService.Setup(bs => bs.AccountService.GetListOfAccounts())
                .Returns(new List<Account>
                {
                    new Account {AssetId = 1, AssetName = alphaLastAssetName, AssetTypeId = 3, AssetTypeName = "type" },
                    new Account {AssetId = 1, AssetName = alphaFirstAssetName, AssetTypeId = 3, AssetTypeName = "type" },
                });

            _controller = new AccountController(_unitOfWork.Object, _businessService.Object);

        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{ 
    public static class FakeAssetTransactions
    {
        public static IEnumerable<AssetTransaction> InitialFakeAssetTransactions()
        {
            yield return new AssetTransaction() { Id = 1, AssetId = 2, TransactionTypeId = 4, TransactionCategoryId = 5, TransactionDescriptionId = 2, Amount = 1.11M, IsActive = true };
            yield return new AssetTransaction() { Id = 2, AssetId = 1, TransactionTypeId = 5, TransactionCategoryId = 4, TransactionDescriptionId = 4, Amount = 2.22M, IsActive = true };
            yield return new AssetTransaction() { Id = 3, AssetId = 2, TransactionTypeId = 1, TransactionCategoryId = 4, TransactionDescriptionId = 5, Amount = 3.33M, IsActive = false };
            yield return new AssetTransaction() { Id = 4, AssetId = 5, TransactionTypeId = 2, TransactionCategoryId = 1, TransactionDescriptionId = 5, Amount = 4.44M, IsActive = true };
            yield return new AssetTransaction() { Id = 5, AssetId = 4, TransactionTypeId = 1, TransactionCategoryId = 2, TransactionDescriptionId = 1, Amount = 5.55M, IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Models;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeSettingType
{
    public class CreateLinkedSettingTypesViewModel
    {
        public CreateLinkedSettingTypesViewModel()
        {

        }
        public CreateLinkedSettingTypesViewModel(Business.Models.AccountType bmAssetType,
            List<Business.Models.AttributeType> bmSettingTypes)
        {
            AssetTypeId = bmAssetType.AssetTypeId;
            AssetTypeName = bmAssetType.AssetTypeName;
            SettingTypes = bmSettingTypes;
        }

        public int AssetTypeId { get; set; }

        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }

        public List<Business.Models.AccountTypeSettingType> LinkedAssetTypeSettingTypes { get; set; }
        public List<Business.Models.AttributeType> SettingTypes { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;
//using Financial.Business.Models.BusinessModels;
using Financial.Business.Utilities;
using Financial.WebApplication.Models.ViewModels.AssetTypeSettingType;
using Financial.Data;
using Financial.Business.Models;
using Financial.Business.ServiceInterfaces;

namespace Financial.WebApplication.Controllers
{
    public class AssetTypeSettingTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IAccountTypeSettingTypeService _assetTypeSettingTypeService;
        
        public AssetTypeSettingTypeController(IUnitOfWork unitOfWork, IAccountTypeSettingTypeService assetTypeSettingTypeService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _assetTypeSettingTypeService = assetTypeSettingTypeService;
        }

        [ChildActionOnly]
        public ActionResult IndexLinkedSettingTypes(int assetTypeId)
        {
            try
            {
                // transfer bm to vm
                var vmIndexLinkedSettingTypes = _assetTypeSettingTypeService.GetListOfLinkedSettingTypes(assetTypeId)
                    .OrderBy(r => r.SettingTypeName)
                    .Select(r => new IndexLinkedSettingTypesViewModel(r))
                    .ToList();

                return PartialView("_IndexLinkedSettingTypes", vmIndexLinkedSettingTypes);
            }
            catch (Exception)
            {
                ViewData["ErrorMessage"] = "Encountered problem";
                return PartialView("_IndexLinkedSettingTypes", new List<IndexLinkedSettingTypesViewModel>());
            }
        }

        [ChildActionOnly]
        public ActionResult IndexLinkedAssetTypes(int settingTypeId)
        {
            try
            {
                // transfer bm to vm
                var vmIndexLinkedAssetTypes = _assetTypeSettingTypeService.GetListOfLinkedAssetTypes(settingTypeId)
                    .OrderBy(r => r.AssetTypeName)
                    .Select(r => new IndexLinkedSettingTypesViewModel(r))
                    .ToList();

                return PartialView("_IndexLinkedAssetTypes", vmIndexLinkedAssetTypes);
            }
            catch (Exception)
            {
                ViewData["ErrorMessage"] = "Encountered problem";
                return PartialView("_IndexLinkedAssetTypes", new List<IndexLinkedAssetTypesViewModel>());
            }
        }

        [HttpGet]
        public ActionResult CreateLinkedSettingTypes(int assetTypeId)
        {
            try
            {
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // get bm for supplied id
                var bmAssetType = _assetTypeSettingTypeService.CreateLinkedSettingTypesGetModel(assetTypeId);
                if(bmAssetType == null)
                {
                    TempData["ErrorMessage"] = "Unable to create record. Try again.";
                    return RedirectToAction("Index", "AssetType");
                }

                // get bm for linked setting types
                var bmSettingTypes = _assetTypeSettingTypeService.GetListOfSettingTypesWithLinkedAssetType(bmAssetType.AssetTypeId);

                // transfer bm to vm
                return View("CreateLinkedSettingTypes", new CreateLinkedSettingTypesViewModel(bmAssetType, bmSettingTypes));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateLinkedSettingTypes(CreateLinkedSettingTypesViewModel vmCreateLinkedSettingTypes)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return RedirectToAction("Index", "AssetType");
                }

                // transfer vm to bm
                foreach(var vmSettingType in vmCreateLinkedSettingTypes.SettingTypes)
                {

                }




                if (ModelState.IsValid)
                {
                    // transfer vm to db
                    foreach (var atstLink in vmCreateLinkedSettingTypes.LinkedAssetTypeSettingTypes)
                    {
                        _unitOfWork.AssetTypeSettingTypes.Add(new Core.Models.AssetTypeSettingType()
                        {
                            AssetTypeId = atstLink.AssetTypeId,
                            SettingTypeId = atstLink.SettingTypeId,
                            //IsActive = atstLink.IsActive
                        });
                    }

                    // complete db update
                    _unitOfWork.CommitTrans();

                    // display view with message
                    TempData["SuccessMessage"] = "Linked setting types created.";
                    return RedirectToAction("Index", "AssetType");
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "AssetType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpGet]
        public ActionResult CreateLinkedAssetTypes(int? settingTypeId)
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }

            try
            { 
                // transfer dto to vm
                var dtoSettingType = _unitOfWork.AssetTypes.Get(DataTypeUtility.GetIntegerFromString(settingTypeId.ToString()));
                if (dtoSettingType != null)
                {
                    /*
                    var atstLinks = _unitOfWork.AssetTypes.GetAllActive()
                        .Select(r => new AssetTypeSettingType(r, dtoSettingType))
                        .ToList();
                    */
                    // display view
                    //return View("CreateLinkedAssetTypes", new CreateLinkedAssetTypesViewModel(dtoSettingType, atstLinks));
                    return View("CreateLinkedAssetTypes", new CreateLinkedAssetTypesViewModel());
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "SettingType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateLinkedAssetTypes(CreateLinkedAssetTypesViewModel vmCreateLinkedAssetTypes)
        {
            try
            { 
                if (ModelState.IsValid)
                {
                    // transfer vm to db
                    foreach (var atstLink in vmCreateLinkedAssetTypes.LinkedAssetTypeSettingTypes)
                    {
                        _unitOfWork.AssetTypeSettingTypes.Add(new Core.Models.AssetTypeSettingType()
                        {
                            AssetTypeId = atstLink.AssetTypeId,
                            SettingTypeId = atstLink.SettingTypeId,
                            //IsActive = atstLink.IsActive
                        });
                    }

                    // complete db update
                    _unitOfWork.CommitTrans();

                    // display view with message
                    TempData["SuccessMessage"] = "Linked asset types created";
                    return RedirectToAction("Index", "SettingType", new { id = vmCreateLinkedAssetTypes.SettingTypeId });
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "SettingType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpGet]
        public ActionResult EditLinkedSettingTypes(int assetTypeId)
        {
            try
            {
                // transfer dto to bm
                var bmAssetType = _assetTypeSettingTypeService.EditLinkedSettingTypesGetModel(assetTypeId);
                if(bmAssetType == null)
                {
                    TempData["ErrorMessage"] = "Problem displaying asset type";
                    return RedirectToAction("Index", "AssetType");
                }

                //var bmSettingTypes = _businessService.AssetTypeSettingTypeService.GetListOfSettingTypesWithLinkedAssetType(assetTypeId);

                return View("EditLinkedSettingTypes", new EditLinkedSettingTypesViewModel(bmAssetType));


                /*
                // transfer dto for Id
                var dtoAssetType = _unitOfWork.AssetTypes.Get(assetTypeId);
                if (dtoAssetType != null)
                {
                    
                    // get list of all active setting types
                    var atstLinks = new List<AssetTypeSettingType>();
                    var dbSettingTypes = _unitOfWork.SettingTypes.GetAllActive();
                    foreach (var dtoSettingType in dbSettingTypes)
                    {
                        // transfer dto to vm
                        var dtoAssetTypeSettingType = _unitOfWork.AssetTypesSettingTypes.Get(dtoAssetType.Id, dtoSettingType.Id);
                        var link = dtoAssetTypeSettingType != null
                            ? new AssetTypeSettingType(dtoAssetTypeSettingType, dtoAssetType, dtoSettingType)
                            : new AssetTypeSettingType(new Core.Models.AssetTypeSettingType(), dtoAssetType, dtoSettingType);
                        atstLinks.Add(link);
                    }
                    
                    // display view
                    //return View("EditLinkedSettingTypes", new EditLinkedSettingTypesViewModel(dtoAssetType, atstLinks));
                    return View("EditLinkedSettingTypes", new EditLinkedSettingTypesViewModel());
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "AssetType");
                */
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditLinkedSettingTypes(EditLinkedSettingTypesViewModel vmEditLinks)
        {
            try
            { 
                if (ModelState.IsValid)
                {
                    /*
                    foreach (var atstLink in vmEditLinks.LinkedAssetTypeSettingTypes)
                    {
                        // transfer vm to dto
                        var dtoAssetTypeSettingType = _unitOfWork.AssetTypesSettingTypes.Get(atstLink.Id);
                        if (dtoAssetTypeSettingType != null)
                        {
                            // update dto
                            dtoAssetTypeSettingType.IsActive = atstLink.IsActive;
                        }
                        else if(atstLink.Id == 0)
                        {
                            // create new dto
                            _unitOfWork.AssetTypesSettingTypes.Add(new Core.Models.AssetTypeSettingType()
                            {
                                AssetTypeId = atstLink.AssetTypeId,
                                SettingTypeId = atstLink.SettingTypeId,
                                IsActive = true
                            });
                        }
                    }

                    // complete db update
                    _unitOfWork.CommitTrans();
                    */
                    // display view with message
                    TempData["SuccessMessage"] = "Linked setting types updated.";
                    return RedirectToAction("Details", "AssetType", new { id = vmEditLinks.AssetTypeId });
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "AssetType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetType");
            }
        }

        [ChildActionOnly]
        public ActionResult IndexSettingTypesForAssetType(int assetTypeId)
        {
            try
            {
                var vmIndex = _assetTypeSettingTypeService.GetListOfSettingTypesWithLinkedAssetType(assetTypeId)
                    .Select(st => new IndexSettingTypesForAssetTypeViewModel(assetTypeId, st))
                    .ToList();

                return PartialView("_IndexSettingTypesForAssetType", vmIndex);
            }
            catch (Exception)
            {
                return PartialView("_IndexSettingTypesForAssetType", new List<IndexSettingTypesForAssetTypeViewModel>());
            }
        }

        [HttpGet]
        public ActionResult EditLinkedAssetTypes(int settingTypeId)
        {
            try
            { 
                // transfer dto for id
                var dtoSettingType = _unitOfWork.SettingTypes.Get(settingTypeId);
                if (dtoSettingType != null)
                {
                    /*
                    // get list of all active asset types
                    var atstLinks = new List<AssetTypeSettingType>();
                    var dbAssetTypes = _unitOfWork.AssetTypes.GetAllActive();
                    foreach (var dtoAssetType in dbAssetTypes)
                    {
                        // transfer dto to vm
                        var dtoAssetTypeSettingType = _unitOfWork.AssetTypesSettingTypes.Get(dtoAssetType.Id, dtoSettingType.Id);
                        var link = dtoAssetTypeSettingType != null
                            ? new AssetTypeSettingType(dtoAssetTypeSettingType, dtoAssetType, dtoSettingType)
                            : new AssetTypeSettingType(new Core.Models.AssetTypeSettingType(), dtoAssetType, dtoSettingType);
                        atstLinks.Add(link);
                    }
                    */

                    // display view
                    //return View("EditLinkedAssetTypes", new EditLinkedAssetTypesViewModel(dtoSettingType, atstLinks));
                    return View("EditLinkedAssetTypes", new EditLinkedAssetTypesViewModel());
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "SettingType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditLinkedAssetTypes(EditLinkedAssetTypesViewModel vmEditLinkedAssetTypes)
        {
            try
            { 
                if(ModelState.IsValid)
                { 
                    /*
                    // transfer vm to dto
                    foreach(var atstLink in vmEditLinkedAssetTypes.LinkedAssetTypeSettingTypes)
                    {
                        // transfer vm to dto
                        var dtoAssetTypeSettingType = _unitOfWork.AssetTypesSettingTypes.Get(atstLink.Id);
                        if (dtoAssetTypeSettingType != null)
                        {
                            // update dto
                            dtoAssetTypeSettingType.IsActive = atstLink.IsActive;
                        }
                        else if (atstLink.Id == 0)
                        {
                            // create new dto
                            _unitOfWork.AssetTypesSettingTypes.Add(new Core.Models.AssetTypeSettingType()
                            {
                                AssetTypeId = atstLink.AssetTypeId,
                                SettingTypeId = atstLink.SettingTypeId,
                                IsActive = true
                            });
                        }
                    }

                    // update db
                    _unitOfWork.CommitTrans();
                    */
                    // display view with message
                    TempData["SuccessMessage"] = "Linked asset types updated.";
                    return RedirectToAction("Details", "SettingType", new { id = vmEditLinkedAssetTypes.SettingTypeId });
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "SettingType");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "SettingType");
            }
        }


    }
}<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.ParentChildRelationshipType;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business;

namespace Financial.WebApplication.Controllers
{
    public class ParentChildRelationshipTypeController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;


        public ParentChildRelationshipTypeController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [ChildActionOnly]
        public ActionResult Index(int relationshipTypeId)
        {
            //transfer dto for id
            var dtoSuppliedRelationshipType = _unitOfWork.RelationshipTypes.Get(relationshipTypeId);

            // transfer db for supplied ParentId
            var dbParentRelationshipTypes = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.IsActive)
                .Where(r => r.ParentRelationshipTypeId == relationshipTypeId)
                .ToList();
            
            // transfer db for supplied ChildId
            var dbChildRelationshipTypes = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.IsActive)
                .Where(r => r.ChildRelationshipTypeId == relationshipTypeId)
                .ToList();

            // tranfer dbParent to vm
            var vmIndex = new List<IndexViewModel>();
            foreach(var dtoParentChildRelationshipType in dbParentRelationshipTypes)
            {
                var dtoParentRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ParentRelationshipTypeId);
                var dtoChildRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ChildRelationshipTypeId);
                vmIndex.Add(new IndexViewModel(dtoParentChildRelationshipType, dtoSuppliedRelationshipType, dtoParentRelationshipType, dtoChildRelationshipType));
            }

            // tranfer dbChild to vm
            foreach (var dtoParentChildRelationshipType in dbChildRelationshipTypes)
            {
                var dtoParentRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ParentRelationshipTypeId);
                var dtoChildRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ChildRelationshipTypeId);
                vmIndex.Add(new IndexViewModel(dtoParentChildRelationshipType, dtoSuppliedRelationshipType, dtoParentRelationshipType, dtoChildRelationshipType));
            }

            // display view
            return PartialView("_Index", vmIndex);
        }

        [HttpGet]
        public ViewResult Create(int relationshipTypeId)
        {
            // transfer dto for id
            var dtoSuppliedRelationshipType = _unitOfWork.RelationshipTypes.Get(relationshipTypeId);

            // transfer db to sli
            List<SelectListItem> sliRelationshipTypes = GetDropDownListForRelationshipTypes(relationshipTypeId, null);

            // transfer levels to sli
            List<SelectListItem> sliRelationshipLevels = GetDropDownListForRelationshipLevels(null);

            // display view
            return View("Create", new CreateViewModel(dtoSuppliedRelationshipType, sliRelationshipLevels, sliRelationshipTypes));
        }

        [HttpPost]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            // validation
            if(!ModelState.IsValid)
            {
                return View("Create", vmCreate);
            }

            // link duplicated?
            var countExistingParentLinks = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.ParentRelationshipTypeId == vmCreate.SuppliedRelationshipTypeId)
                .Where(r => r.ChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedRelationshipType))
                .Count(r => r.IsActive);
            var countExistingChildLinks = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.ChildRelationshipTypeId == vmCreate.SuppliedRelationshipTypeId)
                .Where(r => r.ParentRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedRelationshipType))
                .Count(r => r.IsActive);
            if (countExistingParentLinks > 0 || countExistingChildLinks > 0)
            {
                // update Drop Down Lists for vm
                vmCreate.LinkedRelationshipTypes = GetDropDownListForRelationshipTypes(vmCreate.SuppliedRelationshipTypeId, null);
                vmCreate.RelationshipLevels = GetDropDownListForRelationshipLevels(null);

                // redisplay view
                ViewData["ErrorMessage"] = "Record already exists";
                return View("Create", vmCreate);
            }

            // determine relationship level
            int parentRelationshipType = 0;
            int childRelationshipType = 0;
            if(vmCreate.SelectedRelationshipLevel == "Parent-Child")
            {
                parentRelationshipType = vmCreate.SuppliedRelationshipTypeId;
                childRelationshipType = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedRelationshipType);
            }
            else // Child-Parent
            { 
                parentRelationshipType = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmCreate.SelectedLinkedRelationshipType);
                childRelationshipType = vmCreate.SuppliedRelationshipTypeId;
            }

            // transfer vm to dto
            _unitOfWork.ParentChildRelationshipTypes.Add(new ParentChildRelationshipType()
            {
                ParentRelationshipTypeId = parentRelationshipType,
                ChildRelationshipTypeId = childRelationshipType,
                IsActive = true
            });

            // update db
            _unitOfWork.CommitTrans();

            // display view
            return RedirectToAction("Details", "RelationshipType", new { id = vmCreate.SuppliedRelationshipTypeId });
        }

        [HttpGet]
        public ViewResult Edit(int id, int relationshipTypeId)
        {
            // transfer dto for id
            var dtoSuppliedParentChildRelationshipType = _unitOfWork.ParentChildRelationshipTypes.Get(id);
            var dtoSuppliedRelationshipType = _unitOfWork.RelationshipTypes.Get(relationshipTypeId);

            // transfer levels to sli
            var selectedRelationshipLevelId = dtoSuppliedParentChildRelationshipType.ParentRelationshipTypeId == relationshipTypeId ?
                "Parent-Child" : "Child-Parent";
            List<SelectListItem> sliRelationshipLevels = GetDropDownListForRelationshipLevels(selectedRelationshipLevelId);

            // transfer db to sli
            var selectedRelationshipTypeId = dtoSuppliedParentChildRelationshipType.ParentRelationshipTypeId == relationshipTypeId ? 
                dtoSuppliedParentChildRelationshipType.ChildRelationshipTypeId : 
                dtoSuppliedParentChildRelationshipType.ParentRelationshipTypeId;
            List<SelectListItem> sliRelationshipTypes = GetDropDownListForRelationshipTypes(relationshipTypeId, selectedRelationshipTypeId);

            // display view
            return View("Edit", new EditViewModel(dtoSuppliedParentChildRelationshipType, dtoSuppliedRelationshipType, sliRelationshipLevels, selectedRelationshipLevelId, sliRelationshipTypes, selectedRelationshipTypeId));
        }

        [HttpPost]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            if(!ModelState.IsValid)
            {
                return View("Edit", vmEdit);
            }

            // duplicated relationship?
            var countExistingParentChildRelationship = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.Id != vmEdit.Id)
                .Where(r => r.ParentRelationshipTypeId == vmEdit.RelationshipTypeId)
                .Where(r => r.ChildRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedRelationshipType))
                .Count(r => r.IsActive);
            var countExistingChildParentRelationship = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                .Where(r => r.Id != vmEdit.Id)
                .Where(r => r.ChildRelationshipTypeId == vmEdit.RelationshipTypeId)
                .Where(r => r.ParentRelationshipTypeId == Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedRelationshipType))
                .Count(r => r.IsActive);

            if (countExistingParentChildRelationship > 0 || countExistingChildParentRelationship > 0)
            {
                // update Drop Down Lists for vm
                vmEdit.RelationshipTypes = GetDropDownListForRelationshipTypes(vmEdit.RelationshipTypeId, Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedRelationshipType));
                vmEdit.RelationshipLevels = GetDropDownListForRelationshipLevels(vmEdit.SelectedRelationshipLevel);

                // redisplay view
                ViewData["ErrorMessage"] = "Record already exists";
                return View("Edit", vmEdit);
            }

            // transfer vm to dto
            var dtoParentChildRelationshipType = _unitOfWork.ParentChildRelationshipTypes.Get(vmEdit.Id);
            if(vmEdit.SelectedRelationshipLevel == "Parent-Child")
            {
                dtoParentChildRelationshipType.ParentRelationshipTypeId = vmEdit.RelationshipTypeId;
                dtoParentChildRelationshipType.ChildRelationshipTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedRelationshipType);
            }
            else // Child-Parent
            {
                dtoParentChildRelationshipType.ParentRelationshipTypeId = Business.Utilities.DataTypeUtility.GetIntegerFromString(vmEdit.SelectedRelationshipType);
                dtoParentChildRelationshipType.ChildRelationshipTypeId = vmEdit.RelationshipTypeId; 
            }

            // update db
            _unitOfWork.CommitTrans();

            // display view
            return RedirectToAction("Details", "RelationshipType", new { id = vmEdit.RelationshipTypeId });
        }

        [HttpGet]
        public ViewResult Delete(int id, int relationshipTypeId)
        {
            // transfer values to dto
            var dtoParentChildRelationshipType = _unitOfWork.ParentChildRelationshipTypes.Get(id);
            var dtoRelationshipType = _unitOfWork.RelationshipTypes.Get(relationshipTypeId);
            var dtoParentRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ParentRelationshipTypeId);
            var dtoChildRelationshipType = _unitOfWork.RelationshipTypes.Get(dtoParentChildRelationshipType.ChildRelationshipTypeId);
            
            // display view
            return View("Delete", new DeleteViewModel(dtoParentChildRelationshipType, dtoRelationshipType, dtoParentRelationshipType, dtoChildRelationshipType));
        }

        [HttpPost]
        public ActionResult Delete(DeleteViewModel vmDelete)
        {
            if(!ModelState.IsValid)
            {
                return View("Delete", vmDelete);
            }

            // update dto
            var dtoParentChildRelationshipType = _unitOfWork.ParentChildRelationshipTypes.Get(vmDelete.Id);
            dtoParentChildRelationshipType.IsActive = false;

            // update db
            _unitOfWork.CommitTrans();

            // display view
            return RedirectToAction("Details", "RelationshipType", new { id = vmDelete.RelationshipTypeId });
        }

        private List<SelectListItem> GetDropDownListForRelationshipTypes(int relationshipTypeId, int? selectedId)
        {
            // validate selectedId
            var intSelectedId = 0;
            int.TryParse(selectedId.ToString(), out intSelectedId);

            // transfer db
            var dbRelationshipTypes = _unitOfWork.RelationshipTypes.GetAll()
                .Where(r => r.IsActive)
                .Where(r => r.Id != relationshipTypeId)
                .ToList();

            // transfer db to sli
            var sliRelationshipTypes = new List<SelectListItem>();
            foreach (var dtoRelationshipType in dbRelationshipTypes)
            {
                var countLinkedParentRelationships = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                    .Where(r => r.ParentRelationshipTypeId == relationshipTypeId)
                    .Where(r => r.ChildRelationshipTypeId == dtoRelationshipType.Id)
                    .Where(r => r.ParentRelationshipTypeId != selectedId)
                    .Where(r => r.ChildRelationshipTypeId != selectedId)
                    .Count(r => r.IsActive);
                var countLinkedChildRelationships = _unitOfWork.ParentChildRelationshipTypes.GetAll()
                    .Where(r => r.ChildRelationshipTypeId == relationshipTypeId)
                    .Where(r => r.ParentRelationshipTypeId == dtoRelationshipType.Id)
                    .Where(r => r.ChildRelationshipTypeId != selectedId)
                    .Where(r => r.ParentRelationshipTypeId != selectedId)
                    .Count(r => r.IsActive);

                // add if existing link not found
                if (countLinkedParentRelationships == 0 && countLinkedChildRelationships == 0)
                {
                    sliRelationshipTypes.Add(new SelectListItem()
                    {
                        Value = dtoRelationshipType.Id.ToString(),
                        Selected = dtoRelationshipType.Id == intSelectedId,
                        Text = dtoRelationshipType.Name
                    });
                }
            }

            return sliRelationshipTypes;
        }

        private static List<SelectListItem> GetDropDownListForRelationshipLevels(string selectedValue)
        {
            var sliRelationshipLevels = new List<SelectListItem>();
            sliRelationshipLevels.Add(new SelectListItem()
            {
                Value = "Parent-Child",
                Selected = "Parent-Child" == selectedValue,
                Text = "Parent-Child"
            });
            sliRelationshipLevels.Add(new SelectListItem()
            {
                Value = "Child-Parent",
                Selected = "Child-Parent" == selectedValue,
                Text = "Child-Parent"
            });
            return sliRelationshipLevels;
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountRelationships")]
    public class AssetRelationship : BaseEntity
    {
        [Required]
        [Display(Name = "Parent Asset ID")]
        [Column("ParentAccountId")]
        public int ParentAssetId { get; set; }
        [Required]
        [Display(Name = "Child Asset ID")]
        [Column("ChildAccountId")]
        public int ChildAssetId { get; set; }
        [Required]
        [Display(Name = "AccountTypeRelationshipType ID")]
        public int AssetTypeRelationshipTypeId { get; set; }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class ParentChildRelationshipTypeRepository : Repository<ParentChildRelationshipType>, IParentChildRelationshipTypeRepository
    {
        public ParentChildRelationshipTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("AccountTypes")]
    public class AssetType : BaseEntity
    {
        [Required]
        public string Name { get; set; }



        //public ICollection<Asset> Assets { get; set; }


        public static readonly int IdForCreditCard = 3;
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class SettingTypeRepository : Repository<SettingType>, ISettingTypeRepository
    {
        public SettingTypeRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }




        public IEnumerable<SettingType> GetAllOrderedByName()
        {
            return FinancialDbContext.SettingTypes
                .OrderBy(r => r.Name)
                .ToList();
        }

        public int CountMatching(string name)
        {
            return FinancialDbContext.SettingTypes
                .Count(r => r.Name == name);
        }

        public int CountMatching(int excludeId, string name)
        {
            return FinancialDbContext.SettingTypes
                .Where(r => r.Id != excludeId)
                .Count(r => r.Name == name);
        }


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core.Models
{
    [Table("TransactionTypes")]
    public class TransactionType : BaseEntity
    {
        [Required]
        public string Name { get; set; }




        public ICollection<AssetTransaction> AssetTransactions { get; set; }



        public static readonly int IdForExpense = 1;
        public static readonly int IdForIncome = 2;
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Business.Models.AccountTransaction bmAssetTransaction)
        {
            Id = bmAssetTransaction.AssetTransactionId;
            AssetId = bmAssetTransaction.AssetId;
            AssetName = bmAssetTransaction.AssetName;
            AssetTypeName = bmAssetTransaction.AssetTypeName;
            DueDate = bmAssetTransaction.DueDate;
            ClearDate = bmAssetTransaction.ClearDate;
            CheckNumber = bmAssetTransaction.CheckNumber;
            Amount = bmAssetTransaction.Amount;
            Note = bmAssetTransaction.Note;
            //TransactionTypes = bmAssetTransaction.TransactionTypeSelectList;
            //SelectedTransactionTypeId = bmAssetTransaction.SelectedTransactionTypeId;
            //TransactionCategories = bmAssetTransaction.TransactionCategorySelectList;
            SelectedTransactionCategoryId = bmAssetTransaction.SelectedTransactionCategoryId;
        }


        public int Id { get; set; }
        public int AssetId { get; set; }
        [Display(Name = "Asset Name")]
        public string AssetName { get; set; }
        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }
        [Display(Name = "Check Number")]
        public string CheckNumber { get; set; }
        [Required]
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime ClearDate { get; set; }
        [Required]
        public decimal Amount { get; set; }
        public string Note { get; set; }
        [Required]
        [Display(Name = "Type")]
        public string SelectedTransactionTypeId { get; set; }
        public IEnumerable<SelectListItem> TransactionTypes { get; set; }
        [Required]
        [Display(Name = "Category")]
        public string SelectedTransactionCategoryId { get; set; }
        public IEnumerable<SelectListItem> TransactionCategories { get; set; }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TransactionCategory = Financial.Core.Models.TransactionCategory;

namespace Financial.Data.Repositories
{
    public class TransactionCategoryRepository : Repository<TransactionCategory>, ITransactionCategoryRepository
    {
        public TransactionCategoryRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }



        public IEnumerable<TransactionCategory> GetAllActiveOrderedByName()
        {
            return FinancialDbContext.TransactionCategories
                .Where(r => r.IsActive)
                .OrderBy(r => r.Name);
        }
    }
}
<file_sep>﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Financial.Business.Models;
using Financial.Business.ServiceInterfaces;
using Financial.Business.Utilities;
using Financial.Core.Models;
using Financial.Data;

namespace Financial.Business.Services
{
    public class AccountService : IAccountService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAccountSettingService _assetSettingService;

        public AccountService()
        {
            _unitOfWork = new UnitOfWork();
        }

        public AccountService(
            IUnitOfWork unitOfWork, 
            IAccountSettingService assetSettingService)
        {
            _unitOfWork = unitOfWork;
            _assetSettingService = assetSettingService;
        }




        public List<Account> GetListOfAccounts()
        {
            // create list object to return
            var bmAccountList = new List<Account>();

            // get assets from db
            var dbAssetList = _unitOfWork.Assets.GetAllActiveOrderedByName();
            foreach (var dbAsset in dbAssetList)
            {
                // get asset type from db
                var dbAssetType = _unitOfWork.AssetTypes.Get(dbAsset.AssetTypeId);
                if (dbAssetType == null)
                    return new List<Account>();

                // add additional information to asset name
                if (dbAssetType.Id == AssetType.IdForCreditCard)
                {
                    var dbAssetSetting = _unitOfWork.AssetSettings.GetActive(dbAsset.Id, Core.Models.SettingType.IdForAccountNumber);
                    if(dbAssetSetting != null)
                        dbAsset.Name = AccountUtility.FormatAccountName(dbAsset.Name, dbAssetType.Id, dbAssetSetting.Value);
                }

                // transfer dto to bm
                bmAccountList.Add(new Account(dbAsset, dbAssetType));
            }

            return bmAccountList;
        }


        public string GetAccountIdentificationInformation(Account bmAccount)
        {
            if (bmAccount == null)
                return string.Empty;

            if (bmAccount.AssetTypeId == AssetType.IdForCreditCard)
            {
                var dtoAssetSetting = _unitOfWork.AssetSettings.GetActive(bmAccount.AssetId, Core.Models.SettingType.IdForAccountNumber);
                if (dtoAssetSetting == null)
                    return string.Empty;

                return $" ({dtoAssetSetting.Value})";
            }

            return string.Empty;
        }

        public List<SelectListItem> GetSelectListOfAccounts(int? selectedId = null)
        {
            // transfer values from db
            var dbAssets = _unitOfWork.Assets.GetAllActiveOrderedByName();

            // transfer dto to sli
            var sliAssets = new List<SelectListItem>();
            foreach (var dtoAsset in dbAssets)
            {
                // add credit card account number to name
                var assetName = dtoAsset.Name;
                var assetNameInformation = _assetSettingService.GetAccountIdentificationInformation(new Account(dtoAsset));

                sliAssets.Add(new SelectListItem()
                {
                    Value = dtoAsset.Id.ToString(),
                    Text = string.Format("{0}{1}", assetName, assetNameInformation),
                    Selected = dtoAsset.Id.ToString() == selectedId.ToString(),
                });
            }
            return sliAssets;
        }


    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IParentChildRelationshipTypeRepository : IRepository<ParentChildRelationshipType>
    {
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface IAssetSettingRepository : IRepository<AssetSetting>
    {
        AssetSetting GetActive(int assetId, int settingTypeId);
        IEnumerable<AssetSetting> GetAllActiveForAsset(int assetId);
        IEnumerable<AssetSetting> GetAllActiveForSettingType(int settingTypeId);
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeAssetTypesRelationshipTypes
    {
        public static IEnumerable<AssetTypeRelationshipType> InitialFakeAssetTypesRelationshipTypes()
        {
            yield return new AssetTypeRelationshipType() { Id = 1, ParentAssetTypeId = 2, ChildAssetTypeId = 4, ParentChildRelationshipTypeId = 5, IsActive = true };
            yield return new AssetTypeRelationshipType() { Id = 2, ParentAssetTypeId = 4, ChildAssetTypeId = 5, ParentChildRelationshipTypeId = 1, IsActive = true };
            yield return new AssetTypeRelationshipType() { Id = 3, ParentAssetTypeId = 3, ChildAssetTypeId = 3, ParentChildRelationshipTypeId = 3, IsActive = false };
            yield return new AssetTypeRelationshipType() { Id = 4, ParentAssetTypeId = 5, ChildAssetTypeId = 1, ParentChildRelationshipTypeId = 2, IsActive = true };
            yield return new AssetTypeRelationshipType() { Id = 5, ParentAssetTypeId = 1, ChildAssetTypeId = 2, ParentChildRelationshipTypeId = 4, IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Utilities
{
    public class TransactionUtility
    {
        public static decimal FormatAmount(int TransactionTypeId, decimal amount)
        {
            if(TransactionTypeId == TransactionType.IdForExpense)
                return amount * -1;

            return amount;
        }

        /*
        public static decimal CalculateTransaction(decimal initialBalance, decimal transactionAmount, string transactionType)
        {
            if (transactionType == "Income")
            {
                return initialBalance + transactionAmount;
            }
            else if (transactionType == "Expense")
            {
                return initialBalance - transactionAmount;
            }

            return initialBalance;
        }

        public static string FormatCheckNumber(string checkNumber)
        {
            return string.IsNullOrWhiteSpace(checkNumber)
                ? string.Empty
                : checkNumber;
        }

        public static string FormatTransactionNote(string note)
        {
            return string.IsNullOrWhiteSpace(note)
                ? string.Empty
                : note;
        }
        */
    }
}
<file_sep>﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Financial.Business.Services;
using Financial.Business.Tests.Fakes.Repositories;

namespace Financial.Business.Tests.Services
{
    public class AssetTypeServiceTestsBase : ServiceTestsBase
    {
        public AssetTypeServiceTestsBase()
        {
            _service = new AccountTypeService(_unitOfWork);
        }

        protected AccountTypeService _service;
    }


    [TestClass()]
    public class AssetTypeServiceTests : AssetTypeServiceTestsBase
    {
        [TestMethod()]
        public void GetAssetType_WhenProvidedValidInput_ReturnValue_Test()
        {
            // Assemble
            var assetTypeId = 1;

            // Act
            var result = _service.GetAssetType(assetTypeId);

            // Assert
            Assert.IsInstanceOfType(result, typeof(Business.Models.AccountType), "Result Type");
            Assert.AreEqual(assetTypeId, result.AssetTypeId, "Asset Type Id");
        }

        [TestMethod()]
        public void GetAssetType_WhenProvidedInvalidAssetTypeId_ReturnValue_Test()
        {
            // Assemble
            var assetTypeId = 0;

            // Act
            var result = _service.GetAssetType(assetTypeId);

            // Assert
            Assert.IsNull(result, "Result");
        }

        [TestMethod()]
        public void GetAssetType_WhenProvidedValidInputIsNotActive_ReturnValue_Test()
        {
            // Assemble
            var _fakeAssetTypes = new List<Core.Models.AssetType>() {
                new Core.Models.AssetType() { Id = 10, Name = "Name 1", IsActive = false }
            };
            _unitOfWork.AssetTypes = new InMemoryAssetTypeRepository(_fakeAssetTypes);
            var service = new AccountTypeService(_unitOfWork);

            // Act
            var result = _service.GetAssetType(_fakeAssetTypes[0].Id);

            // Assert
            Assert.IsNull(result, "Result");
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.Account
{
    public class DeleteViewModel
    {
        public DeleteViewModel() { }

        public DeleteViewModel(Core.Models.Asset dtoAsset, Core.Models.AssetType dtoAssetType)
        {
            Id = dtoAsset.Id;
            AssetName = dtoAsset.Name;
            AssetTypeName = dtoAssetType.Name;
        }


        public int Id { get; set; }
        [Display(Name = "Name")]
        public string AssetName { get; set; }
        [Display(Name = "Type")]
        public string AssetTypeName { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType
{
    public class CreateViewModel
    {
        public CreateViewModel() { }

        public CreateViewModel(Core.Models.AssetType dtoSuppliedAssetType, 
            List<SelectListItem> sliRelationshipLevels, List<SelectListItem> sliLinkAssetTypes,
            string selectedRelationshipLevel, string selectedLinkedAssetType)
        {
            SuppliedAssetTypeId = dtoSuppliedAssetType.Id;
            SuppliedAssetTypeName = dtoSuppliedAssetType.Name;
            RelationshipLevels = sliRelationshipLevels;
            SelectedRelationshipLevel = selectedRelationshipLevel;
            LinkAssetTypes = sliLinkAssetTypes;
            SelectedLinkedAssetTypeId = selectedLinkedAssetType;
        }


        public int SuppliedAssetTypeId { get; set; }
        [Display(Name = "Asset Type")]
        public string SuppliedAssetTypeName { get; set; }

        [Required]
        [Display(Name = "Relationship Level")]
        public string SelectedRelationshipLevel { get; set; }
        public IEnumerable<SelectListItem> RelationshipLevels { get; set; }


        [Required]
        [Display(Name = "Relationship Type")]
        public string SelectedParentChildRelationshipTypeId { get; set; }
        public IEnumerable<SelectListItem> ParentChildRelationshipTypes { get; set; }

        [Required]
        [Display(Name = "Link Asset Type")]
        public string SelectedLinkedAssetTypeId { get; set; }
        public IEnumerable<SelectListItem> LinkAssetTypes { get; set; }


    }
}
<file_sep>﻿using Financial.Business;
using Financial.Business.ServiceInterfaces;
using Financial.Business.Utilities;
using Financial.Core;
using Financial.Core.Models;
using Financial.Data;
using Financial.WebApplication.Models.ViewModels.AccountTransaction;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Financial.Business.Models;

namespace Financial.WebApplication.Controllers
{
    public class AccountTransactionController : BaseController
    {
        private IBusinessService _businessService;

        public AccountTransactionController(IBusinessService businessService)
            : base()
        {
            _businessService = businessService;
        }

        [HttpGet]
        public ViewResult Index()
        {
            try
            {
                if (TempData["ErrorMessage"] != null)
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                if (TempData["SuccessMessage"] != null)
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];

                // transfer bm to vm
                var vmIndex = _businessService.AccountTransactionService.GetListOfActiveTransactions()
                    .OrderByDescending(r => r.DueDate)
                    .Select(r => new IndexViewModel(r))
                    .ToList();

                return View("Index", vmIndex);
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return View("Index", new List<IndexViewModel>());
            }
        }

        [HttpGet]
        public ActionResult Create(int? assetId)
        {
            try
            {
                var bmAccount = _businessService.AccountTransactionService.GetAccountForTransaction(assetId);
                var sliAccounts = _businessService.AccountTransactionService.GetAccountSelectList(assetId.ToString());
                var sliTransactionTypes = _businessService.AccountTransactionService.GetTransactionTypeSelectList(null);
                var sliTransactionCategory = _businessService.AccountTransactionService.GetTransactionCategorySelectList(null);

                /*
                // get bm
                var bmAssetTransaction = _businessService.AccountTransactionService.GetTransactionOptions(assetId);
                if (bmAssetTransaction == null)
                {
                    TempData["ErrorMessage"] = "Unable to create record. Try again.";
                    return RedirectToAction("Index", "AccountTransaction");
                }

                // transfer bm to vm
                var vmCreate = new CreateViewModel(bmAssetTransaction);
                */
                return View("Create", new CreateViewModel(sliAccounts, sliTransactionTypes, sliTransactionCategory));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    TempData["ErrorMessage"] = "Problem creating record. Try again.";
                    return RedirectToAction("Index", "AccountTransaction");
                }

                // transfer vm to bm
                var bmAssetTransaction = new Business.Models.AccountTransaction()
                {
                    AssetId = DataTypeUtility.GetIntegerFromString(vmCreate.SelectedAccountId),
                    TransactionTypeId = DataTypeUtility.GetIntegerFromString(vmCreate.SelectedTransactionTypeId),
                    TransactionCategoryId = DataTypeUtility.GetIntegerFromString(vmCreate.SelectedTransactionCategoryId),
                    CheckNumber = vmCreate.CheckNumber,
                    DueDate = Convert.ToDateTime(vmCreate.DueDate),
                    ClearDate = Convert.ToDateTime(vmCreate.ClearDate),
                    Amount = vmCreate.Amount,
                    Note = vmCreate.Note,
                };

                // update db
                if (!_businessService.AccountTransactionService.AddTransaction(bmAssetTransaction))
                {
                    //bmAssetTransaction = _businessService.AccountTransactionService.GetTransactionOptions(vmCreate.AssetId);
                    //vmCreate.Assets = bmAssetTransaction.AssetSelectList;
                    //vmCreate.TransactionTypes = bmAssetTransaction.TransactionTypeSelectList;
                    //vmCreate.TransactionCategories= bmAssetTransaction.TransactionCategorySelectList;
                    ViewData["ErrorMessage"] = "Problem creating record";
                    return View("Create", vmCreate);
                }

                TempData["SuccessMessage"] = "Record created";
                return RedirectToAction("Details", "Account", new { Id = vmCreate.AssetId });
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            try
            {
                // get bm
                var bmAssetTransaction = _businessService.AccountTransactionService.GetTransactionToEdit(id);
                if (bmAssetTransaction == null)
                {
                    TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                    return RedirectToAction("Index", "AccountTransaction");
                }

                return View("Edit", new EditViewModel(bmAssetTransaction));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            try
            {
                if(!ModelState.IsValid)
                {
                    TempData["ErrorMessage"] = "Problem editing record. Try again.";
                    return RedirectToAction("Index", "AccountTransaction");
                }

                // transfer vm to bm
                var bmAssetTransaction = new Business.Models.AccountTransaction()
                {
                    AssetTransactionId = vmEdit.Id,
                    AssetId = vmEdit.AssetId,
                    TransactionTypeId = DataTypeUtility.GetIntegerFromString(vmEdit.SelectedTransactionTypeId),
                    TransactionCategoryId = DataTypeUtility.GetIntegerFromString(vmEdit.SelectedTransactionCategoryId),
                    CheckNumber = vmEdit.CheckNumber,
                    DueDate = Convert.ToDateTime(vmEdit.DueDate),
                    ClearDate = Convert.ToDateTime(vmEdit.ClearDate),
                    Amount = vmEdit.Amount,
                    Note = vmEdit.Note,
                };

                // update db
                if (!_businessService.AccountTransactionService.UpdateTransaction(bmAssetTransaction))
                {
                    ViewData["ErrorMessage"] = "Problem updating record";
                    return View("Edit", vmEdit);
                }

                TempData["SuccessMessage"] = "Record updated";
                return RedirectToAction("Details", "Account", new { id = vmEdit.AssetId });
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            try
            {
                // get bm
                var bmAssetTransaction = _businessService.AccountTransactionService.GetTransactionToDelete(id);

                // tranfer bm to vm
                return View("Delete", new DeleteViewModel(bmAssetTransaction));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(DeleteViewModel vmDelete)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    TempData["ErrorMessage"] = "Problem deleting record. Try again.";
                    return RedirectToAction("Index", "AccountTransaction");
                }

                // update db
                if (!_businessService.AccountTransactionService.DeleteTransaction(vmDelete.Id))
                {
                    ViewData["ErrorMessage"] = "Problem deleting record";
                    return View("Delete", vmDelete);
                }

                TempData["SuccessMessage"] = "Record deleted";
                return RedirectToAction("Index", "AccountTransaction");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }




        [HttpGet]
        public ActionResult DisplayForAsset(int assetId)
        {
            try
            {
                /*
                // transfer assetId from db
                var dbAssetTransactions = _unitOfWork.AssetTransactions.GetAllActiveByDescendingDueDate(assetId);

                // transfer dto to vm
                var vmDisplayForAsset = new List<DisplayForAssetViewModel>();
                foreach(var dtoAssetTransaction in dbAssetTransactions)
                {
                    var dtoTransactionCategory = _unitOfWork.TransactionCategories.Get(dtoAssetTransaction.TransactionCategoryId);

                    // is Expense?
                    if(dtoAssetTransaction.TransactionTypeId == 1)
                    {
                        // update to "-0.00"
                        dtoAssetTransaction.Amount = dtoAssetTransaction.Amount * -1;
                    }

                    // format date
                    string clearDate = DataTypeUtility.GetDateValidatedToShortDateString(dtoAssetTransaction.ClearDate);

                    // transfer to vm
                    vmDisplayForAsset.Add(new DisplayForAssetViewModel(dtoAssetTransaction, clearDate, dtoTransactionCategory));
                }
                */
                // display view
                return PartialView("_DisplayForAsset", new List<DisplayForAssetViewModel>());
            }
            catch (Exception)
            {
                ViewData["ErrorMessage"] = "Encountered problem";
                return PartialView("_DisplayForAsset", new List<DisplayForAssetViewModel>());
            }
        }

        /*
         * TODO: implement service
        [HttpGet]
        public ActionResult SelectAssetToCreate()
        {
            try
            {
                // transfer dto to sli
                var sliAssets = _businessService.AssetService.GetSelectListOfAssets(null);

                // display view
                return View("SelectAssetToCreate", new SelectAssetToCreateViewModel(sliAssets));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AssetTransaction");
            }
        }
        */

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SelectAssetToCreate(SelectAssetToCreateViewModel vmSelectedAssetToCreate)
        {
            try
            {
                // get & validate selected id
                var id = DataTypeUtility.GetIntegerFromString(vmSelectedAssetToCreate.SelectedAssetId);
                if (id > 0)
                {
                    // display view
                    return RedirectToAction("Create", "AccountTransaction", new { assetId = id });
                }
                TempData["ErrorMessage"] = "Value must be selected.";
                return RedirectToAction("SelectAssetToCreate", "AccountTransaction");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }

        /*
         * TODO: implement service
        [HttpGet]
        public ActionResult EditAsset(int id, int assetId)
        {
            try
            {
                // transfer id to dto
                var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(id);
                var dtoAsset = _unitOfWork.Assets.Get(assetId);
                if (dtoAssetTransaction != null && dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);
                    var dtoTransactionType = _unitOfWork.TransactionTypes.Get(dtoAssetTransaction.TransactionTypeId);
                    var dtoTransactionCategory = _unitOfWork.TransactionCategories.Get(dtoAssetTransaction.TransactionCategoryId);
                    if (dtoAssetType != null && dtoTransactionType != null && dtoTransactionCategory != null)
                    {
                        // validate values to display
                        dtoAssetTransaction.CheckNumber = TransactionUtility.FormatCheckNumber(dtoAssetTransaction.CheckNumber);
                        dtoAssetTransaction.Note = TransactionUtility.FormatTransactionNote(dtoAssetTransaction.Note);

                        // transfer dto to sli
                        var sliAssets = _businessService.AssetService.GetSelectListOfAssets(dtoAsset.Id.ToString());

                        // transfer to vm and display view
                        return View("EditAsset", new EditAssetViewModel(dtoAssetTransaction, sliAssets, dtoAsset.Id.ToString(), dtoAssetType, dtoTransactionType.Name, dtoTransactionCategory.Name));
                    }
                    TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                    return RedirectToAction("Edit", "AssetTransaction", new { id = id });
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "AssetTransaction");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AssetTransaction");
            }
        }
        */

        [HttpPost]
        public ActionResult EditAsset(EditAssetViewModel vmEditAsset)
        {
            try
            { 
                /*
                if (ModelState.IsValid)
                {
                    // transfer vm to dto
                    var dtoAssetTransaction = _unitOfWork.AssetTransactions.Get(vmEditAsset.Id);
                    if (dtoAssetTransaction != null)
                    {
                        dtoAssetTransaction.AssetId = DataTypeUtility.GetIntegerFromString(vmEditAsset.SelectedAssetId);

                        // update db
                        _unitOfWork.CommitTrans();

                        // display view
                        TempData["SuccessMessage"] = "Asset Name updated";
                        return RedirectToAction("Edit", "AccountTransaction", new { id = vmEditAsset.Id });
                    }
                }
                */
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "AccountTransaction");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered Problem";
                return RedirectToAction("Index", "AccountTransaction");
            }
        }


    }
}<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class AssetTransactionRepository : Repository<AssetTransaction>, IAssetTransactionRepository
    {
        public AssetTransactionRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }



        public IEnumerable<AssetTransaction> GetAllActiveByDueDate()
        {
            return FinancialDbContext.AssetTransactions
                .Include(r => r.Asset)
                .Include(r => r.Asset.AssetType)
                .Include(r => r.TransactionType)
                .Where(r => r.IsActive)
                .OrderBy(r => r.DueDate)
                .ToList();
        }

        public IEnumerable<AssetTransaction> GetAllActiveByDescendingDueDate(int assetId)
        {
            return FinancialDbContext.AssetTransactions
                .Where(r => r.IsActive)
                .Where(r => r.AssetId == assetId)
                .OrderByDescending(r => r.DueDate)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetSetting
{
    public class CreateLinkedSettingTypesViewModel
    {
        public CreateLinkedSettingTypesViewModel() { }

        public CreateLinkedSettingTypesViewModel(Core.Models.Asset dtoAsset,
            Core.Models.AssetType dtoAssetType,List<CreateViewModel> vmCreate)
        {
            AssetId = dtoAsset.Id;
            AssetName = dtoAsset.Name;
            AssetTypeName = dtoAssetType.Name;
            CreateViewModels = vmCreate;
        }

        public int AssetId { get; set; }
        [Display(Name = "Name")]
        public string AssetName { get; set; }
        [Display(Name = "Type")]
        public string AssetTypeName { get; set; }
        public List<CreateViewModel> CreateViewModels { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.ParentChildRelationshipType
{
    public class IndexViewModel
    {
        public IndexViewModel() { }

        public IndexViewModel(Core.Models.ParentChildRelationshipType dtoParentChildRelationshipType, Core.Models.RelationshipType dtoSuppliedRelationshipType,
            Core.Models.RelationshipType dtoParentRelationshipType, Core.Models.RelationshipType dtoChildRelationshipType)
        {
            Id = dtoParentChildRelationshipType.Id;
            RelationshipTypeId = dtoSuppliedRelationshipType.Id;
            ParentRelationshipTypeName = dtoParentRelationshipType.Name;
            ChildRelationshipTypeName = dtoChildRelationshipType.Name;
        }

        public int Id { get; set; }
        public int RelationshipTypeId { get; set; }
        [Display(Name = "Parent")]
        public string ParentRelationshipTypeName { get; set; }
        [Display(Name = "Child")]
        public string ChildRelationshipTypeName { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Models
{
    public class AttributeType
    {
        public AttributeType() { }
        public AttributeType(Core.Models.SettingType dtoSettingType)
        {
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
        }
        public AttributeType(Core.Models.SettingType dtoSettingType, 
            Core.Models.AssetTypeSettingType dtoAssetTypeSettingType)
        {
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            AssetTypeSettingTypeId = dtoAssetTypeSettingType.Id;
        }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }
        public int AssetTypeSettingTypeId { get; set; }

    }
}
<file_sep>﻿using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryRelationshipTypeRepository : InMemoryRepository<RelationshipType>, IRelationshipTypeRepository
    {
        private List<RelationshipType> _entities = null;

        public InMemoryRelationshipTypeRepository(IEnumerable<RelationshipType> entities)
            : base(entities)
        {
            _entities = entities as List<RelationshipType>;
        }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public static class FakeAssetSettings
    {
        public static IEnumerable<AssetSetting> InitialFakeAssetSettings()
        {
            yield return new AssetSetting() { Id = 1, AssetId = 2, SettingTypeId = 4, Value = "AssetSetting1", IsActive = true };
            yield return new AssetSetting() { Id = 2, AssetId = 1, SettingTypeId = 4, Value = "AssetSetting2", IsActive = true };
            yield return new AssetSetting() { Id = 3, AssetId = 1, SettingTypeId = 2, Value = "AssetSetting3", IsActive = false };
            yield return new AssetSetting() { Id = 4, AssetId = 5, SettingTypeId = 2, Value = "AssetSetting4", IsActive = true };
            yield return new AssetSetting() { Id = 5, AssetId = 4, SettingTypeId = 1, Value = "AssetSetting5", IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetTypeRelationshipType
{
    public class IndexViewModel
    {
        public IndexViewModel() { }

        public IndexViewModel(Core.Models.AssetTypeRelationshipType dtoAssetTypeRelationshipType,
                              Core.Models.AssetType dtoSuppliedAssetType,
                              Core.Models.AssetType dtoLinkedAssetType,
                              Core.Models.RelationshipType dtoRelationshipType)
        {
            Id = dtoAssetTypeRelationshipType.Id;
            SuppliedAssetTypeId = dtoSuppliedAssetType.Id;
            SuppliedAssetTypeName = dtoSuppliedAssetType.Name;
            LinkedAssetTypeName = dtoLinkedAssetType.Name;
            RelationshipTypeName = dtoRelationshipType.Name;
        }

        public IndexViewModel(Core.Models.AssetTypeRelationshipType dtoAssetTypeRelationshipType,
                      Core.Models.AssetType dtoParentAssetType,
                      Core.Models.AssetType dtoChildAssetType,
                      Core.Models.RelationshipType dtoParentRelationshipType,
                      Core.Models.RelationshipType dtoChildRelationshipType)
        {
            Id = dtoAssetTypeRelationshipType.Id;
            ParentAssetTypeName = dtoParentAssetType.Name;
            ChildAssetTypeName = dtoChildAssetType.Name;
            ParentRelationshipTypeName = dtoParentRelationshipType.Name;
            ChildRelationshipTypeName = dtoChildRelationshipType.Name;
        }


        public int Id { get; set; }
        public int SuppliedAssetTypeId { get; set; }
        public string SuppliedAssetTypeName { get; set; }
        [Display(Name = "Linked Asset Type")]
        public string LinkedAssetTypeName { get; set; }
        [Display(Name = "Relationship Type")]
        public string RelationshipTypeName { get; set; }

        [Display(Name = "Parent")]
        public string ParentAssetTypeName { get; set; }
        [Display(Name = "Child")]
        public string ChildAssetTypeName { get; set; }
        [Display(Name = "Parent-Child")]
        public string ParentRelationshipTypeName { get; set; }
        [Display(Name = "Child-Parent")]
        public string ChildRelationshipTypeName { get; set; }
    }
}
<file_sep>﻿using Financial.Business;
using Financial.Business.Utilities;
using Financial.Core;
using Financial.Core.Models;
using Financial.WebApplication.Models.ViewModels.Account;
using Financial.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Financial.WebApplication.Controllers
{
    public class AccountController : BaseController
    {
        private IUnitOfWork _unitOfWork;
        private IBusinessService _businessService;

        public AccountController(IUnitOfWork unitOfWork, IBusinessService businessService)
            : base()
        {
            _unitOfWork = unitOfWork;
            _businessService = businessService;
        }

        [HttpGet]
        public ViewResult Index()
        {
            try
            {
                // get messages from other controllers to display in view
                if (TempData["SuccessMessage"] != null)
                {
                    ViewData["SuccessMessage"] = TempData["SuccessMessage"];
                }
                if (TempData["ErrorMessage"] != null)
                {
                    ViewData["ErrorMessage"] = TempData["ErrorMessage"];
                }

                // transfer bm to vm
                var vmIndexList = _businessService.AccountService.GetListOfAccounts()
                        .OrderBy(r => r.AssetName)
                        .Select(r => new IndexViewModel(r))
                        .ToList();
 
                // display view
                return View("Index", vmIndexList);
            }
            catch (Exception e)
            {
                // todo: setup logging

                TempData["ErrorMessage"] = "Encountered problem";
                return View("Index", new List<IndexViewModel>());
            }
        }

        [HttpGet]
        public ActionResult Create()
        {
            try
            {
                // transfer dto to sli
                var sliAssetTypes = _businessService.AccountTypeService.GetAssetTypesDropDownList(null);

                // display view
                return View("Create", new CreateViewModel(sliAssetTypes));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateViewModel vmCreate)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // transfer vm to dto
                    var dtoAsset = new Asset()
                    {
                        AssetTypeId = DataTypeUtility.GetIntegerFromString(vmCreate.SelectedAssetTypeId),
                        Name = vmCreate.AssetName,
                        IsActive = true
                    };
                    _unitOfWork.Assets.Add(dtoAsset);

                    // update db
                    _unitOfWork.CommitTrans();

                    // display view
                    TempData["SuccessMessage"] = "Asset Created";
                    return RedirectToAction("Create", "AssetSetting", new { assetId = dtoAsset.Id });
                }
                TempData["ErrorMessage"] = "Unable to create record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            try
            { 
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(id);
                if (dtoAsset != null)
                {
                    var sliAssetTypes = _businessService.AccountTypeService.GetAssetTypesDropDownList(dtoAsset.AssetTypeId);

                    // display view
                    return View("Edit", new EditViewModel(dtoAsset, sliAssetTypes));
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditViewModel vmEdit)
        {
            try
            { 
                // transfer vm to dto
                var dtoAsset = _unitOfWork.Assets.Get(vmEdit.Id);
                if (dtoAsset != null)
                {
                    dtoAsset.Name = vmEdit.Name;
                    dtoAsset.AssetTypeId = DataTypeUtility.GetIntegerFromString(vmEdit.SelectedAssetTypeId);

                    // update db
                    _unitOfWork.CommitTrans();

                    // display view with message
                    TempData["SuccessMessage"] = "Record updated.";
                    return RedirectToAction("Details", "Asset", new { id = vmEdit.Id });
                }
                TempData["ErrorMessage"] = "Unable to edit record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        } 

        [HttpGet]
        public ActionResult Details(int id)
        {
            // get messages from other controllers to display in view
            if (TempData["SuccessMessage"] != null)
            {
                ViewData["SuccessMessage"] = TempData["SuccessMessage"];
            }

            try
            { 
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(id);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);

                    // display view with message
                    return View("Details", new DetailsViewModel(dtoAsset, dtoAssetType));
                }
                TempData["ErrorMessage"] = "Unable to display record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            try
            { 
                // transfer id to dto
                var dtoAsset = _unitOfWork.Assets.Get(id);
                if (dtoAsset != null)
                {
                    var dtoAssetType = _unitOfWork.AssetTypes.Get(dtoAsset.AssetTypeId);

                    // display view
                    return View("Delete", new DeleteViewModel(dtoAsset, dtoAssetType));
                }
                TempData["ErrorMessage"] = "Unable to delete record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(DeleteViewModel vmDelete)
        {
            try
            { 
                // transfer vm to dto
                var dtoAsset = _unitOfWork.Assets.Get(vmDelete.Id);
                if (dtoAsset != null)
                {
                    dtoAsset.IsActive = false;

                    // update db
                    _unitOfWork.CommitTrans();

                    // display view with message
                    TempData["SuccessMessage"] = "Record Deleted";
                    return RedirectToAction("Index", "Asset");
                }
                TempData["ErrorMessage"] = "Unable to delete record. Try again.";
                return RedirectToAction("Index", "Asset");
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Encountered problem";
                return RedirectToAction("Index", "Asset");
            }
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NSubstitute;
using System.Data.Entity.Infrastructure;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using Moq.Language.Flow;
using Moq.Language;
using Moq;

namespace Financial.Tests.Mocks
{
    public static class MockDbSet
    {
        public static DbSet<T> Create<T>(IEnumerable<T> data = null) where T : class
        {
            // create a mock DbSet exposing both DbSet and IQueryable interfaces for setup
            var mockDbSet = Substitute.For<DbSet<T>, IQueryable<T>>();

            if (data != null)
            {
                // convert list to queryable
                var qData = data.AsQueryable();

                // setup all IQueryable methods using what you have from "data"
                ((IQueryable<T>)mockDbSet).Provider.Returns(qData.Provider);
                ((IQueryable<T>)mockDbSet).Expression.Returns(qData.Expression);
                ((IQueryable<T>)mockDbSet).ElementType.Returns(qData.ElementType);
                ((IQueryable<T>)mockDbSet).GetEnumerator().Returns(qData.GetEnumerator());
            }

            // bypass include
            mockDbSet.Include(Arg.Any<string>())
                .Returns(mockDbSet);

            return mockDbSet;
        }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Data.RepositoryInterfaces;
using Financial.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly FinancialDbContext _context;
        private bool _trans;

        public UnitOfWork()
        {
            _context = new FinancialDbContext();
            SetRepositories();
        }

        public UnitOfWork(FinancialDbContext context)
        {
            _context = context;
            SetRepositories();
        }

        private void SetRepositories()
        {
            AssetSettings = new AssetSettingRepository(_context);
            AssetRelationships = new AssetRelationshipRepository(_context);
            Assets = new AssetRepository(_context);
            AssetTransactions = new AssetTransactionRepository(_context);
            AssetTypeSettingTypes = new AssetTypeSettingTypeRepository(_context);
            AssetTypeRelationshipTypes = new AssetTypeRelationshipTypeRepository(_context);
            AssetTypes = new AssetTypeRepository(_context);
            ParentChildRelationshipTypes = new ParentChildRelationshipTypeRepository(_context);
            RelationshipTypes = new RelationshipTypeRepository(_context);
            SettingTypes = new SettingTypeRepository(_context);
            TransactionCategories = new TransactionCategoryRepository(_context);
            TransactionDescriptions = new TransactionDescriptionRepository(_context);
            TransactionTypes = new TransactionTypeRepository(_context);
        }

        public IAssetSettingRepository AssetSettings { get; private set; }
        public IAssetRelationshipRepository AssetRelationships { get; private set; }
        public IAssetRepository Assets { get; private set; }
        public IAssetTransactionRepository AssetTransactions { get; private set; }
        public IAssetTypeSettingTypeRepository AssetTypeSettingTypes { get; private set; }
        public IAssetTypeRelationshipTypeRepository AssetTypeRelationshipTypes { get; private set; }
        public IAssetTypeRepository AssetTypes { get; private set; }
        public IParentChildRelationshipTypeRepository ParentChildRelationshipTypes { get; set; }
        public IRelationshipTypeRepository RelationshipTypes { get; private set; }
        public ISettingTypeRepository SettingTypes { get; private set; }
        public ITransactionCategoryRepository TransactionCategories { get; private set; }
        public ITransactionDescriptionRepository TransactionDescriptions { get; private set; }
        public ITransactionTypeRepository TransactionTypes { get; private set; }

        public void BeginTrans()
        {
            _trans = true;
        }
        public void CommitTrans()
        {
            _trans = false;
            Complete();
        }
        public void RollBackTrans()
        {
            _trans = false;
        }
        public void Complete()
        {
            if(!_trans)
            {
                _context.SaveChanges();
            }
        }
        public void Dispose()
        {
            _context.Dispose();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;

namespace Financial.Business.Tests.Fakes.Repositories
{
    public class InMemoryAssetTypeRepository : InMemoryRepository<AssetType>, IAssetTypeRepository
    {
        private List<AssetType> _entities = null;

        public InMemoryAssetTypeRepository(IEnumerable<AssetType> entities)
            : base(entities)
        {
            _entities = entities as List<AssetType>;
        }




        public int CountMatching(string name)
        {
            return _entities
                .Count(r => r.Name == name);
        }

        public int CountMatching(int excludeId, string name)
        {
            return _entities
                .Where(r => r.Id != excludeId)
                .Count(r => r.Name == name);
        }

        public IEnumerable<AssetType> GetAllActiveOrderedByName()
        {
            throw new NotImplementedException();
        }

        public IEnumerable<AssetType> GetAllOrderedByName()
        {
            return _entities
                .OrderBy(r => r.Name)
                .ToList();
        }
    }
}
<file_sep>﻿using Financial.Core;
using Financial.Core.Models;
using Financial.Data.RepositoryInterfaces;
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.Repositories
{
    public class AssetRepository : Repository<Asset>, IAssetRepository
    {

        public AssetRepository(FinancialDbContext context)
            : base(context)
        {
        }

        private FinancialDbContext FinancialDbContext
        {
            get { return _context as FinancialDbContext; }
        }


        public new Asset Get(int id)
        {
            return FinancialDbContext.Assets
                .Include(r => r.AssetType)
                .FirstOrDefault(r => r.Id == id);
        }

        public IEnumerable<Asset> GetAllActiveOrderedByName()
        {
            return FinancialDbContext.Assets
                .Include(r => r.AssetType)
                .Where(r => r.IsActive)
                .OrderBy(r => r.Name)
                .ToList();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.SettingType
{
    public class IndexViewModel
    {
        public IndexViewModel()
        {
        }

        public IndexViewModel(Business.Models.AttributeType bmSettingType)
        {
            Id = bmSettingType.SettingTypeId;
            Name = bmSettingType.SettingTypeName;
            //IsActive = bmSettingType.IsActive;
        }

        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Display(Name = "Active")]
        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Core;

namespace Financial.Business.Models
{
    public class Account
    {
        public Account()
        {
            
        }

        public Account(Core.Models.Asset dtoAsset)
        {
            AssetId = dtoAsset.Id;
            AssetName = dtoAsset.Name;
            AssetTypeId = dtoAsset.AssetTypeId;
            AssetTypeName = dtoAsset.AssetType.Name;
        }

        public Account(Core.Models.Asset dtoAsset, Core.Models.AssetType dtoAssetType)
        {
            AssetId = dtoAsset.Id;
            AssetName = dtoAsset.Name;
            AssetTypeId = dtoAssetType.Id;
            AssetTypeName = dtoAssetType.Name;
        }
        public int AssetId { get; set; }
        public string AssetName { get; set; }
        public int AssetTypeId { get; set; }
        public string AssetTypeName { get; set; }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Financial.Core.Models;
using System.Data.Entity;
using Moq;
using Financial.Core;
using Financial.Data.Repositories;
using Financial.Tests.Mocks;

namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class AssetTypeRepositoryTests
    {
        private Asset _dbAsset;
        private AssetType _dbAssetType;
        private DbSet<Asset> _mockAssetDbSet;
        private DbSet<AssetType> _mockAssetTypeDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private int _callCount;
        private AssetTypeRepository _repository;

        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset { Id = 2, AssetTypeId = _dbAssetType.Id, Name = "b", IsActive = true };

            // setup DbContext
            Setup_FakeDbContext();

            // set up repository
            _repository = new AssetTypeRepository(_fakeDbContext);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void Get_WhenCalled_ReturnAssetType_Test()
        {
            var result = _repository.Get(_dbAssetType.Id);

            Assert.That(result, Is.InstanceOf<AssetType>());
        }


        // private methods



        private void Setup_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset },
                new List<AssetType> { _dbAssetType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetType> fakeAssetTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetTypes: fakeAssetTypeList);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dynamitey;
using NUnit.Framework;
using Moq;
using NSubstitute;
using Financial.Data;
using Financial.Core;
using Financial.Core.Models;
using Financial.Data.Repositories;
using Financial.Data.RepositoryInterfaces;
using Financial.Tests.Mocks;
using Financial.Tests._DmitriNesteruk;


namespace Financial.Tests.Data.Repositories
{
    [TestFixture]
    public class AssetRepositoryTests
    {
        private Asset _dbAsset;
        private AssetSetting _dbAssetSetting;
        private AssetType _dbAssetType;
        private SettingType _dbSettingType;
        private DbSet<Asset> _mockAssetDbSet;
        private DbSet<AssetType> _mockAssetTypeDbSet;
        private Mock<FinancialDbContext> _mockDbContext;
        private FinancialDbContext _fakeDbContext;
        private int _callCount;
        private AssetRepository _repository;

        [SetUp]
        public void SetUp()
        {
            // setup fake model
            _dbAssetType = new AssetType { Id = 1, Name = "a", IsActive = true };
            _dbAsset = new Asset
            {
                Id = 2,
                AssetTypeId = _dbAssetType.Id,
                AssetType = _dbAssetType, // setup include
                Name = "b",
                IsActive = true
            };
            _dbSettingType = new SettingType { Id = 3, Name = "c", IsActive = true };
            _dbAssetSetting = new AssetSetting
            {
                Id = 4,
                AssetId = _dbAsset.Id,
                Asset = _dbAsset, // setup include
                SettingTypeId = _dbSettingType.Id,
                SettingType = _dbSettingType, // setup include
                Value = "d",
                IsActive = true
            };

            // setup DbContext
            Setup_FakeDbContext();

            // set up repository
            _repository = new AssetRepository(_fakeDbContext);
        }

        [TearDown]
        public void TearDown()
        {

        }



        [Test]
        public void Add_WhenAssetProvided_ShouldCallDbContextSetAssetProperty_Test()
        {
            Setup_Repository_MockDbContext(new List<Asset>());

            // Arrange
            var newAsset = new Asset { /*Id = 1,*/ AssetTypeId = 2, Name = "b", IsActive = true };

            // reset count for repository call
            _callCount = 0;

            // Act
            _repository.Add(newAsset);

            // Assert
            Assert.That(_callCount, Is.EqualTo(1));
        }

        [Test]
        public void Add_WhenAssetProvided_AddEntityToDbContext_Test()
        {
            // Arrange
            _fakeDbContext = new FinancialDbContext();

            _repository = new AssetRepository(_fakeDbContext);

            var expectedAsset = new Asset { /*Id = 1,*/ AssetTypeId = 2, Name = "b", IsActive = true };

            // Act
            _repository.Add(expectedAsset);
            var actualAsset = _fakeDbContext.Assets.Local.ToList()[0];

            // Assert
            Assert.Multiple(() =>
            {
                Assert.That(actualAsset.Id, Is.EqualTo(0), "Asset Id");
                Assert.That(actualAsset.Name, Is.EqualTo(expectedAsset.Name), "Asset Name");
                Assert.That(actualAsset.AssetTypeId, Is.EqualTo(expectedAsset.AssetTypeId), "AssetType Id");
                Assert.That(actualAsset.IsActive, Is.EqualTo(expectedAsset.IsActive), "IsActive");
            });
        }


        [Test]
        public void Get_WhenCalled_ReturnAsset_Test()
        {
            var result = _repository.Get(_dbAsset.Id);

            Assert.That(result, Is.InstanceOf<Asset>());
        }

        [Test]
        public void Get_WhenCalled_ReturnAssetValues_Test()
        {
            var result = _repository.Get(_dbAsset.Id);

            Assert.Multiple(() =>
            {
                Assert.That(result.Id, Is.EqualTo(_dbAsset.Id), "Asset Id");
                Assert.That(result.AssetTypeId, Is.EqualTo(_dbAsset.AssetTypeId), "AssetType Id");
                Assert.That(result.AssetType.Name, Is.EqualTo(_dbAssetType.Name), "AssetType Name");
                Assert.That(result.Name, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result.IsActive, Is.EqualTo(_dbAsset.IsActive), "IsActive");
            });
        }



        [Test]
        public void GetAllActiveOrderedByName_WhenCalled_ReturnAssetIEnumerable_Test()
        {
            var result = _repository.GetAllActiveOrderedByName();

            Assert.That(result, Is.InstanceOf<IEnumerable<Asset>>());
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenCalled_ReturnAssetValues_Test()
        {
            var result = _repository.GetAllActiveOrderedByName().ToList();

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Id, Is.EqualTo(_dbAsset.Id), "Asset Id");
                Assert.That(result[0].AssetTypeId, Is.EqualTo(_dbAsset.AssetTypeId), "AssetType Id");
                Assert.That(result[0].Name, Is.EqualTo(_dbAsset.Name), "Asset Name");
                Assert.That(result[0].IsActive, Is.EqualTo(_dbAsset.IsActive), "IsActive");
            });
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenIsActiveEqualsTrue_ReturnAsset_Test()
        {
            var fakeAssetTypes = new List<AssetType> {_dbAssetType};
            var fakeAssets = new List<Asset>
            {
                new Asset { Id = 1, AssetTypeId = _dbAssetType.Id, Name = "a", IsActive = true },
            };

            Setup_Repository_FakeDbContext(fakeAssets, fakeAssetTypes);

            var result = _repository.GetAllActiveOrderedByName();

            Assert.That(result.Count(), Is.EqualTo(1));
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenIsActiveEqualsFalse_DoNotReturnAsset_Test()
        {
            var fakeAssetTypes = new List<AssetType> { _dbAssetType };
            var fakeAssets = new List<Asset>
            {
                new Asset { Id = 1, AssetTypeId = _dbAssetType.Id, Name = "a", IsActive = false },
            };

            Setup_Repository_FakeDbContext(fakeAssets, fakeAssetTypes);

            var result = _repository.GetAllActiveOrderedByName();

            Assert.That(result.Count(), Is.EqualTo(0));
        }

        [Test]
        public void GetAllActiveOrderedByName_WhenMultipleAssetsFound_ReturnListSortedAscendingByAssetName_Test()
        {
            var fakeAssetTypes = new List<AssetType> { _dbAssetType };
            var fakeAssets = new List<Asset>
            {
                new Asset { Id = 1, AssetTypeId = _dbAssetType.Id, Name = "z", IsActive = true },
                new Asset { Id = 2, AssetTypeId = _dbAssetType.Id, Name = "a", IsActive = true }
            };

            Setup_Repository_FakeDbContext(fakeAssets, fakeAssetTypes);

            var result = _repository.GetAllActiveOrderedByName().ToList();

            Assert.Multiple(() =>
            {
                Assert.That(result[0].Name, Is.EqualTo("a"), "First Index");
                Assert.That(result[1].Name, Is.EqualTo("z"), "Second Index");
            });
        }



        // private methods


        private void Setup_FakeDbContext()
        {
            // setup dbContext
            Setup_FakeDbContext(
                new List<Asset> { _dbAsset }, 
                new List<AssetType> { _dbAssetType },
                new List<AssetSetting> { _dbAssetSetting },
                new List<SettingType> { _dbSettingType });
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList,
            List<AssetType> fakeAssetTypeList,
            List<AssetSetting> fakeAssetSettingList,
            List<SettingType> fakeSettingTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetTypes: fakeAssetTypeList,
                assetSettings: fakeAssetSettingList,
                settingTypes: fakeSettingTypeList);
        }

        private void Setup_FakeDbContext(
            List<Asset> fakeAssetList, 
            List<AssetType> fakeAssetTypeList)
        {
            // setup dbContext
            _fakeDbContext = MockFinancialDbContext.Create(
                assets: fakeAssetList,
                assetTypes: fakeAssetTypeList);
        }

        private void Setup_Repository_FakeDbContext(List<Asset> fakeAssetList, List<AssetType> fakeAssetTypeList)
        {
            // setup DbContext
            Setup_FakeDbContext(fakeAssetList, fakeAssetTypeList);

            // set up repository
            _repository = new AssetRepository(_fakeDbContext);
        }

        private void Setup_Repository_MockDbContext(List<Asset> fakeAssets)
        {
            // setup DbSet
            _mockAssetDbSet = MockDbSet.Create<Asset>(fakeAssets);

            // setup DbContext
            _callCount = 0;
            _mockDbContext = new Mock<FinancialDbContext>();
            _mockDbContext.Setup(c => c.Set<Asset>())
                .Returns(_mockAssetDbSet)
                .Callback(() => _callCount++);

            // set up repository
            _repository = new AssetRepository(_mockDbContext.Object);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.WebApplication.Models.ViewModels.AssetSetting
{
    public class EditViewModel
    {
        public EditViewModel() { }

        public EditViewModel(Core.Models.AssetSetting dtoAssetSetting, Core.Models.Asset dtoAsset,
            Core.Models.SettingType dtoSettingType)
        {
            Id = dtoAssetSetting.Id;
            AssetId = dtoAsset.Id;
            SettingTypeId = dtoSettingType.Id;
            SettingTypeName = dtoSettingType.Name;
            Value = dtoAssetSetting.Value;
            IsActive = dtoAssetSetting.IsActive;
        }

        public int Id { get; set; }
        public int AssetId { get; set; }
        public int SettingTypeId { get; set; }
        public string SettingTypeName { get; set; }
        public string Value { get; set; }
        public bool IsActive { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeSettingTypes
    {
        public static IEnumerable<SettingType> InitialFakeSettingTypes()
        {
            yield return new SettingType() { Id = 1, Name = "SettingTypeName1", IsActive = true };
            yield return new SettingType() { Id = 2, Name = "SettingTypeName2", IsActive = true };
            yield return new SettingType() { Id = 3, Name = "SettingTypeName3", IsActive = false };
            yield return new SettingType() { Id = 4, Name = "SettingTypeName4", IsActive = true };
            yield return new SettingType() { Id = 5, Name = "SettingTypeName5", IsActive = true };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class EditAssetViewModel
    {
        public EditAssetViewModel() { }

        public EditAssetViewModel(Core.Models.AssetTransaction dtoAssetTransaction, 
            List<SelectListItem> sliAssets, string selectdAssetId, 
            Core.Models.AssetType dtoAssetType, string transactionType, string transactionCategory)
        {
            Id = dtoAssetTransaction.Id;
            Assets = sliAssets;
            SelectedAssetId = selectdAssetId;
            AssetTypeName = dtoAssetType.Name;
            DueDate = dtoAssetTransaction.DueDate.ToString("MM/dd/yyyy");
            ClearDate = dtoAssetTransaction.ClearDate.ToString("MM/dd/yyyy");
            CheckNumber = dtoAssetTransaction.CheckNumber;
            Amount = string.Format("{0:C}", dtoAssetTransaction.Amount);
            Note = dtoAssetTransaction.Note;
            TransactionType = transactionCategory;
            TransactionCategory = transactionCategory;
        }


        public int Id { get; set; }
        [Required]
        [Display(Name = "Asset Name")]
        public string SelectedAssetId { get; set; }
        public IEnumerable<SelectListItem> Assets { get; set; }
        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }
        [Display(Name = "Check Number")]
        public string CheckNumber { get; set; }
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public string DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public string ClearDate { get; set; }
        public string Amount { get; set; }
        public string Note { get; set; }
        [Display(Name = "Type")]
        public string TransactionType { get; set; }
        [Display(Name = "Category")]
        public string TransactionCategory { get; set; }
    }
}
<file_sep>﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;

namespace Financial.WebApplication.App_Start
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            //Mapper.Map<>();
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class DeleteViewModel
    {
        public DeleteViewModel() { }

        public DeleteViewModel(Business.Models.AccountTransaction bmAssetTransaction)
        {
            Id = bmAssetTransaction.AssetTransactionId;
            AssetId = bmAssetTransaction.AssetId;
            AssetName = bmAssetTransaction.AssetName;
            AssetTypeName = bmAssetTransaction.AssetTypeName;
            DueDate = bmAssetTransaction.DueDate;
            ClearDate = bmAssetTransaction.ClearDate;
            CheckNumber = bmAssetTransaction.CheckNumber;
            Amount = bmAssetTransaction.Amount;
            Note = bmAssetTransaction.Note;
            TransactionTypeName = bmAssetTransaction.TransactionTypeName;
            TransactionCategoryName = bmAssetTransaction.TransactionCategoryName;
        }


        public int Id { get; set; }
        public int AssetId { get; set; }
        [Display(Name = "Asset Name")]
        public string AssetName { get; set; }
        [Display(Name = "Asset Type")]
        public string AssetTypeName { get; set; }
        [Display(Name = "Check Number")]
        public string CheckNumber { get; set; }
        [Display(Name = "Due")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DueDate { get; set; }
        [Display(Name = "Cleared")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime ClearDate { get; set; }
        public decimal Amount { get; set; }
        public string Note { get; set; }
        [Display(Name = "Type")]
        public string TransactionTypeName { get; set; }
        [Display(Name = "Category")]
        public string TransactionCategoryName { get; set; }
    }
}<file_sep>﻿using Financial.Business.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Financial.Business.Tests.Fakes.Repositories;
using System.Web.Mvc;
using NUnit.Framework;

namespace Financial.Business.Tests.Services
{
    /*
    public class AssetTransactionServiceTestsBase : ServiceTestsBase
    {
        public AssetTransactionServiceTestsBase()
        {
            _service = new AssetTransactionService(_unitOfWork);
        }

        protected AssetTransactionService _service;
    }
    */

    public static class AssetTransactionServiceObjectMother
    {
        public static int AssetTypeIdForCreditCard = 3;
        public static int SettingTypeIdForAccountNumber = 1;
    }


    [TestFixture]
    public class AssetTransactionServiceTests : ServiceTestsBase
    {
        private AccountTransactionService _service;

        // SetUp Setting
        // TearDown Setting

        [SetUp]
        public void SetUp()
        {
            ResetUnitOfWork();
            _service = new AccountTransactionService(_unitOfWork);
        }


        [Test]
        public void GetListOfActiveTransactions_WhenNoInputValues_ReturnList_Test()
        {
            // Arrange

            // Act
            var result = _service.GetListOfActiveTransactions();

            // Assert
            Assert.IsInstanceOf(typeof(List<Business.Models.AccountTransaction>), result, "Result Type");
            Assert.That(result, Is.TypeOf<Business.Models.AccountTransaction>());
            Assert.IsNotNull(result, "Asset Transaction List");
        }


        /*
        [Test]
        public void GetTransactionOptions_WhenValidAssetIdProvided_ReturnAssetId_Test()
        {
            // Arrange

            // Act
            var result = _service.GetTransactionOptions(1);

            // Assert
            Assert.That(result.AssetId, Is.EqualTo(1));
        }
        */
        /*
        [Test]
        [TestCase(99, 0)]
        [TestCase(null, 0)]
        public void GetTransactionOptions_WhenInvalidAssetIdProvided_ReturnAssetIdEqualsZero_Test(int? assetId, int expectedResult)
        {
            // Arrange
            //var expAssetId = 1;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionOptions(assetId);

            // Assert
            Assert.That(result.AssetId, Is.EqualTo(0));
        }
        */
        /*
        [Test]
        public void GetTransactionOptions_WhenAssetIdExists_ReturnAssetTransaction_Test()
        {
            // Arrange
            var expAssetId = 1;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionOptions(expAssetId);

            // Assert
            Assert.IsInstanceOf(typeof(Business.Models.AssetTransaction), result, "Result Type");
            Assert.IsNotNull(result, "Asset Transaction");
        }

        [Test]
        public void GetTransactionOptions_WhenAssetIdNotFound_ReturnNull_Test()
        {
            // Arrange
            int? expAssetId = 99;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionOptions(expAssetId);

            // Assert
            Assert.IsNull(result, "Asset Transaction");
        }

        [Test]
        public void GetTransactionOptions_WhenAssetIdIsNull_ReturnNull_Test()
        {
            // Arrange
            int? expAssetId = null;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionOptions(expAssetId);

            // Assert
            Assert.IsNull(result, "Asset Transaction");
        }
        */
        /*
        [Test]
        public void GetTransactionOptions_WhenAssetIdNotFound_ThrowException()
        {
            var result = _service.GetTransactionOptions(99);

            Assert.That(() => _service.GetTransactionOptions(99), Throws.ArgumentNullException);
        }
        */
        /*
        [Test]
        [TestCase("1", true)]
        [TestCase("0", false)]
        [TestCase("99", false)]
        [TestCase(null, false)]
        public void GetAssetSelectList_WhenCalled_ReturnSelectListWithSelectedValue_Test(string selectedId, bool expectedResult)
        {
            // Arrange

            // Act
            var result = _service.GetAssetSelectList(selectedId);

            // Assert
            Assert.That(result.Any(r => r.Selected), Is.EqualTo(expectedResult));
        }
        */
        /*
        [Test]
        public void GetAssetSelectList_WhenSuccess_ReturnSelectList_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsNotNull(result, "Result");
            Assert.AreNotEqual(0, result.Count, "Result Count");
        }

        [Test]
        public void GetAssetSelectList_WhenSelectedValueIsNull_ReturnNoSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetAssetSelectList_WhenSelectedValueIsFound_ReturnSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = "1";

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(expSelectedId, result.FirstOrDefault(r => r.Selected).Value, "Result Selected Value");
        }

        [Test]
        public void GetAssetSelectList_WhenSelectedValueIsNotFound_ReturnNoSelectedValue_Test()
        {
            // Arrange
            // sut = _service;
            string expSelectedId = "99";

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetAssetSelectList_WhenSuccess_ReturnActiveAssets_Test()
        {
            // Arrange
            var _dataAssets = new List<Core.Models.Asset>()
            {
                new Core.Models.Asset() {Id = 10, Name = "Active", IsActive = true },
                new Core.Models.Asset() {Id = 11, Name = "Not Active", IsActive = false },
            };
            _unitOfWork.Assets = new InMemoryAssetRepository(_dataAssets);
            _service = new AssetTransactionService(_unitOfWork);
            string expSelectedId = null;

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(1, result.Count, "Result Count");
        }

        [Test]
        public void GetAssetSelectList_WhenSuccess_ReturnOrderedByTransactionTypeName_Test()
        {
            // Arrange
            var _dataAssets = new List<Core.Models.Asset>()
            {
                new Core.Models.Asset() {Id = 10, Name = "Z", IsActive = true },
                new Core.Models.Asset() {Id = 11, Name = "A", IsActive = true },
                new Core.Models.Asset() {Id = 12, Name = "B", IsActive = true },
            };
            _unitOfWork.Assets = new InMemoryAssetRepository(_dataAssets);
            _service = new AssetTransactionService(_unitOfWork);
            string expSelectedId = "99";

            // Act
            var result = _service.GetAssetSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual("A", result[0].Text, "Result Name A");
            Assert.AreEqual("B", result[1].Text, "Result Name B");
            Assert.AreEqual("Z", result[2].Text, "Result Name Z");
        }
        */



        [Test]
        [Ignore("Because I am testing this feature")]
        public void AddTransaction_WhenAssetTransactionIsValid_ReturnTrue_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetId = 1,
                TransactionTypeId = 2,
                TransactionCategoryId = 3
            };
            //var sut = _service;

            // Act
            var result = _service.AddTransaction(expAssetTransaction);

            // Assert
            Assert.IsTrue(result, "Result");
        }

        [Test]
        public void AddTransaction_WhenAssetIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetId = 99,
                TransactionTypeId = 2,
                TransactionCategoryId = 3
            };
            //var sut = _service;

            // Act
            var result = _service.AddTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void AddTransaction_WhenTransactionTypeIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetId = 1,
                TransactionTypeId = 99,
                TransactionCategoryId = 3
            };
            //var sut = _service;

            // Act
            var result = _service.AddTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void AddTransaction_WhenTransactionCateogryIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetId = 1,
                TransactionTypeId = 2,
                TransactionCategoryId = 99
            };
            //var sut = _service;

            // Act
            var result = _service.AddTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }



        [Test]
        public void GetTransactionToEdit_WhenAssetTransactionIdIsValid_ReturnAssetTransaction_Test()
        {
            // Arrange
            var expAssetTransactionId = 1;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionToEdit(expAssetTransactionId);

            // Assert
            Assert.IsInstanceOf(typeof(Business.Models.AccountTransaction), result, "Result Type");
            Assert.IsNotNull(result, "Asset Transaction List");
            //Assert.IsNotNull(result.TransactionTypeSelectList, "Transaction Type List");
            //Assert.IsNotNull(result.TransactionCategorySelectList, "Transaction Category List");
        }

        [Test]
        public void GetTransactionToEdit_WhenAssetTransactionIdNotFound_ReturnNull_Test()
        {
            // Arrange
            var expAssetTransactionId = 99;
            //var sut = _service;

            // Act
            var result = _service.GetTransactionToEdit(expAssetTransactionId);

            // Assert
            Assert.IsNull(result, "Result");
        }



        [Test]
        public void GetAssetIdentificationInformation_WhenAssetIsValid_ReturnAssetName_Test()
        {
            // Arrange
            var expAsset = new Core.Models.Asset()
            {
                Id = 1,
                AssetTypeId = 2,
                Name = "Asset Name",
                IsActive = true,
            };
           // var sut = _service;

            // Act
            var result = _service.GetAssetIdentificationInformation(expAsset);

            // Assert
            Assert.IsInstanceOf(typeof(string), result, "Result Type");
            Assert.IsNotNull(result, "Formatted Asset Name");
        }

        [Test]
        public void GetAssetIdentificationInformation_WhenAssetIsNull_ReturnEmptyString_Test()
        {
            // Arrange
            //var sut = _service;

            // Act
            var result = _service.GetAssetIdentificationInformation(null);

            // Assert
            Assert.IsInstanceOf(typeof(string), result, "Result Type");
            Assert.AreEqual(string.Empty, result, "Formatted Asset Name");
        }

        [Test]
        public void GetAssetIdentificationInformation_WhenAssetTypeIsCreditCard_ReturnUpdatedAssetName_Test()
        {
            // Arrange
            var expAsset = new Core.Models.Asset()
            {
                Id = 1,
                AssetTypeId = AssetTransactionServiceObjectMother.AssetTypeIdForCreditCard,
                Name = "Asset Name",
                IsActive = true,
            };
            var expSettingTypeId = AssetTransactionServiceObjectMother.SettingTypeIdForAccountNumber;
            var _dataSettingTypes = new List<Core.Models.SettingType>()
            {
                new Core.Models.SettingType()
                {
                    Id = expSettingTypeId,
                    IsActive = true,
                }
            };
            var _dataAssetSettings = new List<Core.Models.AssetSetting>()
            {
                new Core.Models.AssetSetting() {
                    Id = 10,
                    AssetId = expAsset.Id,
                    SettingTypeId = expSettingTypeId,
                    Value = "1234",
                    IsActive = true,
                }
            };
            _unitOfWork.AssetSettings = new InMemoryAssetSettingRepository(_dataAssetSettings);
            var expAssetName = expAsset.Name + " (1234)";
            _service = new AccountTransactionService(_unitOfWork);

            // Act
            var result = _service.GetAssetIdentificationInformation(expAsset);

            // Assert
            Assert.IsInstanceOf(typeof(string), result, "Result Type");
            Assert.AreEqual(expAssetName, result, "Asset Name");
        }



        [Test]
        public void GetTransactionTypeSelectList_WhenSuccess_ReturnSelectList_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsNotNull(result, "Result");
            Assert.AreNotEqual(0, result.Count, "Result Count");
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSelectedValueIsNull_ReturnNoSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSelectedValueIsFound_ReturnSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = "1";

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(expSelectedId, result.FirstOrDefault(r => r.Selected).Value, "Result Selected Value");
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSelectedValueIsNotFound_ReturnNoSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = "99";

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSuccess_ReturnActiveTransactionTypes_Test()
        {
            // Arrange
            var _dataTransactionTypes = new List<Core.Models.TransactionType>()
            {
                new Core.Models.TransactionType() {Id = 10, Name = "Active", IsActive = true },
                new Core.Models.TransactionType() {Id = 11, Name = "Not Active", IsActive = false },
            };
            _unitOfWork.TransactionTypes = new InMemoryTransactionTypeRepository(_dataTransactionTypes);
            _service = new AccountTransactionService(_unitOfWork);
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(1, result.Count, "Result Count");
        }

        [Test]
        public void GetTransactionTypeSelectList_WhenSuccess_ReturnOrderedByTransactionTypeName_Test()
        {
            // Arrange
            var _dataTransactionTypes = new List<Core.Models.TransactionType>()
            {
                new Core.Models.TransactionType() {Id = 10, Name = "Z", IsActive = true },
                new Core.Models.TransactionType() {Id = 11, Name = "A", IsActive = true },
                new Core.Models.TransactionType() {Id = 12, Name = "B", IsActive = true },
            };
            _unitOfWork.TransactionTypes = new InMemoryTransactionTypeRepository(_dataTransactionTypes);
            _service = new AccountTransactionService(_unitOfWork);
            string expSelectedId = "99";

            // Act
            var result = _service.GetTransactionTypeSelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual("A", result[0].Text, "Result Name A");
            Assert.AreEqual("B", result[1].Text, "Result Name B");
            Assert.AreEqual("Z", result[2].Text, "Result Name Z");
        }



        [Test]
        public void GetTransactionCategorySelectList_WhenSuccess_ReturnSelectList_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsNotNull(result, "Result");
            Assert.AreNotEqual(0, result.Count, "Result Count");
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSelectedValueIsNull_ReturnNoSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSelectedValueIsFound_ReturnSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = "1";

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(expSelectedId, result.FirstOrDefault(r => r.Selected).Value, "Result Selected Value");
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSelectedValueIsNotFound_ReturnNoSelectedValue_Test()
        {
            // Arrange
            //var sut = _service;
            string expSelectedId = "99";

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.IsFalse(result.Any(r => r.Selected), "Result Selected Value");
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSuccess_ReturnActiveTransactionTypes_Test()
        {
            // Arrange
            var _dataTransactionCategories = new List<Core.Models.TransactionCategory>()
            {
                new Core.Models.TransactionCategory() {Id = 10, Name = "Active", IsActive = true },
                new Core.Models.TransactionCategory() {Id = 11, Name = "Not Active", IsActive = false },
            };
            _unitOfWork.TransactionCategories = new InMemoryTransactionCategoryRepository(_dataTransactionCategories);
            _service = new AccountTransactionService(_unitOfWork);
            string expSelectedId = null;

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual(1, result.Count, "Result Count");
        }

        [Test]
        public void GetTransactionCategorySelectList_WhenSuccess_ReturnOrderedByTransactionTypeName_Test()
        {
            // Arrange
            var _dataTransactionCategories = new List<Core.Models.TransactionCategory>()
            {
                new Core.Models.TransactionCategory() {Id = 10, Name = "Z", IsActive = true },
                new Core.Models.TransactionCategory() {Id = 11, Name = "A", IsActive = true },
                new Core.Models.TransactionCategory() {Id = 12, Name = "B", IsActive = true },
            };
            _unitOfWork.TransactionCategories = new InMemoryTransactionCategoryRepository(_dataTransactionCategories);
            _service = new AccountTransactionService(_unitOfWork);
            string expSelectedId = "99";

            // Act
            var result = _service.GetTransactionCategorySelectList(expSelectedId);

            // Assert
            Assert.IsInstanceOf(typeof(List<SelectListItem>), result, "Result Type");
            Assert.AreEqual("A", result[0].Text, "Result Name A");
            Assert.AreEqual("B", result[1].Text, "Result Name B");
            Assert.AreEqual("Z", result[2].Text, "Result Name Z");
        }



        [Test]
        public void UpdateTransaction_WhenAssetTransactionIsValid_ReturnTrue_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetTransactionId = 1,
                AssetId = 2,
                TransactionTypeId = 3,
                TransactionCategoryId = 4,
            };
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(expAssetTransaction);

            // Assert
            Assert.IsTrue(result, "Result");
        }

        [Test]
        public void UpdateTransaction_WhenAssetTransactionIsNull_ReturnFalse_Test()
        {
            // Arrange
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(null);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void UpdateTransaction_WhenAssetTransactionIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetTransactionId = 99,
                AssetId = 2,
                TransactionTypeId = 3,
                TransactionCategoryId = 4,
            };
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void UpdateTransaction_WhenAssetIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetTransactionId = 1,
                AssetId = 99,
                TransactionTypeId = 3,
                TransactionCategoryId = 4,
            };
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void UpdateTransaction_WhenTransactionTypeIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetTransactionId = 1,
                AssetId = 2,
                TransactionTypeId = 99,
                TransactionCategoryId = 4,
            };
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }

        [Test]
        public void UpdateTransaction_WhenTransactionCateogryIdIsNotFound_ReturnFalse_Test()
        {
            // Arrange
            var expAssetTransaction = new Business.Models.AccountTransaction()
            {
                AssetTransactionId = 1,
                AssetId = 2,
                TransactionTypeId = 3,
                TransactionCategoryId = 99,
            };
            //var sut = _service;

            // Act
            var result = _service.UpdateTransaction(expAssetTransaction);

            // Assert
            Assert.IsFalse(result, "Result");
        }



        [Test]
        public void GetTransactionToDelete_WhenAssetTransactionIdIsValid_ReturnAssetTransaction_Test()
        {
            // Arrange
            //var sut = _service;
            var expAssetTransactionId = 1;

            // Act
            var result = _service.GetTransactionToDelete(expAssetTransactionId);

            // Assert
            Assert.IsInstanceOf(typeof(Business.Models.AccountTransaction), result, "Result Type");
            Assert.IsNotNull(result, "Asset Transaction List");
        }

        [Test]
        public void GetTransactionToDelete_WhenAssetTransactionIdNotFound_ReturnNull_Test()
        {
            // Arrange
            //var sut = _service;
            var expAssetTransactionId = 99;

            // Act
            var result = _service.GetTransactionToDelete(expAssetTransactionId);

            // Assert
            Assert.IsNull(result, "Result");
        }



        [Test]
        public void DeleteTransaction_WhenAssetTransactionIdIsValid_ReturnTrue_Test()
        {
            // Arrange
            //var sut = _service;
            var expAssetTransactionId = 1;

            // Act
            var result = _service.DeleteTransaction(expAssetTransactionId);

            // Assert
            Assert.IsInstanceOf(typeof(bool), result, "Result Type");
            Assert.IsTrue(result, "Result");
        }

        [Test]
        public void DeleteTransaction_WhenAssetTransactionIdNotFound_ReturnFalse_Test()
        {
            // Arrange
            //var sut = _service;
            var expAssetTransactionId = 99;

            // Act
            var result = _service.DeleteTransaction(expAssetTransactionId);

            // Assert
            Assert.IsInstanceOf(typeof(bool), result, "Result Type");
            Assert.IsFalse(result, "Result");
        }


    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Financial.WebApplication.Models.ViewModels.AccountTransaction
{
    public class SelectAssetToCreateViewModel
    {
        public SelectAssetToCreateViewModel() { }
        public SelectAssetToCreateViewModel(List<SelectListItem> sliAssets)
        {
            Assets = sliAssets;
        }


        [Required]
        [Display(Name = "Asset Name")]
        public string SelectedAssetId { get; set; }
        public IEnumerable<SelectListItem> Assets { get; set; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Core
{
    public interface IFinancialDbContext
    {
        DbSet<Asset> Assets { get; }
        DbSet<AssetSetting> AssetSettings { get; }
        DbSet<AssetRelationship> AssetRelationships { get; }
        DbSet<AssetTransaction> AssetTransactions { get; }
        DbSet<AssetType> AssetTypes { get; }
        DbSet<AssetTypeSettingType> AssetTypesSettingTypes { get; }
        DbSet<AssetTypeRelationshipType> AssetTypesRelationshipTypes { get; }
        DbSet<ParentChildRelationshipType> ParentChildRelationshipTypes { get; }
        DbSet<RelationshipType> RelationshipTypes { get; }
        DbSet<SettingType> SettingTypes { get; }
        DbSet<TransactionCategory> TransactionCategories { get; }
        DbSet<TransactionDescription> TransactionDescriptions { get; }
        DbSet<TransactionType> TransactionTypes { get; }
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Data.RepositoryInterfaces
{
    public interface ISettingTypeRepository : IRepository<SettingType>
    {
        SettingType GetActive(int id);
        IEnumerable<SettingType> GetAllOrderedByName();
        int CountMatching(string name);
        int CountMatching(int excludeId, string name);
    }
}
<file_sep>﻿using Financial.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.Tests.Fakes.Database
{
    public class FakeAssetTypesSettingTypes
    {
        public static IEnumerable<AssetTypeSettingType> InitialFakeAssetTypesSettingTypes()
        {
            yield return new AssetTypeSettingType() { Id = 1, AssetTypeId = 1, SettingTypeId = 4, IsActive = true };
            yield return new AssetTypeSettingType() { Id = 2, AssetTypeId = 1, SettingTypeId = 5, IsActive = true };
            yield return new AssetTypeSettingType() { Id = 3, AssetTypeId = 1, SettingTypeId = 2, IsActive = false };
            yield return new AssetTypeSettingType() { Id = 4, AssetTypeId = 5, SettingTypeId = 2, IsActive = true };
            yield return new AssetTypeSettingType() { Id = 5, AssetTypeId = 4, SettingTypeId = 1, IsActive = true };
        }
    }
}
<file_sep>﻿using Financial.Business.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Financial.Business.ServiceInterfaces
{
    public interface IAccountTypeSettingTypeService
    {
        Business.Models.AccountType CreateLinkedSettingTypesGetModel(int assetTypeId);
        Business.Models.AccountType EditLinkedSettingTypesGetModel(int assetTypeId);




        List<AccountType> GetListOfLinkedAssetTypes(int settingTypeId);

        List<AttributeType> GetListOfLinkedSettingTypes(int assetTypeId);

        List<AttributeType> GetListOfSettingTypesWithLinkedAssetType(int assetTypeId);

    }
}
