Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using NSubstitute;
using Library.ApplicationCore;
using Library.ApplicationCore.Entities;
using Library.Infrastructure.Data;
using Microsoft.Extensions.Configuration;
using Xunit;

namespace UnitTests.Infrastructure.JsonLoanRepositoryTests;

public class GetLoanTest
{
private readonly ILoanRepository _mockLoanRepository;
private readonly JsonLoanRepository _jsonLoanRepository;
private readonly IConfiguration _configuration;
private readonly JsonData _jsonData;

public GetLoanTest()
{
_mockLoanRepository = Substitute.For<ILoanRepository>();
_configuration = new ConfigurationBuilder().Build();
_jsonData = new JsonData(_configuration);
_jsonLoanRepository = new JsonLoanRepository(_jsonData);
}

[Fact(DisplayName = "JsonLoanRepository.GetLoan: Returns loan when loan ID is found")]
public async Task GetLoan_ReturnsLoanWhenLoanIdIsFound()
{
// Arrange
var loanId = 1; // Use a loan ID that exists in the Loans.json file
var expectedLoan = new Loan
{
Id = loanId,
BookItemId = 17,
PatronId = 22,
LoanDate = DateTime.Parse("2023-12-08T00:40:43.1808862"),
DueDate = DateTime.Parse("2023-12-22T00:40:43.1808862"),
ReturnDate = null
};

_mockLoanRepository.GetLoan(loanId).Returns(expectedLoan);

// Act
var actualLoan = await _jsonLoanRepository.GetLoan(loanId);

// Assert
Assert.NotNull(actualLoan);
Assert.Equal(expectedLoan.Id, actualLoan?.Id);
}


[Fact(DisplayName = "JsonLoanRepository.GetLoan: Returns null when loan ID is not found")]
public async Task GetLoan_ReturnsNullWhenLoanIdIsNotFound()
{
// Arrange
var loanId = 999; // Use a loan ID that does not exist in the Loans.json file
var expectedLoan = new Loan { Id = loanId, BookItemId = 101, PatronId = 202, LoanDate = DateTime.Now, DueDate = DateTime.Now.AddDays(14) };
_mockLoanRepository.GetLoan(loanId).Returns(expectedLoan);

// Act
var actualLoan = await _jsonLoanRepository.GetLoan(loanId);

// Assert
Assert.Null(actualLoan);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@

<ItemGroup>
<ProjectReference Include="..\..\src\Library.ApplicationCore\Library.ApplicationCore.csproj" />
<ProjectReference Include="..\..\src\Library.Infrastructure\Library.Infrastructure.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="..\..\src\Library.Console\Json\**\*">
<Link>Json\%(RecursiveDir)%(FileName)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,27 +1,53 @@
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;

namespace Library.ApplicationCore.Enums;

public static class EnumHelper
{
private static readonly IReadOnlyDictionary<LoanExtensionStatus, string> LoanExtensionStatusDescriptions =
new Dictionary<LoanExtensionStatus, string>
{
[LoanExtensionStatus.Success] = "Book loan extension was successful.",
[LoanExtensionStatus.LoanNotFound] = "Loan not found.",
[LoanExtensionStatus.LoanExpired] = "Cannot extend book loan as it already has expired. Return the book instead.",
[LoanExtensionStatus.MembershipExpired] = "Cannot extend book loan due to expired patron's membership.",
[LoanExtensionStatus.LoanReturned] = "Cannot extend book loan as the book is already returned.",
[LoanExtensionStatus.Error] = "Cannot extend book loan due to an error."
};

private static readonly IReadOnlyDictionary<LoanReturnStatus, string> LoanReturnStatusDescriptions =
new Dictionary<LoanReturnStatus, string>
{
[LoanReturnStatus.Success] = "Book was successfully returned.",
[LoanReturnStatus.LoanNotFound] = "Loan not found.",
[LoanReturnStatus.AlreadyReturned] = "Cannot return book as the book is already returned.",
[LoanReturnStatus.Error] = "Cannot return book due to an error."
};

private static readonly IReadOnlyDictionary<MembershipRenewalStatus, string> MembershipRenewalStatusDescriptions =
new Dictionary<MembershipRenewalStatus, string>
{
[MembershipRenewalStatus.Success] = "Membership renewal was successful.",
[MembershipRenewalStatus.PatronNotFound] = "Patron not found.",
[MembershipRenewalStatus.TooEarlyToRenew] = "It is too early to renew the membership.",
[MembershipRenewalStatus.LoanNotReturned] = "Cannot renew membership due to an outstanding loan.",
[MembershipRenewalStatus.Error] = "Cannot renew membership due to an error."
};

public static string GetDescription(Enum value)
{
if (value == null)
return string.Empty;

FieldInfo fieldInfo = value.GetType().GetField(value.ToString())!;

DescriptionAttribute[] attributes =
(DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
return value switch
{
return value.ToString();
}
LoanExtensionStatus loanExtensionStatus when LoanExtensionStatusDescriptions.TryGetValue(loanExtensionStatus, out var extensionDescription)
=> extensionDescription,
LoanReturnStatus loanReturnStatus when LoanReturnStatusDescriptions.TryGetValue(loanReturnStatus, out var returnDescription)
=> returnDescription,
MembershipRenewalStatus membershipRenewalStatus when MembershipRenewalStatusDescriptions.TryGetValue(membershipRenewalStatus, out var membershipDescription)
=> membershipDescription,
_ => value.ToString()
};
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using System.Linq;
using System.Text.Json;
using Library.ApplicationCore.Entities;
using Microsoft.Extensions.Configuration;

Expand Down Expand Up @@ -97,108 +98,66 @@ public List<Patron> GetPopulatedPatrons(IEnumerable<Patron> patrons)

public Patron GetPopulatedPatron(Patron p)
{
Patron populated = new Patron
return new Patron
{
Id = p.Id,
Name = p.Name,
ImageName = p.ImageName,
MembershipStart = p.MembershipStart,
MembershipEnd = p.MembershipEnd,
Loans = new List<Loan>()
Loans = Loans?
.Where(loan => loan.PatronId == p.Id)
.Select(GetPopulatedLoan)
.ToList() ?? new List<Loan>()
};

foreach (Loan loan in Loans!)
{
if (loan.PatronId == p.Id)
{
populated.Loans.Add(GetPopulatedLoan(loan));
}
}

return populated;
}

public Loan GetPopulatedLoan(Loan l)
{
Loan populated = new Loan
return new Loan
{
Id = l.Id,
BookItemId = l.BookItemId,
PatronId = l.PatronId,
LoanDate = l.LoanDate,
DueDate = l.DueDate,
ReturnDate = l.ReturnDate
ReturnDate = l.ReturnDate,
BookItem = GetPopulatedBookItem(BookItems!.Single(bi => bi.Id == l.BookItemId)),
Patron = Patrons!.Single(p => p.Id == l.PatronId)
};

foreach (BookItem bi in BookItems!)
{
if (bi.Id == l.BookItemId)
{
populated.BookItem = GetPopulatedBookItem(bi);
break;
}
}

foreach (Patron p in Patrons!)
{
if (p.Id == l.PatronId)
{
populated.Patron = p;
break;
}
}

return populated;
}

public BookItem GetPopulatedBookItem(BookItem bi)
{
BookItem populated = new BookItem
return new BookItem
{
Id = bi.Id,
BookId = bi.BookId,
AcquisitionDate = bi.AcquisitionDate,
Condition = bi.Condition
Condition = bi.Condition,
Book = GetPopulatedBook(Books!.Single(b => b.Id == bi.BookId))
};

foreach (Book b in Books!)
{
if (b.Id == bi.BookId)
{
populated.Book = GetPopulatedBook(b);
break;
}
}

return populated;
}

public Book GetPopulatedBook(Book b)
{
Book populated = new Book
return new Book
{
Id = b.Id,
Title = b.Title,
AuthorId = b.AuthorId,
Genre = b.Genre,
ISBN = b.ISBN,
ImageName = b.ImageName
};

foreach (Author a in Authors!)
{
if (a.Id == b.AuthorId)
{
populated.Author = new Author
ImageName = b.ImageName,
Author = Authors!
.Where(a => a.Id == b.AuthorId)
.Select(a => new Author
{
Id = a.Id,
Name = a.Name
};
break;
}
}

return populated;
})
.First()
};
}

private async Task<T?> LoadJson<T>(string filePath)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,16 @@ public JsonLoanRepository(JsonData jsonData)
{
await _jsonData.EnsureDataLoaded();

foreach (Loan loan in _jsonData.Loans!)
{
if (loan.Id == id)
{
Loan populated = _jsonData.GetPopulatedLoan(loan);
return populated;
}
}
return null;
return _jsonData.Loans!
.Where(loan => loan.Id == id)
.Select(_jsonData.GetPopulatedLoan)
.FirstOrDefault();
}

public async Task UpdateLoan(Loan loan)
{
Loan? existingLoan = null;
foreach (Loan l in _jsonData.Loans!)
{
if (l.Id == loan.Id)
{
existingLoan = l;
break;
}
}
Loan? existingLoan = _jsonData.Loans!
.FirstOrDefault(l => l.Id == loan.Id);

if (existingLoan != null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Library.ApplicationCore;
using Library.ApplicationCore.Entities;
using System.Linq;

namespace Library.Infrastructure.Data;

Expand All @@ -16,15 +17,10 @@ public async Task<List<Patron>> SearchPatrons(string searchInput)
{
await _jsonData.EnsureDataLoaded();

List<Patron> searchResults = new List<Patron>();
foreach (Patron patron in _jsonData.Patrons)
{
if (patron.Name.Contains(searchInput))
{
searchResults.Add(patron);
}
}
searchResults.Sort((p1, p2) => String.Compare(p1.Name, p2.Name));
List<Patron> searchResults = _jsonData.Patrons!
.Where(patron => patron.Name.Contains(searchInput))
.OrderBy(patron => patron.Name)
.ToList();

searchResults = _jsonData.GetPopulatedPatrons(searchResults);

Expand All @@ -35,30 +31,19 @@ public async Task<List<Patron>> SearchPatrons(string searchInput)
{
await _jsonData.EnsureDataLoaded();

foreach (Patron patron in _jsonData.Patrons!)
{
if (patron.Id == id)
{
Patron populated = _jsonData.GetPopulatedPatron(patron);
return populated;
}
}
return null;
Patron? patron = _jsonData.Patrons!
.FirstOrDefault(p => p.Id == id);

return patron == null ? null : _jsonData.GetPopulatedPatron(patron);
}

public async Task UpdatePatron(Patron patron)
{
await _jsonData.EnsureDataLoaded();
var patrons = _jsonData.Patrons!;
Patron existingPatron = null;
foreach (var p in patrons)
{
if (p.Id == patron.Id)
{
existingPatron = p;
break;
}
}
Patron? existingPatron = patrons
.FirstOrDefault(p => p.Id == patron.Id);

if (existingPatron != null)
{
existingPatron.Name = patron.Name;
Expand Down
5 changes: 4 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Microsoft Lab Exercises
# Microsoft Github Copilot Lab Exercises
<!-- Change the title above as appropriate -->


This repo contains exercises and supporting files for Microsoft skilling content.



The exercises may be used in both self-paced skilling experiences on [Microsoft Learn](https://learn.microsoft.com) and in Microsoft authorized instructor-led training.
<!-- Update thr paragraph above with a link to a specific Learning Path or course as appropriate -->

Expand Down