Why this post exists

This is Part 3 of Day 4 and the mid-level capstone of my six-day C# deep dive. Part 1 covered extension methods, pattern matching and records. Part 2 covered IDisposable, JSON, unit testing and dependency injection. Along with Day 3 (generics, collections, delegates, events, LINQ and iterators), you now have every mid-level concept. This post puts them all in one real project: an Expense Tracker with a passing test suite.

The post gives you the requirements and a suggested order of work first, then the complete solution, a real session, and the reasons each decision was made. Build it yourself before reading the solution. That is where the learning happens.

Mid-level capstone: Expense Tracker

Now combine everything from Days 3 and 4 in one project. Build an Expense Tracker as a console app. Requirements:

  • A generic repository (IRepository<T> with an IEntity constraint)
  • LINQ reports: monthly totals, spending by category for a month, and top spend
  • Events for budget alerts (a warning at 80% and an alert when the limit is passed)
  • Extension methods (money formatting, weekends, month helpers)
  • JSON persistence
  • Records for the transactions
  • Pattern matching for the categorization rules
  • Proper disposal of anything that holds a resource
  • At least 10 unit tests

Try it yourself first. A sensible order is: the Expense record and the repository, then the Categorizer with its tests, then reports, then the budget events, then JSON, and the console menu last. Write each test before or right after the code it covers.

Project layout

ExpenseTracker/ ExpenseTracker.Core/ class library: all the logic, no Console calls Abstractions.cs IEntity, IRepository<T>, InMemoryRepository<T>, IClock Models.cs Expense, Category, report records, BudgetAlertEventArgs Extensions.cs ToMoney, IsWeekend, StartOfMonth, InMonth Categorizer.cs pattern-matching rules ExpenseService.cs adding expenses, budgets, events Reports.cs the LINQ reports ExpenseStore.cs JSON persistence AuditLog.cs IDisposable audit file ExpenseTracker.App/ console app: menu and input/output only Program.cs ExpenseTracker.Tests/ xUnit test project ExpenseTrackerTests.cs 
dotnet new sln -n ExpenseTracker dotnet new classlib -n ExpenseTracker.Core dotnet new console -n ExpenseTracker.App dotnet new xunit -n ExpenseTracker.Tests dotnet add ExpenseTracker.App reference ExpenseTracker.Core dotnet add ExpenseTracker.Tests reference ExpenseTracker.Core dotnet sln add ExpenseTracker.Core ExpenseTracker.App ExpenseTracker.Tests 

Solution

// ===== ExpenseTracker.Core/Abstractions.cs ===== namespace ExpenseTracker.Core; public interface IEntity { int Id { get; } } public interface IRepository<T> where T : class, IEntity { void Add(T item); T? Get(int id); bool Remove(int id); IReadOnlyList<T> GetAll(); } public sealed class InMemoryRepository<T> : IRepository<T> where T : class, IEntity { private readonly Dictionary<int, T> _items = new(); public void Add(T item) { ArgumentNullException.ThrowIfNull(item); if (!_items.TryAdd(item.Id, item)) { throw new InvalidOperationException($"A {typeof(T).Name} with id {item.Id} already exists."); } } public T? Get(int id) => _items.GetValueOrDefault(id); public bool Remove(int id) => _items.Remove(id); public IReadOnlyList<T> GetAll() => _items.Values.ToList(); } public interface IClock { DateTimeOffset UtcNow { get; } } public sealed class SystemClock : IClock { public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; } 
// ===== ExpenseTracker.Core/Models.cs ===== namespace ExpenseTracker.Core; public enum Category { Food, Transport, Housing, Entertainment, Health, Other } public enum AlertLevel { Warning, Exceeded } public sealed record Expense(int Id, DateOnly Date, string Description, decimal Amount, Category Category) : IEntity; public sealed record MonthTotal(DateOnly Month, decimal Total); public sealed record CategoryTotal(Category Category, decimal Total, decimal Share); public sealed class BudgetAlertEventArgs : EventArgs { public BudgetAlertEventArgs(Category category, int year, int month, decimal spent, decimal limit, AlertLevel level) => (Category, Year, Month, Spent, Limit, Level) = (category, year, month, spent, limit, level); public Category Category { get; } public int Year { get; } public int Month { get; } public decimal Spent { get; } public decimal Limit { get; } public AlertLevel Level { get; } } 
// ===== ExpenseTracker.Core/Extensions.cs ===== using System.Globalization; namespace ExpenseTracker.Core; public static class ExpenseExtensions { public static string ToMoney(this decimal amount) => "$" + amount.ToString("N2", CultureInfo.InvariantCulture); public static bool IsWeekend(this DateOnly date) => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday; public static DateOnly StartOfMonth(this DateOnly date) => new(date.Year, date.Month, 1); public static IEnumerable<Expense> InMonth(this IEnumerable<Expense> expenses, int year, int month) => expenses.Where(e => e.Date.Year == year && e.Date.Month == month); } 
// ===== ExpenseTracker.Core/Categorizer.cs ===== using System.Text.RegularExpressions; namespace ExpenseTracker.Core; public static class Categorizer { private static readonly Regex WordPattern = new(@"\p{L}+", RegexOptions.Compiled); public static Category Categorize(string description, decimal amount) { ArgumentException.ThrowIfNullOrWhiteSpace(description); return (Words(description), amount) switch { (_, <= 0) => throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive."), (var w, _) when Has(w, "grocery", "groceries", "restaurant", "cafe", "coffee", "pizza", "breakfast", "lunch", "dinner") => Category.Food, (var w, _) when Has(w, "uber", "taxi", "bus", "train", "metro", "fuel", "petrol", "parking") => Category.Transport, (var w, _) when Has(w, "rent", "mortgage", "electricity", "internet", "water") => Category.Housing, (var w, _) when Has(w, "movie", "netflix", "spotify", "concert", "game", "games") => Category.Entertainment, (var w, _) when Has(w, "pharmacy", "doctor", "dentist", "gym", "medicine") => Category.Health, _ => Category.Other }; } // Whole words only: "bus" must not match "business" private static HashSet<string> Words(string text) => WordPattern.Matches(text).Select(m => m.Value.ToLowerInvariant()).ToHashSet(); private static bool Has(HashSet<string> words, params string[] keywords) => keywords.Any(words.Contains); } 
// ===== ExpenseTracker.Core/ExpenseService.cs ===== namespace ExpenseTracker.Core; public class ExpenseService { private readonly IRepository<Expense> _repository; private readonly Dictionary<Category, decimal> _budgets = new(); private int _nextId; public ExpenseService(IRepository<Expense> repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _nextId = repository.GetAll().Select(e => e.Id).DefaultIfEmpty(0).Max() + 1; } public event EventHandler<Expense>? ExpenseAdded; public event EventHandler<BudgetAlertEventArgs>? BudgetAlert; public void SetBudget(Category category, decimal monthlyLimit) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(monthlyLimit); _budgets[category] = monthlyLimit; } public Expense Add(DateOnly date, string description, decimal amount, Category? category = null) { ArgumentException.ThrowIfNullOrWhiteSpace(description); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount); Category resolved = category ?? Categorizer.Categorize(description, amount); decimal spentBefore = MonthSpend(resolved, date.Year, date.Month); var expense = new Expense(_nextId++, date, description.Trim(), amount, resolved); _repository.Add(expense); ExpenseAdded?.Invoke(this, expense); CheckBudget(resolved, date, spentBefore, spentBefore + amount); return expense; } private decimal MonthSpend(Category category, int year, int month) => _repository.GetAll().Where(e => e.Category == category).InMonth(year, month).Sum(e => e.Amount); private void CheckBudget(Category category, DateOnly date, decimal before, decimal after) { if (!_budgets.TryGetValue(category, out decimal limit)) return; AlertLevel? level = (before, after) switch { var (b, a) when b <= limit && a > limit => AlertLevel.Exceeded, // crossed 100% var (b, a) when b < limit * 0.8m && a >= limit * 0.8m => AlertLevel.Warning, // crossed 80% _ => null }; if (level is { } alertLevel) { BudgetAlert?.Invoke(this, new BudgetAlertEventArgs(category, date.Year, date.Month, after, limit, alertLevel)); } } } 
// ===== ExpenseTracker.Core/Reports.cs ===== namespace ExpenseTracker.Core; public class ReportService { private readonly IRepository<Expense> _repository; public ReportService(IRepository<Expense> repository) => _repository = repository ?? throw new ArgumentNullException(nameof(repository)); public IReadOnlyList<MonthTotal> MonthlyTotals() => _repository.GetAll() .GroupBy(e => e.Date.StartOfMonth()) .OrderBy(g => g.Key) .Select(g => new MonthTotal(g.Key, g.Sum(e => e.Amount))) .ToList(); public IReadOnlyList<CategoryTotal> ByCategory(int year, int month) { List<Expense> inMonth = _repository.GetAll().InMonth(year, month).ToList(); decimal total = inMonth.Sum(e => e.Amount); return inMonth .GroupBy(e => e.Category) .Select(g => new CategoryTotal(g.Key, g.Sum(e => e.Amount), total == 0 ? 0 : g.Sum(e => e.Amount) / total)) .OrderByDescending(c => c.Total) .ThenBy(c => c.Category) .ToList(); } public IReadOnlyList<Expense> TopSpend(int count) => _repository.GetAll() .OrderByDescending(e => e.Amount) .ThenBy(e => e.Date) .ThenBy(e => e.Id) .Take(count) .ToList(); public decimal WeekendTotal(int year, int month) => _repository.GetAll().InMonth(year, month).Where(e => e.Date.IsWeekend()).Sum(e => e.Amount); } 
// ===== ExpenseTracker.Core/ExpenseStore.cs ===== using System.Text.Json; using System.Text.Json.Serialization; namespace ExpenseTracker.Core; public sealed class DataFileException : Exception { public DataFileException(string message, Exception inner) : base(message, inner) { } } public static class ExpenseStore { private static readonly Source:https://dev.to/manoharij/c-mid-level-capstone-build-an-expense-tracker-with-events-linq-json-pattern-matching-and-unit-cih

Related posts