Skip to content

Commit

Permalink
_logger + testing
Browse files Browse the repository at this point in the history
  • Loading branch information
BloodShop committed Nov 21, 2022
1 parent da974e0 commit 343487b
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 6 deletions.
16 changes: 14 additions & 2 deletions Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,25 @@ public class AccountController : Controller
readonly UserManager<IdentityUser> _userManager;
readonly SignInManager<IdentityUser> _signInManager;
readonly RoleManager<IdentityRole> _roleManager;
readonly ILogger<HomeController> _logger;

public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
RoleManager<IdentityRole> roleManager)
RoleManager<IdentityRole> roleManager,
ILogger<HomeController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
_logger = logger;
}

[HttpPost]
[Authorize]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation($"An account has logged out !!");
return RedirectToAction("Index", "Home");
}

Expand All @@ -39,8 +43,12 @@ public async Task<IActionResult> Login(LoginViewModel model)
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);

if (result.Succeeded)
{
_logger.LogInformation($"{model.UserName} has logged in !!");
return RedirectToAction("Index", "Home");

}

_logger.LogInformation($"!! Invalid Login Attempt username: {model.UserName}, pass:{model.Password}");
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
return View(model);
Expand All @@ -60,11 +68,15 @@ public async Task<IActionResult> Register(RegisterViewModel model)
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation($"New registration - username: {model.UserName}, pass: {model.Password}");
return RedirectToAction("Index", "Home");
}

foreach (var error in result.Errors)
{
_logger.LogError("!!" + error.Description);
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}
Expand Down
13 changes: 12 additions & 1 deletion Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ namespace PetShopProj.Controllers
{
public class HomeController : Controller
{
readonly ILogger _logger;
readonly IRepository _repo;
readonly IWebHostEnvironment _hostingEnvironment;

public HomeController(IRepository repository, IWebHostEnvironment hostingEnvironment)
public HomeController(IRepository repository, IWebHostEnvironment hostingEnvironment, ILogger<HomeController> logger)
{
_logger = logger;
_repo = repository;
_hostingEnvironment = hostingEnvironment;
}
Expand Down Expand Up @@ -54,7 +56,10 @@ public IActionResult Search(string text)
public IActionResult Animal(int id, string comment)
{
if (comment != null && comment != string.Empty)
{
_repo.AddComment(id, comment);
_logger.LogInformation("!! Attempted to add an empty comment");
}

return View(_repo.GetAnimal(id));
}
Expand Down Expand Up @@ -85,6 +90,7 @@ public IActionResult AddAnimal(AddAnimalViewModel model)
return RedirectToAction(nameof(Animal), new { id = newAnimal.Id });
}

_logger.LogError("!! Attempted to add an invalid image");
return View("InvalidImageError", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
}

Expand Down Expand Up @@ -134,6 +140,7 @@ public IActionResult EditAnimal(EditAnimalViewModel model)
return RedirectToAction(nameof(Animal), new { id = animal.Id });
}

_logger.LogError("!! Attempted to add an invalid image");
return View("InvalidImageError", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
}

Expand Down Expand Up @@ -180,7 +187,10 @@ public IActionResult ManageCategories(int id)
var category = _repo.GetCategoryById(id)!;

if (category.Animals!.Count != 0)
{
_logger.LogError("!! Attempted to remove category with animals.");
return View("RemoveCategoryError");
}

_repo.DeleteCategory(id);
return View(_repo.GetCategory());
Expand All @@ -200,6 +210,7 @@ public IActionResult AddCategory(AddCategoryViewModel model)
var newCategory = new Category { Name = model.Name };

_repo.AddCategory(newCategory);
_logger.LogInformation("A category has been added.");
return RedirectToAction(nameof(ManageCategories));
}
return View();
Expand Down
1 change: 1 addition & 0 deletions PetShopProj.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="6.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.10" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
</ItemGroup>

</Project>
8 changes: 7 additions & 1 deletion PetShopProj.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32929.385
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PetShopProj", "PetShopProj.csproj", "{1E0C46F0-F547-4C88-B39E-BC8E002A4FA0}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PetShopProj", "PetShopProj.csproj", "{1E0C46F0-F547-4C88-B39E-BC8E002A4FA0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PetShopProj.Tests", "..\PetShopProj.Tests\PetShopProj.Tests.csproj", "{F19177C5-9D5B-4C1C-9833-FE3BD1571C8E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -15,6 +17,10 @@ Global
{1E0C46F0-F547-4C88-B39E-BC8E002A4FA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1E0C46F0-F547-4C88-B39E-BC8E002A4FA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1E0C46F0-F547-4C88-B39E-BC8E002A4FA0}.Release|Any CPU.Build.0 = Release|Any CPU
{F19177C5-9D5B-4C1C-9833-FE3BD1571C8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F19177C5-9D5B-4C1C-9833-FE3BD1571C8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F19177C5-9D5B-4C1C-9833-FE3BD1571C8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F19177C5-9D5B-4C1C-9833-FE3BD1571C8E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
4 changes: 4 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
using Microsoft.EntityFrameworkCore;
using PetShopProj.Data;
using PetShopProj.Repositories;
using Serilog;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IRepository, PetRepository>();
builder.Host.UseSerilog((ctx, lc) =>
lc.ReadFrom.Configuration(ctx.Configuration));
string connectionString = builder.Configuration["ConnectionStrings:DefaultConnection"];
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDbContext<PetDbContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(connectionString));
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options =>
Expand Down
2 changes: 1 addition & 1 deletion Views/Home/Animal.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@
<input class="form-control" style="max-width: 400px" type="text" placeholder="Write your comment here" name="comment" />
@*asp-route-comment=""*@ <button class="btn btn-outline-secondary" asp-route-id="@Model.Id" type="submit" style="border-top-right-radius: 0.375rem; border-bottom-right-radius: 0.375rem">Add Comment</button>
</form>

@* <a class="btn btn-primary m-1" asp-action="BuyAnimal" asp-route-id="@Model.Id">Buy</a>
*@</section>
18 changes: 17 additions & 1 deletion appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,21 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"Serilog": {
"MinimumLevel": {
"Default": "Warning"
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "./log.txt"
}
}
]
}
}
2 changes: 2 additions & 0 deletions log.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
2022-11-21 09:58:19.720 +02:00 [WRN] Failed to determine the https port for redirect.
2022-11-21 09:58:36.490 +02:00 [ERR] !! Attempted to remove category with animals.

0 comments on commit 343487b

Please sign in to comment.