Included file scope namespaces for all files

This commit is contained in:
Sumit Ghosh 2021-10-20 16:04:59 +05:30
parent 610707a5b7
commit 5e7de1617e
47 changed files with 1299 additions and 1567 deletions

View File

@ -1,30 +1,29 @@
namespace Microsoft.eShopOnContainers.WebMVC namespace Microsoft.eShopOnContainers.WebMVC;
public class AppSettings
{ {
public class AppSettings //public Connectionstrings ConnectionStrings { get; set; }
{ public string PurchaseUrl { get; set; }
//public Connectionstrings ConnectionStrings { get; set; } public string SignalrHubUrl { get; set; }
public string PurchaseUrl { get; set; } public bool ActivateCampaignDetailFunction { get; set; }
public string SignalrHubUrl { get; set; } public Logging Logging { get; set; }
public bool ActivateCampaignDetailFunction { get; set; } public bool UseCustomizationData { get; set; }
public Logging Logging { get; set; } }
public bool UseCustomizationData { get; set; }
} public class Connectionstrings
{
public class Connectionstrings public string DefaultConnection { get; set; }
{ }
public string DefaultConnection { get; set; }
} public class Logging
{
public class Logging public bool IncludeScopes { get; set; }
{ public Loglevel LogLevel { get; set; }
public bool IncludeScopes { get; set; } }
public Loglevel LogLevel { get; set; }
} public class Loglevel
{
public class Loglevel public string Default { get; set; }
{ public string System { get; set; }
public string Default { get; set; } public string Microsoft { get; set; }
public string System { get; set; }
public string Microsoft { get; set; }
}
} }

View File

@ -1,53 +1,42 @@
using Microsoft.AspNetCore.Authentication; namespace Microsoft.eShopOnContainers.WebMVC.Controllers;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class AccountController : Controller
{ {
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] private readonly ILogger<AccountController> _logger;
public class AccountController : Controller
public AccountController(ILogger<AccountController> logger)
{ {
private readonly ILogger<AccountController> _logger; _logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public AccountController(ILogger<AccountController> logger) [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public async Task<IActionResult> SignIn(string returnUrl)
{
var user = User as ClaimsPrincipal;
var token = await HttpContext.GetTokenAsync("access_token");
_logger.LogInformation("----- User {@User} authenticated into {AppName}", user, Program.AppName);
if (token != null)
{ {
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); ViewData["access_token"] = token;
} }
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] // "Catalog" because UrlHelper doesn't support nameof() for controllers
public async Task<IActionResult> SignIn(string returnUrl) // https://github.com/aspnet/Mvc/issues/5853
{ return RedirectToAction(nameof(CatalogController.Index), "Catalog");
var user = User as ClaimsPrincipal; }
var token = await HttpContext.GetTokenAsync("access_token");
_logger.LogInformation("----- User {@User} authenticated into {AppName}", user, Program.AppName); public async Task<IActionResult> Signout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
if (token != null) // "Catalog" because UrlHelper doesn't support nameof() for controllers
{ // https://github.com/aspnet/Mvc/issues/5853
ViewData["access_token"] = token; var homeUrl = Url.Action(nameof(CatalogController.Index), "Catalog");
} return new SignOutResult(OpenIdConnectDefaults.AuthenticationScheme,
new AspNetCore.Authentication.AuthenticationProperties { RedirectUri = homeUrl });
// "Catalog" because UrlHelper doesn't support nameof() for controllers
// https://github.com/aspnet/Mvc/issues/5853
return RedirectToAction(nameof(CatalogController.Index), "Catalog");
}
public async Task<IActionResult> Signout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
// "Catalog" because UrlHelper doesn't support nameof() for controllers
// https://github.com/aspnet/Mvc/issues/5853
var homeUrl = Url.Action(nameof(CatalogController.Index), "Catalog");
return new SignOutResult(OpenIdConnectDefaults.AuthenticationScheme,
new AspNetCore.Authentication.AuthenticationProperties { RedirectUri = homeUrl });
}
} }
} }

View File

@ -1,89 +1,79 @@
using Microsoft.AspNetCore.Authentication.OpenIdConnect; namespace Microsoft.eShopOnContainers.WebMVC.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class CartController : Controller
{ {
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] private readonly IBasketService _basketSvc;
public class CartController : Controller private readonly ICatalogService _catalogSvc;
private readonly IIdentityParser<ApplicationUser> _appUserParser;
public CartController(IBasketService basketSvc, ICatalogService catalogSvc, IIdentityParser<ApplicationUser> appUserParser)
{ {
private readonly IBasketService _basketSvc; _basketSvc = basketSvc;
private readonly ICatalogService _catalogSvc; _catalogSvc = catalogSvc;
private readonly IIdentityParser<ApplicationUser> _appUserParser; _appUserParser = appUserParser;
}
public CartController(IBasketService basketSvc, ICatalogService catalogSvc, IIdentityParser<ApplicationUser> appUserParser) public async Task<IActionResult> Index()
{
try
{ {
_basketSvc = basketSvc; var user = _appUserParser.Parse(HttpContext.User);
_catalogSvc = catalogSvc; var vm = await _basketSvc.GetBasket(user);
_appUserParser = appUserParser;
return View(vm);
}
catch (Exception ex)
{
HandleException(ex);
} }
public async Task<IActionResult> Index() return View();
}
[HttpPost]
public async Task<IActionResult> Index(Dictionary<string, int> quantities, string action)
{
try
{ {
try var user = _appUserParser.Parse(HttpContext.User);
var basket = await _basketSvc.SetQuantities(user, quantities);
if (action == "[ Checkout ]")
{
return RedirectToAction("Create", "Order");
}
}
catch (Exception ex)
{
HandleException(ex);
}
return View();
}
public async Task<IActionResult> AddToCart(CatalogItem productDetails)
{
try
{
if (productDetails?.Id != null)
{ {
var user = _appUserParser.Parse(HttpContext.User); var user = _appUserParser.Parse(HttpContext.User);
var vm = await _basketSvc.GetBasket(user); await _basketSvc.AddItemToBasket(user, productDetails.Id);
return View(vm);
} }
catch (Exception ex) return RedirectToAction("Index", "Catalog");
{
HandleException(ex);
}
return View();
} }
catch (Exception ex)
[HttpPost]
public async Task<IActionResult> Index(Dictionary<string, int> quantities, string action)
{ {
try // Catch error when Basket.api is in circuit-opened mode
{ HandleException(ex);
var user = _appUserParser.Parse(HttpContext.User);
var basket = await _basketSvc.SetQuantities(user, quantities);
if (action == "[ Checkout ]")
{
return RedirectToAction("Create", "Order");
}
}
catch (Exception ex)
{
HandleException(ex);
}
return View();
} }
public async Task<IActionResult> AddToCart(CatalogItem productDetails) return RedirectToAction("Index", "Catalog", new { errorMsg = ViewBag.BasketInoperativeMsg });
{ }
try
{
if (productDetails?.Id != null)
{
var user = _appUserParser.Parse(HttpContext.User);
await _basketSvc.AddItemToBasket(user, productDetails.Id);
}
return RedirectToAction("Index", "Catalog");
}
catch (Exception ex)
{
// Catch error when Basket.api is in circuit-opened mode
HandleException(ex);
}
return RedirectToAction("Index", "Catalog", new { errorMsg = ViewBag.BasketInoperativeMsg }); private void HandleException(Exception ex)
} {
ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative {ex.GetType().Name} - {ex.Message}";
private void HandleException(Exception ex)
{
ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative {ex.GetType().Name} - {ex.Message}";
}
} }
} }

View File

@ -1,45 +1,37 @@
using Microsoft.AspNetCore.Mvc; namespace Microsoft.eShopOnContainers.WebMVC.Controllers;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers public class CatalogController : Controller
{ {
public class CatalogController : Controller private ICatalogService _catalogSvc;
public CatalogController(ICatalogService catalogSvc) =>
_catalogSvc = catalogSvc;
public async Task<IActionResult> Index(int? BrandFilterApplied, int? TypesFilterApplied, int? page, [FromQuery] string errorMsg)
{ {
private ICatalogService _catalogSvc; var itemsPage = 9;
var catalog = await _catalogSvc.GetCatalogItems(page ?? 0, itemsPage, BrandFilterApplied, TypesFilterApplied);
public CatalogController(ICatalogService catalogSvc) => var vm = new IndexViewModel()
_catalogSvc = catalogSvc;
public async Task<IActionResult> Index(int? BrandFilterApplied, int? TypesFilterApplied, int? page, [FromQuery] string errorMsg)
{ {
var itemsPage = 9; CatalogItems = catalog.Data,
var catalog = await _catalogSvc.GetCatalogItems(page ?? 0, itemsPage, BrandFilterApplied, TypesFilterApplied); Brands = await _catalogSvc.GetBrands(),
var vm = new IndexViewModel() Types = await _catalogSvc.GetTypes(),
BrandFilterApplied = BrandFilterApplied ?? 0,
TypesFilterApplied = TypesFilterApplied ?? 0,
PaginationInfo = new PaginationInfo()
{ {
CatalogItems = catalog.Data, ActualPage = page ?? 0,
Brands = await _catalogSvc.GetBrands(), ItemsPerPage = catalog.Data.Count,
Types = await _catalogSvc.GetTypes(), TotalItems = catalog.Count,
BrandFilterApplied = BrandFilterApplied ?? 0, TotalPages = (int)Math.Ceiling(((decimal)catalog.Count / itemsPage))
TypesFilterApplied = TypesFilterApplied ?? 0, }
PaginationInfo = new PaginationInfo() };
{
ActualPage = page ?? 0,
ItemsPerPage = catalog.Data.Count,
TotalItems = catalog.Count,
TotalPages = (int)Math.Ceiling(((decimal)catalog.Count / itemsPage))
}
};
vm.PaginationInfo.Next = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : ""; vm.PaginationInfo.Next = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : ""; vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
ViewBag.BasketInoperativeMsg = errorMsg; ViewBag.BasketInoperativeMsg = errorMsg;
return View(vm); return View(vm);
}
} }
} }

View File

@ -1,9 +1,6 @@
using Microsoft.AspNetCore.Mvc; namespace WebMVC.Controllers;
namespace WebMVC.Controllers public class ErrorController : Controller
{ {
public class ErrorController : Controller public IActionResult Error() => View();
{
public IActionResult Error() => View();
}
} }

View File

@ -1,82 +1,75 @@
using Microsoft.AspNetCore.Authentication.OpenIdConnect; namespace Microsoft.eShopOnContainers.WebMVC.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class OrderController : Controller
{ {
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] private IOrderingService _orderSvc;
public class OrderController : Controller private IBasketService _basketSvc;
private readonly IIdentityParser<ApplicationUser> _appUserParser;
public OrderController(IOrderingService orderSvc, IBasketService basketSvc, IIdentityParser<ApplicationUser> appUserParser)
{ {
private IOrderingService _orderSvc; _appUserParser = appUserParser;
private IBasketService _basketSvc; _orderSvc = orderSvc;
private readonly IIdentityParser<ApplicationUser> _appUserParser; _basketSvc = basketSvc;
public OrderController(IOrderingService orderSvc, IBasketService basketSvc, IIdentityParser<ApplicationUser> appUserParser)
{
_appUserParser = appUserParser;
_orderSvc = orderSvc;
_basketSvc = basketSvc;
}
public async Task<IActionResult> Create()
{
var user = _appUserParser.Parse(HttpContext.User);
var order = await _basketSvc.GetOrderDraft(user.Id);
var vm = _orderSvc.MapUserInfoIntoOrder(user, order);
vm.CardExpirationShortFormat();
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Checkout(Order model)
{
try
{
if (ModelState.IsValid)
{
var user = _appUserParser.Parse(HttpContext.User);
var basket = _orderSvc.MapOrderToBasket(model);
await _basketSvc.Checkout(basket);
//Redirect to historic list.
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
ModelState.AddModelError("Error", $"It was not possible to create a new order, please try later on ({ex.GetType().Name} - {ex.Message})");
}
return View("Create", model);
}
public async Task<IActionResult> Cancel(string orderId)
{
await _orderSvc.CancelOrder(orderId);
//Redirect to historic list.
return RedirectToAction("Index");
}
public async Task<IActionResult> Detail(string orderId)
{
var user = _appUserParser.Parse(HttpContext.User);
var order = await _orderSvc.GetOrder(user, orderId);
return View(order);
}
public async Task<IActionResult> Index(Order item)
{
var user = _appUserParser.Parse(HttpContext.User);
var vm = await _orderSvc.GetMyOrders(user);
return View(vm);
}
} }
}
public async Task<IActionResult> Create()
{
var user = _appUserParser.Parse(HttpContext.User);
var order = await _basketSvc.GetOrderDraft(user.Id);
var vm = _orderSvc.MapUserInfoIntoOrder(user, order);
vm.CardExpirationShortFormat();
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Checkout(Order model)
{
try
{
if (ModelState.IsValid)
{
var user = _appUserParser.Parse(HttpContext.User);
var basket = _orderSvc.MapOrderToBasket(model);
await _basketSvc.Checkout(basket);
//Redirect to historic list.
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
ModelState.AddModelError("Error", $"It was not possible to create a new order, please try later on ({ex.GetType().Name} - {ex.Message})");
}
return View("Create", model);
}
public async Task<IActionResult> Cancel(string orderId)
{
await _orderSvc.CancelOrder(orderId);
//Redirect to historic list.
return RedirectToAction("Index");
}
public async Task<IActionResult> Detail(string orderId)
{
var user = _appUserParser.Parse(HttpContext.User);
var order = await _orderSvc.GetOrder(user, orderId);
return View(order);
}
public async Task<IActionResult> Index(Order item)
{
var user = _appUserParser.Parse(HttpContext.User);
var vm = await _orderSvc.GetMyOrders(user);
return View(vm);
}
}

View File

@ -1,41 +1,32 @@
using Microsoft.AspNetCore.Authentication.OpenIdConnect; namespace WebMVC.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Threading.Tasks;
using WebMVC.Services.ModelDTOs;
namespace WebMVC.Controllers [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class OrderManagementController : Controller
{ {
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] private IOrderingService _orderSvc;
public class OrderManagementController : Controller private readonly IIdentityParser<ApplicationUser> _appUserParser;
public OrderManagementController(IOrderingService orderSvc, IIdentityParser<ApplicationUser> appUserParser)
{ {
private IOrderingService _orderSvc; _appUserParser = appUserParser;
private readonly IIdentityParser<ApplicationUser> _appUserParser; _orderSvc = orderSvc;
public OrderManagementController(IOrderingService orderSvc, IIdentityParser<ApplicationUser> appUserParser) }
public async Task<IActionResult> Index()
{
var user = _appUserParser.Parse(HttpContext.User);
var vm = await _orderSvc.GetMyOrders(user);
return View(vm);
}
[HttpPost]
public async Task<IActionResult> OrderProcess(string orderId, string actionCode)
{
if (OrderProcessAction.Ship.Code == actionCode)
{ {
_appUserParser = appUserParser; await _orderSvc.ShipOrder(orderId);
_orderSvc = orderSvc;
} }
public async Task<IActionResult> Index() return RedirectToAction("Index");
{
var user = _appUserParser.Parse(HttpContext.User);
var vm = await _orderSvc.GetMyOrders(user);
return View(vm);
}
[HttpPost]
public async Task<IActionResult> OrderProcess(string orderId, string actionCode)
{
if (OrderProcessAction.Ship.Code == actionCode)
{
await _orderSvc.ShipOrder(orderId);
}
return RedirectToAction("Index");
}
} }
} }

View File

@ -1,61 +1,52 @@
using Microsoft.AspNetCore.Authorization; namespace WebMVC.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace WebMVC.Controllers class TestPayload
{ {
class TestPayload public int CatalogItemId { get; set; }
public string BasketId { get; set; }
public int Quantity { get; set; }
}
[Authorize]
public class TestController : Controller
{
private readonly IHttpClientFactory _client;
private readonly IIdentityParser<ApplicationUser> _appUserParser;
public TestController(IHttpClientFactory client, IIdentityParser<ApplicationUser> identityParser)
{ {
public int CatalogItemId { get; set; } _client = client;
_appUserParser = identityParser;
public string BasketId { get; set; }
public int Quantity { get; set; }
} }
[Authorize] public async Task<IActionResult> Ocelot()
public class TestController : Controller
{ {
private readonly IHttpClientFactory _client; var url = "http://apigw/shopping/api/v1/basket/items";
private readonly IIdentityParser<ApplicationUser> _appUserParser;
public TestController(IHttpClientFactory client, IIdentityParser<ApplicationUser> identityParser) var payload = new TestPayload()
{ {
_client = client; CatalogItemId = 1,
_appUserParser = identityParser; Quantity = 1,
BasketId = _appUserParser.Parse(User).Id
};
var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");
var response = await _client.CreateClient(nameof(IBasketService))
.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var str = await response.Content.ReadAsStringAsync();
return Ok(str);
} }
else
public async Task<IActionResult> Ocelot()
{ {
var url = "http://apigw/shopping/api/v1/basket/items"; return Ok(new { response.StatusCode, response.ReasonPhrase });
var payload = new TestPayload()
{
CatalogItemId = 1,
Quantity = 1,
BasketId = _appUserParser.Parse(User).Id
};
var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");
var response = await _client.CreateClient(nameof(IBasketService))
.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var str = await response.Content.ReadAsStringAsync();
return Ok(str);
}
else
{
return Ok(new { response.StatusCode, response.ReasonPhrase });
}
} }
} }
} }

View File

@ -1,35 +1,28 @@
using System; namespace Microsoft.eShopOnContainers.WebMVC.Extensions;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace Microsoft.eShopOnContainers.WebMVC.Extensions public static class HttpClientExtensions
{ {
public static class HttpClientExtensions public static void SetBasicAuthentication(this HttpClient client, string userName, string password) =>
client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(userName, password);
public static void SetToken(this HttpClient client, string scheme, string token) =>
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme, token);
public static void SetBearerToken(this HttpClient client, string token) =>
client.SetToken(JwtConstants.TokenType, token);
}
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{ {
public static void SetBasicAuthentication(this HttpClient client, string userName, string password) => Encoding encoding = Encoding.GetEncoding("iso-8859-1");
client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(userName, password); string credential = String.Format("{0}:{1}", userName, password);
public static void SetToken(this HttpClient client, string scheme, string token) => return Convert.ToBase64String(encoding.GetBytes(credential));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme, token);
public static void SetBearerToken(this HttpClient client, string token) =>
client.SetToken(JwtConstants.TokenType, token);
}
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
} }
} }

View File

@ -1,8 +1,4 @@
using Microsoft.AspNetCore.Http; public static class SessionExtensions
using System.Text.Json;
public static class SessionExtensions
{ {
public static void SetObject(this ISession session, string key, object value) => public static void SetObject(this ISession session, string key, object value) =>
session.SetString(key,JsonSerializer.Serialize(value)); session.SetString(key,JsonSerializer.Serialize(value));

View File

@ -1,86 +1,85 @@
namespace WebMVC.Infrastructure namespace WebMVC.Infrastructure;
public static class API
{ {
public static class API
public static class Purchase
{ {
public static string AddItemToBasket(string baseUri) => $"{baseUri}/basket/items";
public static string UpdateBasketItem(string baseUri) => $"{baseUri}/basket/items";
public static class Purchase public static string GetOrderDraft(string baseUri, string basketId) => $"{baseUri}/order/draft/{basketId}";
}
public static class Basket
{
public static string GetBasket(string baseUri, string basketId) => $"{baseUri}/{basketId}";
public static string UpdateBasket(string baseUri) => baseUri;
public static string CheckoutBasket(string baseUri) => $"{baseUri}/checkout";
public static string CleanBasket(string baseUri, string basketId) => $"{baseUri}/{basketId}";
}
public static class Order
{
public static string GetOrder(string baseUri, string orderId)
{ {
public static string AddItemToBasket(string baseUri) => $"{baseUri}/basket/items"; return $"{baseUri}/{orderId}";
public static string UpdateBasketItem(string baseUri) => $"{baseUri}/basket/items";
public static string GetOrderDraft(string baseUri, string basketId) => $"{baseUri}/order/draft/{basketId}";
} }
public static class Basket public static string GetAllMyOrders(string baseUri)
{ {
public static string GetBasket(string baseUri, string basketId) => $"{baseUri}/{basketId}"; return baseUri;
public static string UpdateBasket(string baseUri) => baseUri;
public static string CheckoutBasket(string baseUri) => $"{baseUri}/checkout";
public static string CleanBasket(string baseUri, string basketId) => $"{baseUri}/{basketId}";
} }
public static class Order public static string AddNewOrder(string baseUri)
{ {
public static string GetOrder(string baseUri, string orderId) return $"{baseUri}/new";
{
return $"{baseUri}/{orderId}";
}
public static string GetAllMyOrders(string baseUri)
{
return baseUri;
}
public static string AddNewOrder(string baseUri)
{
return $"{baseUri}/new";
}
public static string CancelOrder(string baseUri)
{
return $"{baseUri}/cancel";
}
public static string ShipOrder(string baseUri)
{
return $"{baseUri}/ship";
}
} }
public static class Catalog public static string CancelOrder(string baseUri)
{ {
public static string GetAllCatalogItems(string baseUri, int page, int take, int? brand, int? type) return $"{baseUri}/cancel";
{ }
var filterQs = "";
if (type.HasValue) public static string ShipOrder(string baseUri)
{ {
var brandQs = (brand.HasValue) ? brand.Value.ToString() : string.Empty; return $"{baseUri}/ship";
filterQs = $"/type/{type.Value}/brand/{brandQs}";
}
else if (brand.HasValue)
{
var brandQs = (brand.HasValue) ? brand.Value.ToString() : string.Empty;
filterQs = $"/type/all/brand/{brandQs}";
}
else
{
filterQs = string.Empty;
}
return $"{baseUri}items{filterQs}?pageIndex={page}&pageSize={take}";
}
public static string GetAllBrands(string baseUri)
{
return $"{baseUri}catalogBrands";
}
public static string GetAllTypes(string baseUri)
{
return $"{baseUri}catalogTypes";
}
} }
} }
}
public static class Catalog
{
public static string GetAllCatalogItems(string baseUri, int page, int take, int? brand, int? type)
{
var filterQs = "";
if (type.HasValue)
{
var brandQs = (brand.HasValue) ? brand.Value.ToString() : string.Empty;
filterQs = $"/type/{type.Value}/brand/{brandQs}";
}
else if (brand.HasValue)
{
var brandQs = (brand.HasValue) ? brand.Value.ToString() : string.Empty;
filterQs = $"/type/all/brand/{brandQs}";
}
else
{
filterQs = string.Empty;
}
return $"{baseUri}items{filterQs}?pageIndex={page}&pageSize={take}";
}
public static string GetAllBrands(string baseUri)
{
return $"{baseUri}catalogBrands";
}
public static string GetAllTypes(string baseUri)
{
return $"{baseUri}catalogTypes";
}
}
}

View File

@ -1,49 +1,40 @@
using Microsoft.AspNetCore.Authentication; namespace WebMVC.Infrastructure;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace WebMVC.Infrastructure public class HttpClientAuthorizationDelegatingHandler
: DelegatingHandler
{ {
public class HttpClientAuthorizationDelegatingHandler private readonly IHttpContextAccessor _httpContextAccessor;
: DelegatingHandler
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
{ {
private readonly IHttpContextAccessor _httpContextAccessor; _httpContextAccessor = httpContextAccessor;
}
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor) protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authorizationHeader = _httpContextAccessor.HttpContext
.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authorizationHeader))
{ {
_httpContextAccessor = httpContextAccessor; request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
} }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) var token = await GetToken();
if (token != null)
{ {
var authorizationHeader = _httpContextAccessor.HttpContext request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authorizationHeader))
{
request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
}
var token = await GetToken();
if (token != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
return await base.SendAsync(request, cancellationToken);
} }
async Task<string> GetToken() return await base.SendAsync(request, cancellationToken);
{ }
const string ACCESS_TOKEN = "access_token";
return await _httpContextAccessor.HttpContext async Task<string> GetToken()
.GetTokenAsync(ACCESS_TOKEN); {
} const string ACCESS_TOKEN = "access_token";
return await _httpContextAccessor.HttpContext
.GetTokenAsync(ACCESS_TOKEN);
} }
} }

View File

@ -1,29 +1,23 @@
using System; namespace WebMVC.Infrastructure;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WebMVC.Infrastructure public class HttpClientRequestIdDelegatingHandler
: DelegatingHandler
{ {
public class HttpClientRequestIdDelegatingHandler
: DelegatingHandler public HttpClientRequestIdDelegatingHandler()
{ {
public HttpClientRequestIdDelegatingHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Post || request.Method == HttpMethod.Put)
{
if (!request.Headers.Contains("x-requestid"))
{
request.Headers.Add("x-requestid", Guid.NewGuid().ToString());
}
}
return await base.SendAsync(request, cancellationToken);
}
} }
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Post || request.Method == HttpMethod.Put)
{
if (!request.Headers.Contains("x-requestid"))
{
request.Headers.Add("x-requestid", Guid.NewGuid().ToString());
}
}
return await base.SendAsync(request, cancellationToken);
}
}

View File

@ -1,97 +1,85 @@
using Microsoft.AspNetCore.Builder; namespace WebMVC.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.eShopOnContainers.WebMVC;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Serilog; using Serilog;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace WebMVC.Infrastructure public class WebContextSeed
{ {
public class WebContextSeed public static void Seed(IApplicationBuilder applicationBuilder, IWebHostEnvironment env)
{ {
public static void Seed(IApplicationBuilder applicationBuilder, IWebHostEnvironment env) var log = Serilog.Log.Logger;
var settings = (AppSettings)applicationBuilder
.ApplicationServices.GetRequiredService<IOptions<AppSettings>>().Value;
var useCustomizationData = settings.UseCustomizationData;
var contentRootPath = env.ContentRootPath;
var webroot = env.WebRootPath;
if (useCustomizationData)
{ {
var log = Serilog.Log.Logger; GetPreconfiguredImages(contentRootPath, webroot, log);
var settings = (AppSettings)applicationBuilder GetPreconfiguredCSS(contentRootPath, webroot, log);
.ApplicationServices.GetRequiredService<IOptions<AppSettings>>().Value;
var useCustomizationData = settings.UseCustomizationData;
var contentRootPath = env.ContentRootPath;
var webroot = env.WebRootPath;
if (useCustomizationData)
{
GetPreconfiguredImages(contentRootPath, webroot, log);
GetPreconfiguredCSS(contentRootPath, webroot, log);
}
} }
}
static void GetPreconfiguredCSS(string contentRootPath, string webroot, Serilog.ILogger log) static void GetPreconfiguredCSS(string contentRootPath, string webroot, ILogger log)
{
try
{ {
try string overrideCssFile = Path.Combine(contentRootPath, "Setup", "override.css");
if (!File.Exists(overrideCssFile))
{ {
string overrideCssFile = Path.Combine(contentRootPath, "Setup", "override.css"); log.Error("Override css file '{FileName}' does not exists.", overrideCssFile);
if (!File.Exists(overrideCssFile)) return;
{ }
log.Error("Override css file '{FileName}' does not exists.", overrideCssFile);
return;
}
string destinationFilename = Path.Combine(webroot, "css", "override.css"); string destinationFilename = Path.Combine(webroot, "css", "override.css");
File.Copy(overrideCssFile, destinationFilename, true); File.Copy(overrideCssFile, destinationFilename, true);
}
catch (Exception ex)
{
log.Error(ex, "EXCEPTION ERROR: {Message}", ex.Message);
}
} }
catch (Exception ex)
static void GetPreconfiguredImages(string contentRootPath, string webroot, Serilog.ILogger log)
{ {
try log.Error(ex, "EXCEPTION ERROR: {Message}", ex.Message);
}
}
static void GetPreconfiguredImages(string contentRootPath, string webroot, ILogger log)
{
try
{
string imagesZipFile = Path.Combine(contentRootPath, "Setup", "images.zip");
if (!File.Exists(imagesZipFile))
{ {
string imagesZipFile = Path.Combine(contentRootPath, "Setup", "images.zip"); log.Error("Zip file '{ZipFileName}' does not exists.", imagesZipFile);
if (!File.Exists(imagesZipFile)) return;
{ }
log.Error("Zip file '{ZipFileName}' does not exists.", imagesZipFile);
return;
}
string imagePath = Path.Combine(webroot, "images"); string imagePath = Path.Combine(webroot, "images");
string[] imageFiles = Directory.GetFiles(imagePath).Select(file => Path.GetFileName(file)).ToArray(); string[] imageFiles = Directory.GetFiles(imagePath).Select(file => Path.GetFileName(file)).ToArray();
using (ZipArchive zip = ZipFile.Open(imagesZipFile, ZipArchiveMode.Read)) using (ZipArchive zip = ZipFile.Open(imagesZipFile, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in zip.Entries)
{ {
foreach (ZipArchiveEntry entry in zip.Entries) if (imageFiles.Contains(entry.Name))
{ {
if (imageFiles.Contains(entry.Name)) string destinationFilename = Path.Combine(imagePath, entry.Name);
if (File.Exists(destinationFilename))
{ {
string destinationFilename = Path.Combine(imagePath, entry.Name); File.Delete(destinationFilename);
if (File.Exists(destinationFilename))
{
File.Delete(destinationFilename);
}
entry.ExtractToFile(destinationFilename);
}
else
{
log.Warning("Skipped file '{FileName}' in zipfile '{ZipFileName}'", entry.Name, imagesZipFile);
} }
entry.ExtractToFile(destinationFilename);
}
else
{
log.Warning("Skipped file '{FileName}' in zipfile '{ZipFileName}'", entry.Name, imagesZipFile);
} }
} }
} }
catch (Exception ex)
{
log.Error(ex, "EXCEPTION ERROR: {Message}", ex.Message);
}
} }
catch (Exception ex)
{
log.Error(ex, "EXCEPTION ERROR: {Message}", ex.Message);
}
} }
} }

View File

@ -1,13 +1,4 @@
using Microsoft.AspNetCore; var configuration = GetConfiguration();
using Microsoft.AspNetCore.Hosting;
using Microsoft.eShopOnContainers.WebMVC;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.IO;
var configuration = GetConfiguration();
Log.Logger = CreateSerilogLogger(configuration); Log.Logger = CreateSerilogLogger(configuration);

View File

@ -1,130 +1,120 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services using Microsoft.eShopOnContainers.WebMVC.ViewModels;
public class BasketService : IBasketService
{ {
public class BasketService : IBasketService private readonly IOptions<AppSettings> _settings;
private readonly HttpClient _apiClient;
private readonly ILogger<BasketService> _logger;
private readonly string _basketByPassUrl;
private readonly string _purchaseUrl;
public BasketService(HttpClient httpClient, IOptions<AppSettings> settings, ILogger<BasketService> logger)
{ {
private readonly IOptions<AppSettings> _settings; _apiClient = httpClient;
private readonly HttpClient _apiClient; _settings = settings;
private readonly ILogger<BasketService> _logger; _logger = logger;
private readonly string _basketByPassUrl;
private readonly string _purchaseUrl;
public BasketService(HttpClient httpClient, IOptions<AppSettings> settings, ILogger<BasketService> logger) _basketByPassUrl = $"{_settings.Value.PurchaseUrl}/b/api/v1/basket";
{ _purchaseUrl = $"{_settings.Value.PurchaseUrl}/api/v1";
_apiClient = httpClient; }
_settings = settings;
_logger = logger;
_basketByPassUrl = $"{_settings.Value.PurchaseUrl}/b/api/v1/basket"; public async Task<Basket> GetBasket(ApplicationUser user)
_purchaseUrl = $"{_settings.Value.PurchaseUrl}/api/v1"; {
} var uri = API.Basket.GetBasket(_basketByPassUrl, user.Id);
_logger.LogDebug("[GetBasket] -> Calling {Uri} to get the basket", uri);
var response = await _apiClient.GetAsync(uri);
_logger.LogDebug("[GetBasket] -> response code {StatusCode}", response.StatusCode);
var responseString = await response.Content.ReadAsStringAsync();
return string.IsNullOrEmpty(responseString) ?
new Basket() { BuyerId = user.Id } :
JsonSerializer.Deserialize<Basket>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<Basket> GetBasket(ApplicationUser user) public async Task<Basket> UpdateBasket(Basket basket)
{ {
var uri = API.Basket.GetBasket(_basketByPassUrl, user.Id); var uri = API.Basket.UpdateBasket(_basketByPassUrl);
_logger.LogDebug("[GetBasket] -> Calling {Uri} to get the basket", uri);
var response = await _apiClient.GetAsync(uri);
_logger.LogDebug("[GetBasket] -> response code {StatusCode}", response.StatusCode);
var responseString = await response.Content.ReadAsStringAsync();
return string.IsNullOrEmpty(responseString) ?
new Basket() { BuyerId = user.Id } :
JsonSerializer.Deserialize<Basket>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<Basket> UpdateBasket(Basket basket) var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
{
var uri = API.Basket.UpdateBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json"); var response = await _apiClient.PostAsync(uri, basketContent);
var response = await _apiClient.PostAsync(uri, basketContent); response.EnsureSuccessStatusCode();
response.EnsureSuccessStatusCode(); return basket;
}
return basket; public async Task Checkout(BasketDTO basket)
} {
var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
public async Task Checkout(BasketDTO basket) var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
{
var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
_logger.LogInformation("Uri chechout {uri}", uri); _logger.LogInformation("Uri chechout {uri}", uri);
var response = await _apiClient.PostAsync(uri, basketContent); var response = await _apiClient.PostAsync(uri, basketContent);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
public async Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities) public async Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities)
{
var uri = API.Purchase.UpdateBasketItem(_purchaseUrl);
var basketUpdate = new
{ {
var uri = API.Purchase.UpdateBasketItem(_purchaseUrl); BasketId = user.Id,
Updates = quantities.Select(kvp => new
var basketUpdate = new
{ {
BasketId = user.Id, BasketItemId = kvp.Key,
Updates = quantities.Select(kvp => new NewQty = kvp.Value
{ }).ToArray()
BasketItemId = kvp.Key, };
NewQty = kvp.Value
}).ToArray()
};
var basketContent = new StringContent(JsonSerializer.Serialize(basketUpdate), System.Text.Encoding.UTF8, "application/json"); var basketContent = new StringContent(JsonSerializer.Serialize(basketUpdate), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PutAsync(uri, basketContent); var response = await _apiClient.PutAsync(uri, basketContent);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<Basket>(jsonResponse, new JsonSerializerOptions return JsonSerializer.Deserialize<Basket>(jsonResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<Order> GetOrderDraft(string basketId)
{ {
var uri = API.Purchase.GetOrderDraft(_purchaseUrl, basketId); PropertyNameCaseInsensitive = true
});
}
var responseString = await _apiClient.GetStringAsync(uri); public async Task<Order> GetOrderDraft(string basketId)
{
var uri = API.Purchase.GetOrderDraft(_purchaseUrl, basketId);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions var responseString = await _apiClient.GetStringAsync(uri);
{
PropertyNameCaseInsensitive = true
});
return response; var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
}
public async Task AddItemToBasket(ApplicationUser user, int productId)
{ {
var uri = API.Purchase.AddItemToBasket(_purchaseUrl); PropertyNameCaseInsensitive = true
});
var newItem = new return response;
{ }
CatalogItemId = productId,
BasketId = user.Id,
Quantity = 1
};
var basketContent = new StringContent(JsonSerializer.Serialize(newItem), System.Text.Encoding.UTF8, "application/json"); public async Task AddItemToBasket(ApplicationUser user, int productId)
{
var uri = API.Purchase.AddItemToBasket(_purchaseUrl);
var response = await _apiClient.PostAsync(uri, basketContent); var newItem = new
} {
CatalogItemId = productId,
BasketId = user.Id,
Quantity = 1
};
var basketContent = new StringContent(JsonSerializer.Serialize(newItem), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, basketContent);
} }
} }

View File

@ -1,91 +1,80 @@
using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services public class CatalogService : ICatalogService
{ {
public class CatalogService : ICatalogService private readonly IOptions<AppSettings> _settings;
private readonly HttpClient _httpClient;
private readonly ILogger<CatalogService> _logger;
private readonly string _remoteServiceBaseUrl;
public CatalogService(HttpClient httpClient, ILogger<CatalogService> logger, IOptions<AppSettings> settings)
{ {
private readonly IOptions<AppSettings> _settings; _httpClient = httpClient;
private readonly HttpClient _httpClient; _settings = settings;
private readonly ILogger<CatalogService> _logger; _logger = logger;
private readonly string _remoteServiceBaseUrl; _remoteServiceBaseUrl = $"{_settings.Value.PurchaseUrl}/c/api/v1/catalog/";
}
public CatalogService(HttpClient httpClient, ILogger<CatalogService> logger, IOptions<AppSettings> settings) public async Task<Catalog> GetCatalogItems(int page, int take, int? brand, int? type)
{
var uri = API.Catalog.GetAllCatalogItems(_remoteServiceBaseUrl, page, take, brand, type);
var responseString = await _httpClient.GetStringAsync(uri);
var catalog = JsonSerializer.Deserialize<Catalog>(responseString, new JsonSerializerOptions
{ {
_httpClient = httpClient; PropertyNameCaseInsensitive = true
_settings = settings; });
_logger = logger;
_remoteServiceBaseUrl = $"{_settings.Value.PurchaseUrl}/c/api/v1/catalog/"; return catalog;
} }
public async Task<Catalog> GetCatalogItems(int page, int take, int? brand, int? type) public async Task<IEnumerable<SelectListItem>> GetBrands()
{
var uri = API.Catalog.GetAllBrands(_remoteServiceBaseUrl);
var responseString = await _httpClient.GetStringAsync(uri);
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var brands = JsonDocument.Parse(responseString);
foreach (JsonElement brand in brands.RootElement.EnumerateArray())
{ {
var uri = API.Catalog.GetAllCatalogItems(_remoteServiceBaseUrl, page, take, brand, type); items.Add(new SelectListItem()
var responseString = await _httpClient.GetStringAsync(uri);
var catalog = JsonSerializer.Deserialize<Catalog>(responseString, new JsonSerializerOptions
{ {
PropertyNameCaseInsensitive = true Value = brand.GetProperty("id").ToString(),
Text = brand.GetProperty("brand").ToString()
}); });
return catalog;
} }
public async Task<IEnumerable<SelectListItem>> GetBrands() return items;
{ }
var uri = API.Catalog.GetAllBrands(_remoteServiceBaseUrl);
var responseString = await _httpClient.GetStringAsync(uri); public async Task<IEnumerable<SelectListItem>> GetTypes()
{
var uri = API.Catalog.GetAllTypes(_remoteServiceBaseUrl);
var items = new List<SelectListItem>(); var responseString = await _httpClient.GetStringAsync(uri);
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true }); var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var brands = JsonDocument.Parse(responseString); using var catalogTypes = JsonDocument.Parse(responseString);
foreach (JsonElement brand in brands.RootElement.EnumerateArray()) foreach (JsonElement catalogType in catalogTypes.RootElement.EnumerateArray())
{
items.Add(new SelectListItem()
{
Value = brand.GetProperty("id").ToString(),
Text = brand.GetProperty("brand").ToString()
});
}
return items;
}
public async Task<IEnumerable<SelectListItem>> GetTypes()
{ {
var uri = API.Catalog.GetAllTypes(_remoteServiceBaseUrl); items.Add(new SelectListItem()
var responseString = await _httpClient.GetStringAsync(uri);
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var catalogTypes = JsonDocument.Parse(responseString);
foreach (JsonElement catalogType in catalogTypes.RootElement.EnumerateArray())
{ {
items.Add(new SelectListItem() Value = catalogType.GetProperty("id").ToString(),
{ Text = catalogType.GetProperty("type").ToString()
Value = catalogType.GetProperty("id").ToString(), });
Text = catalogType.GetProperty("type").ToString()
});
}
return items;
} }
return items;
} }
} }

View File

@ -1,17 +1,13 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebMVC.Services.ModelDTOs;
namespace Microsoft.eShopOnContainers.WebMVC.Services using Microsoft.eShopOnContainers.WebMVC.ViewModels;
public interface IBasketService
{ {
public interface IBasketService Task<Basket> GetBasket(ApplicationUser user);
{ Task AddItemToBasket(ApplicationUser user, int productId);
Task<Basket> GetBasket(ApplicationUser user); Task<Basket> UpdateBasket(Basket basket);
Task AddItemToBasket(ApplicationUser user, int productId); Task Checkout(BasketDTO basket);
Task<Basket> UpdateBasket(Basket basket); Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities);
Task Checkout(BasketDTO basket); Task<Order> GetOrderDraft(string basketId);
Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities);
Task<Order> GetOrderDraft(string basketId);
}
} }

View File

@ -1,14 +1,8 @@
using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.Services public interface ICatalogService
{ {
public interface ICatalogService Task<Catalog> GetCatalogItems(int page, int take, int? brand, int? type);
{ Task<IEnumerable<SelectListItem>> GetBrands();
Task<Catalog> GetCatalogItems(int page, int take, int? brand, int? type); Task<IEnumerable<SelectListItem>> GetTypes();
Task<IEnumerable<SelectListItem>> GetBrands();
Task<IEnumerable<SelectListItem>> GetTypes();
}
} }

View File

@ -1,9 +1,6 @@
using System.Security.Principal; namespace Microsoft.eShopOnContainers.WebMVC.Services;
namespace Microsoft.eShopOnContainers.WebMVC.Services public interface IIdentityParser<T>
{ {
public interface IIdentityParser<T> T Parse(IPrincipal principal);
{
T Parse(IPrincipal principal);
}
} }

View File

@ -1,18 +1,13 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using System.Collections.Generic; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Threading.Tasks;
using WebMVC.Services.ModelDTOs;
namespace Microsoft.eShopOnContainers.WebMVC.Services public interface IOrderingService
{ {
public interface IOrderingService Task<List<Order>> GetMyOrders(ApplicationUser user);
{ Task<Order> GetOrder(ApplicationUser user, string orderId);
Task<List<Order>> GetMyOrders(ApplicationUser user); Task CancelOrder(string orderId);
Task<Order> GetOrder(ApplicationUser user, string orderId); Task ShipOrder(string orderId);
Task CancelOrder(string orderId); Order MapUserInfoIntoOrder(ApplicationUser user, Order order);
Task ShipOrder(string orderId); BasketDTO MapOrderToBasket(Order order);
Order MapUserInfoIntoOrder(ApplicationUser user, Order order); void OverrideUserInfoIntoOrder(Order original, Order destination);
BasketDTO MapOrderToBasket(Order order);
void OverrideUserInfoIntoOrder(Order original, Order destination);
}
} }

View File

@ -1,42 +1,33 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
namespace Microsoft.eShopOnContainers.WebMVC.Services public class IdentityParser : IIdentityParser<ApplicationUser>
{ {
public class IdentityParser : IIdentityParser<ApplicationUser> public ApplicationUser Parse(IPrincipal principal)
{ {
public ApplicationUser Parse(IPrincipal principal) // Pattern matching 'is' expression
// assigns "claims" if "principal" is a "ClaimsPrincipal"
if (principal is ClaimsPrincipal claims)
{ {
// Pattern matching 'is' expression return new ApplicationUser
// assigns "claims" if "principal" is a "ClaimsPrincipal"
if (principal is ClaimsPrincipal claims)
{ {
return new ApplicationUser
{
CardHolderName = claims.Claims.FirstOrDefault(x => x.Type == "card_holder")?.Value ?? "", CardHolderName = claims.Claims.FirstOrDefault(x => x.Type == "card_holder")?.Value ?? "",
CardNumber = claims.Claims.FirstOrDefault(x => x.Type == "card_number")?.Value ?? "", CardNumber = claims.Claims.FirstOrDefault(x => x.Type == "card_number")?.Value ?? "",
Expiration = claims.Claims.FirstOrDefault(x => x.Type == "card_expiration")?.Value ?? "", Expiration = claims.Claims.FirstOrDefault(x => x.Type == "card_expiration")?.Value ?? "",
CardType = int.Parse(claims.Claims.FirstOrDefault(x => x.Type == "missing")?.Value ?? "0"), CardType = int.Parse(claims.Claims.FirstOrDefault(x => x.Type == "missing")?.Value ?? "0"),
City = claims.Claims.FirstOrDefault(x => x.Type == "address_city")?.Value ?? "", City = claims.Claims.FirstOrDefault(x => x.Type == "address_city")?.Value ?? "",
Country = claims.Claims.FirstOrDefault(x => x.Type == "address_country")?.Value ?? "", Country = claims.Claims.FirstOrDefault(x => x.Type == "address_country")?.Value ?? "",
Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? "", Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? "",
Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "", Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
LastName = claims.Claims.FirstOrDefault(x => x.Type == "last_name")?.Value ?? "", LastName = claims.Claims.FirstOrDefault(x => x.Type == "last_name")?.Value ?? "",
Name = claims.Claims.FirstOrDefault(x => x.Type == "name")?.Value ?? "", Name = claims.Claims.FirstOrDefault(x => x.Type == "name")?.Value ?? "",
PhoneNumber = claims.Claims.FirstOrDefault(x => x.Type == "phone_number")?.Value ?? "", PhoneNumber = claims.Claims.FirstOrDefault(x => x.Type == "phone_number")?.Value ?? "",
SecurityNumber = claims.Claims.FirstOrDefault(x => x.Type == "card_security_number")?.Value ?? "", SecurityNumber = claims.Claims.FirstOrDefault(x => x.Type == "card_security_number")?.Value ?? "",
State = claims.Claims.FirstOrDefault(x => x.Type == "address_state")?.Value ?? "", State = claims.Claims.FirstOrDefault(x => x.Type == "address_state")?.Value ?? "",
Street = claims.Claims.FirstOrDefault(x => x.Type == "address_street")?.Value ?? "", Street = claims.Claims.FirstOrDefault(x => x.Type == "address_street")?.Value ?? "",
ZipCode = claims.Claims.FirstOrDefault(x => x.Type == "address_zip_code")?.Value ?? "" ZipCode = claims.Claims.FirstOrDefault(x => x.Type == "address_zip_code")?.Value ?? ""
}; };
}
throw new ArgumentException(message: "The principal must be a ClaimsPrincipal", paramName: nameof(principal));
} }
throw new ArgumentException(message: "The principal must be a ClaimsPrincipal", paramName: nameof(principal));
} }
} }

View File

@ -1,37 +1,32 @@
using System; namespace WebMVC.Services.ModelDTOs;
using System.ComponentModel.DataAnnotations;
namespace WebMVC.Services.ModelDTOs public record BasketDTO
{ {
public record BasketDTO [Required]
{ public string City { get; init; }
[Required] [Required]
public string City { get; init; } public string Street { get; init; }
[Required] [Required]
public string Street { get; init; } public string State { get; init; }
[Required] [Required]
public string State { get; init; } public string Country { get; init; }
[Required]
public string Country { get; init; }
public string ZipCode { get; init; } public string ZipCode { get; init; }
[Required] [Required]
public string CardNumber { get; init; } public string CardNumber { get; init; }
[Required] [Required]
public string CardHolderName { get; init; } public string CardHolderName { get; init; }
[Required] [Required]
public DateTime CardExpiration { get; init; } public DateTime CardExpiration { get; init; }
[Required] [Required]
public string CardSecurityNumber { get; init; } public string CardSecurityNumber { get; init; }
public int CardTypeId { get; init; } public int CardTypeId { get; init; }
public string Buyer { get; init; } public string Buyer { get; init; }
[Required] [Required]
public Guid RequestId { get; init; } public Guid RequestId { get; init; }
}
} }

View File

@ -1,8 +1,7 @@
namespace WebMVC.Services.ModelDTOs namespace WebMVC.Services.ModelDTOs;
public record LocationDTO
{ {
public record LocationDTO public double Longitude { get; init; }
{ public double Latitude { get; init; }
public double Longitude { get; init; }
public double Latitude { get; init; }
}
} }

View File

@ -1,10 +1,7 @@
using System.ComponentModel.DataAnnotations; namespace WebMVC.Services.ModelDTOs;
namespace WebMVC.Services.ModelDTOs public record OrderDTO
{ {
public record OrderDTO [Required]
{ public string OrderNumber { get; init; }
[Required] }
public string OrderNumber { get; init; }
}
}

View File

@ -1,20 +1,19 @@
namespace WebMVC.Services.ModelDTOs namespace WebMVC.Services.ModelDTOs;
public record OrderProcessAction
{ {
public record OrderProcessAction public string Code { get; }
public string Name { get; }
public static OrderProcessAction Ship = new OrderProcessAction(nameof(Ship).ToLowerInvariant(), "Ship");
protected OrderProcessAction()
{ {
public string Code { get; } }
public string Name { get; }
public static OrderProcessAction Ship = new OrderProcessAction(nameof(Ship).ToLowerInvariant(), "Ship"); public OrderProcessAction(string code, string name)
{
protected OrderProcessAction() Code = code;
{ Name = name;
}
public OrderProcessAction(string code, string name)
{
Code = code;
Name = name;
}
} }
} }

View File

@ -1,149 +1,140 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; namespace Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services using Microsoft.eShopOnContainers.WebMVC.ViewModels;
public class OrderingService : IOrderingService
{ {
public class OrderingService : IOrderingService private HttpClient _httpClient;
private readonly string _remoteServiceBaseUrl;
private readonly IOptions<AppSettings> _settings;
public OrderingService(HttpClient httpClient, IOptions<AppSettings> settings)
{ {
private HttpClient _httpClient; _httpClient = httpClient;
private readonly string _remoteServiceBaseUrl; _settings = settings;
private readonly IOptions<AppSettings> _settings;
_remoteServiceBaseUrl = $"{settings.Value.PurchaseUrl}/o/api/v1/orders";
}
public OrderingService(HttpClient httpClient, IOptions<AppSettings> settings) async public Task<Order> GetOrder(ApplicationUser user, string id)
{
var uri = API.Order.GetOrder(_remoteServiceBaseUrl, id);
var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
{ {
_httpClient = httpClient; PropertyNameCaseInsensitive = true
_settings = settings; });
_remoteServiceBaseUrl = $"{settings.Value.PurchaseUrl}/o/api/v1/orders"; return response;
}
async public Task<List<Order>> GetMyOrders(ApplicationUser user)
{
var uri = API.Order.GetAllMyOrders(_remoteServiceBaseUrl);
var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonSerializer.Deserialize<List<Order>>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response;
}
async public Task CancelOrder(string orderId)
{
var order = new OrderDTO()
{
OrderNumber = orderId
};
var uri = API.Order.CancelOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent);
if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new Exception("Error cancelling order, try later.");
} }
async public Task<Order> GetOrder(ApplicationUser user, string id) response.EnsureSuccessStatusCode();
}
async public Task ShipOrder(string orderId)
{
var order = new OrderDTO()
{ {
var uri = API.Order.GetOrder(_remoteServiceBaseUrl, id); OrderNumber = orderId
};
var responseString = await _httpClient.GetStringAsync(uri); var uri = API.Order.ShipOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions var response = await _httpClient.PutAsync(uri, orderContent);
{
PropertyNameCaseInsensitive = true
});
return response; if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new Exception("Error in ship order process, try later.");
} }
async public Task<List<Order>> GetMyOrders(ApplicationUser user) response.EnsureSuccessStatusCode();
}
public void OverrideUserInfoIntoOrder(Order original, Order destination)
{
destination.City = original.City;
destination.Street = original.Street;
destination.State = original.State;
destination.Country = original.Country;
destination.ZipCode = original.ZipCode;
destination.CardNumber = original.CardNumber;
destination.CardHolderName = original.CardHolderName;
destination.CardExpiration = original.CardExpiration;
destination.CardSecurityNumber = original.CardSecurityNumber;
}
public Order MapUserInfoIntoOrder(ApplicationUser user, Order order)
{
order.City = user.City;
order.Street = user.Street;
order.State = user.State;
order.Country = user.Country;
order.ZipCode = user.ZipCode;
order.CardNumber = user.CardNumber;
order.CardHolderName = user.CardHolderName;
order.CardExpiration = new DateTime(int.Parse("20" + user.Expiration.Split('/')[1]), int.Parse(user.Expiration.Split('/')[0]), 1);
order.CardSecurityNumber = user.SecurityNumber;
return order;
}
public BasketDTO MapOrderToBasket(Order order)
{
order.CardExpirationApiFormat();
return new BasketDTO()
{ {
var uri = API.Order.GetAllMyOrders(_remoteServiceBaseUrl); City = order.City,
Street = order.Street,
var responseString = await _httpClient.GetStringAsync(uri); State = order.State,
Country = order.Country,
var response = JsonSerializer.Deserialize<List<Order>>(responseString, new JsonSerializerOptions ZipCode = order.ZipCode,
{ CardNumber = order.CardNumber,
PropertyNameCaseInsensitive = true CardHolderName = order.CardHolderName,
}); CardExpiration = order.CardExpiration,
CardSecurityNumber = order.CardSecurityNumber,
return response; CardTypeId = 1,
} Buyer = order.Buyer,
RequestId = order.RequestId
};
async public Task CancelOrder(string orderId)
{
var order = new OrderDTO()
{
OrderNumber = orderId
};
var uri = API.Order.CancelOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent);
if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new Exception("Error cancelling order, try later.");
}
response.EnsureSuccessStatusCode();
}
async public Task ShipOrder(string orderId)
{
var order = new OrderDTO()
{
OrderNumber = orderId
};
var uri = API.Order.ShipOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent);
if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new Exception("Error in ship order process, try later.");
}
response.EnsureSuccessStatusCode();
}
public void OverrideUserInfoIntoOrder(Order original, Order destination)
{
destination.City = original.City;
destination.Street = original.Street;
destination.State = original.State;
destination.Country = original.Country;
destination.ZipCode = original.ZipCode;
destination.CardNumber = original.CardNumber;
destination.CardHolderName = original.CardHolderName;
destination.CardExpiration = original.CardExpiration;
destination.CardSecurityNumber = original.CardSecurityNumber;
}
public Order MapUserInfoIntoOrder(ApplicationUser user, Order order)
{
order.City = user.City;
order.Street = user.Street;
order.State = user.State;
order.Country = user.Country;
order.ZipCode = user.ZipCode;
order.CardNumber = user.CardNumber;
order.CardHolderName = user.CardHolderName;
order.CardExpiration = new DateTime(int.Parse("20" + user.Expiration.Split('/')[1]), int.Parse(user.Expiration.Split('/')[0]), 1);
order.CardSecurityNumber = user.SecurityNumber;
return order;
}
public BasketDTO MapOrderToBasket(Order order)
{
order.CardExpirationApiFormat();
return new BasketDTO()
{
City = order.City,
Street = order.Street,
State = order.State,
Country = order.Country,
ZipCode = order.ZipCode,
CardNumber = order.CardNumber,
CardHolderName = order.CardHolderName,
CardExpiration = order.CardExpiration,
CardSecurityNumber = order.CardSecurityNumber,
CardTypeId = 1,
Buyer = order.Buyer,
RequestId = order.RequestId
};
}
} }
} }

View File

@ -1,212 +1,190 @@
using Devspaces.Support; namespace Microsoft.eShopOnContainers.WebMVC;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Logging;
using StackExchange.Redis;
using System;
using System.IdentityModel.Tokens.Jwt;
using WebMVC.Infrastructure;
namespace Microsoft.eShopOnContainers.WebMVC public class Startup
{ {
public class Startup public Startup(IConfiguration configuration)
{ {
public Startup(IConfiguration configuration) Configuration = configuration;
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the IoC container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.Services
.AddAppInsight(Configuration)
.AddHealthChecks(Configuration)
.AddCustomMvc(Configuration)
.AddDevspaces()
.AddHttpClientServices(Configuration);
IdentityModelEventSource.ShowPII = true; // Caution! Do NOT use in production: https://aka.ms/IdentityModel/PII
services.AddControllers();
services.AddCustomAuthentication(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
app.UsePathBase(pathBase);
}
app.UseStaticFiles();
app.UseSession();
WebContextSeed.Seed(app, env);
// Fix samesite issue when running eShop from docker-compose locally as by default http protocol is being used
// Refer to https://github.com/dotnet-architecture/eShopOnContainers/issues/1391
app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = AspNetCore.Http.SameSiteMode.Lax });
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}");
endpoints.MapControllerRoute("defaultError", "{controller=Error}/{action=Error}");
endpoints.MapControllers();
endpoints.MapHealthChecks("/liveness", new HealthCheckOptions
{
Predicate = r => r.Name.Contains("self")
});
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
});
}
} }
static class ServiceCollectionExtensions public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the IoC container.
public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllersWithViews()
.Services
.AddAppInsight(Configuration)
.AddHealthChecks(Configuration)
.AddCustomMvc(Configuration)
.AddDevspaces()
.AddHttpClientServices(Configuration);
public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) IdentityModelEventSource.ShowPII = true; // Caution! Do NOT use in production: https://aka.ms/IdentityModel/PII
services.AddControllers();
services.AddCustomAuthentication(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
if (env.IsDevelopment())
{ {
services.AddApplicationInsightsTelemetry(configuration); app.UseDeveloperExceptionPage();
services.AddApplicationInsightsKubernetesEnricher(); }
else
return services; {
app.UseExceptionHandler("/Error");
} }
public static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration) var pathBase = Configuration["PATH_BASE"];
{
services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy())
.AddUrlGroup(new Uri(configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" });
return services; if (!string.IsNullOrEmpty(pathBase))
{
app.UsePathBase(pathBase);
} }
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration) app.UseStaticFiles();
{ app.UseSession();
services.AddOptions();
services.Configure<AppSettings>(configuration);
services.AddSession();
services.AddDistributedMemoryCache();
if (configuration.GetValue<string>("IsClusterEnv") == bool.TrueString) WebContextSeed.Seed(app, env);
// Fix samesite issue when running eShop from docker-compose locally as by default http protocol is being used
// Refer to https://github.com/dotnet-architecture/eShopOnContainers/issues/1391
app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = AspNetCore.Http.SameSiteMode.Lax });
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}");
endpoints.MapControllerRoute("defaultError", "{controller=Error}/{action=Error}");
endpoints.MapControllers();
endpoints.MapHealthChecks("/liveness", new HealthCheckOptions
{ {
services.AddDataProtection(opts => Predicate = r => r.Name.Contains("self")
{
opts.ApplicationDiscriminator = "eshop.webmvc";
})
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(configuration["DPConnectionString"]), "DataProtection-Keys");
}
return services;
}
// Adds all Http client services
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//register delegating handlers
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
services.AddTransient<HttpClientRequestIdDelegatingHandler>();
//set 5 min as the lifetime for each HttpMessageHandler int the pool
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(TimeSpan.FromMinutes(5)).AddDevspacesSupport();
//add http client services
services.AddHttpClient<IBasketService, BasketService>()
.SetHandlerLifetime(TimeSpan.FromMinutes(5)) //Sample. Default lifetime is 2 minutes
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddDevspacesSupport();
services.AddHttpClient<ICatalogService, CatalogService>()
.AddDevspacesSupport();
services.AddHttpClient<IOrderingService, OrderingService>()
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddHttpMessageHandler<HttpClientRequestIdDelegatingHandler>()
.AddDevspacesSupport();
//add custom application services
services.AddTransient<IIdentityParser<ApplicationUser>, IdentityParser>();
return services;
}
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var identityUrl = configuration.GetValue<string>("IdentityUrl");
var callBackUrl = configuration.GetValue<string>("CallBackUrl");
var sessionCookieLifetime = configuration.GetValue("SessionCookieLifetimeMinutes", 60);
// Add Authentication services
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime))
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = identityUrl.ToString();
options.SignedOutRedirectUri = callBackUrl.ToString();
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("orders");
options.Scope.Add("basket");
options.Scope.Add("webshoppingagg");
options.Scope.Add("orders.signalrhub");
}); });
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
return services; {
} Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
});
}
}
static class ServiceCollectionExtensions
{
public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration)
{
services.AddApplicationInsightsTelemetry(configuration);
services.AddApplicationInsightsKubernetesEnricher();
return services;
}
public static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
{
services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy())
.AddUrlGroup(new Uri(configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" });
return services;
}
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions();
services.Configure<AppSettings>(configuration);
services.AddSession();
services.AddDistributedMemoryCache();
if (configuration.GetValue<string>("IsClusterEnv") == bool.TrueString)
{
services.AddDataProtection(opts =>
{
opts.ApplicationDiscriminator = "eshop.webmvc";
})
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(configuration["DPConnectionString"]), "DataProtection-Keys");
}
return services;
}
// Adds all Http client services
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//register delegating handlers
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
services.AddTransient<HttpClientRequestIdDelegatingHandler>();
//set 5 min as the lifetime for each HttpMessageHandler int the pool
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(TimeSpan.FromMinutes(5)).AddDevspacesSupport();
//add http client services
services.AddHttpClient<IBasketService, BasketService>()
.SetHandlerLifetime(TimeSpan.FromMinutes(5)) //Sample. Default lifetime is 2 minutes
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddDevspacesSupport();
services.AddHttpClient<ICatalogService, CatalogService>()
.AddDevspacesSupport();
services.AddHttpClient<IOrderingService, OrderingService>()
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddHttpMessageHandler<HttpClientRequestIdDelegatingHandler>()
.AddDevspacesSupport();
//add custom application services
services.AddTransient<IIdentityParser<ApplicationUser>, IdentityParser>();
return services;
}
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var identityUrl = configuration.GetValue<string>("IdentityUrl");
var callBackUrl = configuration.GetValue<string>("CallBackUrl");
var sessionCookieLifetime = configuration.GetValue("SessionCookieLifetimeMinutes", 60);
// Add Authentication services
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime))
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = identityUrl.ToString();
options.SignedOutRedirectUri = callBackUrl.ToString();
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("orders");
options.Scope.Add("basket");
options.Scope.Add("webshoppingagg");
options.Scope.Add("orders.signalrhub");
});
return services;
} }
} }

View File

@ -1,37 +1,30 @@
using Microsoft.AspNetCore.Mvc; namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.CartViewModels;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents public class Cart : ViewComponent
{ {
public class Cart : ViewComponent private readonly IBasketService _cartSvc;
public Cart(IBasketService cartSvc) => _cartSvc = cartSvc;
public async Task<IViewComponentResult> InvokeAsync(ApplicationUser user)
{ {
private readonly IBasketService _cartSvc; var vm = new CartComponentViewModel();
try
public Cart(IBasketService cartSvc) => _cartSvc = cartSvc;
public async Task<IViewComponentResult> InvokeAsync(ApplicationUser user)
{ {
var vm = new CartComponentViewModel(); var itemsInCart = await ItemsInCartAsync(user);
try vm.ItemsCount = itemsInCart;
{
var itemsInCart = await ItemsInCartAsync(user);
vm.ItemsCount = itemsInCart;
return View(vm);
}
catch
{
ViewBag.IsBasketInoperative = true;
}
return View(vm); return View(vm);
} }
private async Task<int> ItemsInCartAsync(ApplicationUser user) catch
{ {
var basket = await _cartSvc.GetBasket(user); ViewBag.IsBasketInoperative = true;
return basket.Items.Count;
} }
return View(vm);
}
private async Task<int> ItemsInCartAsync(ApplicationUser user)
{
var basket = await _cartSvc.GetBasket(user);
return basket.Items.Count;
} }
} }

View File

@ -1,33 +1,26 @@
using Microsoft.AspNetCore.Mvc; namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents public class CartList : ViewComponent
{ {
public class CartList : ViewComponent private readonly IBasketService _cartSvc;
public CartList(IBasketService cartSvc) => _cartSvc = cartSvc;
public async Task<IViewComponentResult> InvokeAsync(ApplicationUser user)
{ {
private readonly IBasketService _cartSvc; var vm = new Basket();
try
public CartList(IBasketService cartSvc) => _cartSvc = cartSvc;
public async Task<IViewComponentResult> InvokeAsync(ApplicationUser user)
{ {
var vm = new Basket(); vm = await GetItemsAsync(user);
try
{
vm = await GetItemsAsync(user);
return View(vm);
}
catch (Exception ex)
{
ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative, please try later on. ({ex.GetType().Name} - {ex.Message}))";
}
return View(vm); return View(vm);
} }
catch (Exception ex)
{
ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative, please try later on. ({ex.GetType().Name} - {ex.Message}))";
}
private Task<Basket> GetItemsAsync(ApplicationUser user) => _cartSvc.GetBasket(user); return View(vm);
} }
private Task<Basket> GetItemsAsync(ApplicationUser user) => _cartSvc.GetBasket(user);
} }

View File

@ -1,31 +1,27 @@
using System; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations;
using System.ComponentModel.DataAnnotations;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class CardExpirationAttribute : ValidationAttribute
{ {
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] public override bool IsValid(object value)
public class CardExpirationAttribute : ValidationAttribute
{ {
public override bool IsValid(object value) if (value == null)
return false;
var monthString = value.ToString().Split('/')[0];
var yearString = $"20{value.ToString().Split('/')[1]}";
// Use the 'out' variable initializer to simplify
// the logic of validating the expiration date
if ((int.TryParse(monthString, out var month)) &&
(int.TryParse(yearString, out var year)))
{ {
if (value == null) DateTime d = new DateTime(year, month, 1);
return false;
var monthString = value.ToString().Split('/')[0]; return d > DateTime.UtcNow;
var yearString = $"20{value.ToString().Split('/')[1]}"; }
// Use the 'out' variable initializer to simplify else
// the logic of validating the expiration date {
if ((int.TryParse(monthString, out var month)) && return false;
(int.TryParse(yearString, out var year)))
{
DateTime d = new DateTime(year, month, 1);
return d > DateTime.UtcNow;
}
else
{
return false;
}
} }
} }
} }

View File

@ -1,22 +1,18 @@
using System; namespace WebMVC.ViewModels.Annotations;
using System.ComponentModel.DataAnnotations;
namespace WebMVC.ViewModels.Annotations [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class LatitudeCoordinate : ValidationAttribute
{ {
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] protected override ValidationResult
public class LatitudeCoordinate : ValidationAttribute IsValid(object value, ValidationContext validationContext)
{ {
protected override ValidationResult double coordinate;
IsValid(object value, ValidationContext validationContext) if (!double.TryParse(value.ToString(), out coordinate) || (coordinate < -90 || coordinate > 90))
{ {
double coordinate; return new ValidationResult
if (!double.TryParse(value.ToString(), out coordinate) || (coordinate < -90 || coordinate > 90)) ("Latitude must be between -90 and 90 degrees inclusive.");
{
return new ValidationResult
("Latitude must be between -90 and 90 degrees inclusive.");
}
return ValidationResult.Success;
} }
return ValidationResult.Success;
} }
} }

View File

@ -1,22 +1,18 @@
using System; namespace WebMVC.ViewModels.Annotations;
using System.ComponentModel.DataAnnotations;
namespace WebMVC.ViewModels.Annotations [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class LongitudeCoordinate : ValidationAttribute
{ {
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] protected override ValidationResult
public class LongitudeCoordinate : ValidationAttribute IsValid(object value, ValidationContext validationContext)
{ {
protected override ValidationResult double coordinate;
IsValid(object value, ValidationContext validationContext) if (!double.TryParse(value.ToString(), out coordinate) || (coordinate < -180 || coordinate > 180))
{ {
double coordinate; return new ValidationResult
if (!double.TryParse(value.ToString(), out coordinate) || (coordinate < -180 || coordinate > 180)) ("Longitude must be between -180 and 180 degrees inclusive.");
{
return new ValidationResult
("Longitude must be between -180 and 180 degrees inclusive.");
}
return ValidationResult.Success;
} }
return ValidationResult.Success;
} }
} }

View File

@ -1,28 +1,24 @@
using Microsoft.AspNetCore.Identity; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.ComponentModel.DataAnnotations;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{ {
// Add profile data for application users by adding properties to the ApplicationUser class public string CardNumber { get; set; }
public class ApplicationUser : IdentityUser public string SecurityNumber { get; set; }
{ public string Expiration { get; set; }
public string CardNumber { get; set; } public string CardHolderName { get; set; }
public string SecurityNumber { get; set; } public int CardType { get; set; }
public string Expiration { get; set; } public string Street { get; set; }
public string CardHolderName { get; set; } public string City { get; set; }
public int CardType { get; set; } public string State { get; set; }
public string Street { get; set; } public string StateCode { get; set; }
public string City { get; set; } public string Country { get; set; }
public string State { get; set; } public string CountryCode { get; set; }
public string StateCode { get; set; } public string ZipCode { get; set; }
public string Country { get; set; } public double Latitude { get; set; }
public string CountryCode { get; set; } public double Longitude { get; set; }
public string ZipCode { get; set; } [Required]
public double Latitude { get; set; } public string Name { get; set; }
public double Longitude { get; set; } [Required]
[Required] public string LastName { get; set; }
public string Name { get; set; }
[Required]
public string LastName { get; set; }
}
} }

View File

@ -1,21 +1,16 @@
using System; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public record Basket
{ {
public record Basket // Use property initializer syntax.
{ // While this is often more useful for read only
// Use property initializer syntax. // auto implemented properties, it can simplify logic
// While this is often more useful for read only // for read/write properties.
// auto implemented properties, it can simplify logic public List<BasketItem> Items { get; init; } = new List<BasketItem>();
// for read/write properties. public string BuyerId { get; init; }
public List<BasketItem> Items { get; init; } = new List<BasketItem>();
public string BuyerId { get; init; }
public decimal Total() public decimal Total()
{ {
return Math.Round(Items.Sum(x => x.UnitPrice * x.Quantity), 2); return Math.Round(Items.Sum(x => x.UnitPrice * x.Quantity), 2);
}
} }
} }

View File

@ -1,13 +1,12 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
public record BasketItem
{ {
public record BasketItem public string Id { get; init; }
{ public int ProductId { get; init; }
public string Id { get; init; } public string ProductName { get; init; }
public int ProductId { get; init; } public decimal UnitPrice { get; init; }
public string ProductName { get; init; } public decimal OldUnitPrice { get; init; }
public decimal UnitPrice { get; init; } public int Quantity { get; init; }
public decimal OldUnitPrice { get; init; } public string PictureUrl { get; init; }
public int Quantity { get; init; }
public string PictureUrl { get; init; }
}
} }

View File

@ -1,12 +1,9 @@
using System.Collections.Generic; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public record Campaign
{ {
public record Campaign public int PageIndex { get; init; }
{ public int PageSize { get; init; }
public int PageIndex { get; init; } public int Count { get; init; }
public int PageSize { get; init; } public List<CampaignItem> Data { get; init; }
public int Count { get; init; } }
public List<CampaignItem> Data { get; init; }
}
}

View File

@ -1,20 +1,17 @@
using System; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public record CampaignItem
{ {
public record CampaignItem public int Id { get; init; }
{
public int Id { get; init; }
public string Name { get; init; } public string Name { get; init; }
public string Description { get; init; } public string Description { get; init; }
public DateTime From { get; init; } public DateTime From { get; init; }
public DateTime To { get; init; } public DateTime To { get; init; }
public string PictureUri { get; init; } public string PictureUri { get; init; }
public string DetailsUri { get; init; } public string DetailsUri { get; init; }
} }
}

View File

@ -1,8 +1,7 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.CartViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.CartViewModels;
public class CartComponentViewModel
{ {
public class CartComponentViewModel public int ItemsCount { get; set; }
{ public string Disabled => (ItemsCount == 0) ? "is-disabled" : "";
public int ItemsCount { get; set; }
public string Disabled => (ItemsCount == 0) ? "is-disabled" : "";
}
} }

View File

@ -1,12 +1,9 @@
using System.Collections.Generic; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public record Catalog
{ {
public record Catalog public int PageIndex { get; init; }
{ public int PageSize { get; init; }
public int PageIndex { get; init; } public int Count { get; init; }
public int PageSize { get; init; } public List<CatalogItem> Data { get; init; }
public int Count { get; init; }
public List<CatalogItem> Data { get; init; }
}
} }

View File

@ -1,15 +1,14 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
public record CatalogItem
{ {
public record CatalogItem public int Id { get; init; }
{ public string Name { get; init; }
public int Id { get; init; } public string Description { get; init; }
public string Name { get; init; } public decimal Price { get; init; }
public string Description { get; init; } public string PictureUri { get; init; }
public decimal Price { get; init; } public int CatalogBrandId { get; init; }
public string PictureUri { get; init; } public string CatalogBrand { get; init; }
public int CatalogBrandId { get; init; } public int CatalogTypeId { get; init; }
public string CatalogBrand { get; init; } public string CatalogType { get; init; }
public int CatalogTypeId { get; init; } }
public string CatalogType { get; init; }
}
}

View File

@ -1,16 +1,11 @@
using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination;
using System.Collections.Generic;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels public class IndexViewModel
{ {
public class IndexViewModel public IEnumerable<CatalogItem> CatalogItems { get; set; }
{ public IEnumerable<SelectListItem> Brands { get; set; }
public IEnumerable<CatalogItem> CatalogItems { get; set; } public IEnumerable<SelectListItem> Types { get; set; }
public IEnumerable<SelectListItem> Brands { get; set; } public int? BrandFilterApplied { get; set; }
public IEnumerable<SelectListItem> Types { get; set; } public int? TypesFilterApplied { get; set; }
public int? BrandFilterApplied { get; set; } public PaginationInfo PaginationInfo { get; set; }
public int? TypesFilterApplied { get; set; }
public PaginationInfo PaginationInfo { get; set; }
}
} }

View File

@ -1,34 +1,26 @@
using System; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public class NumberToStringConverter : JsonConverter<string>
{ {
public class NumberToStringConverter : JsonConverter<string> public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ {
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) if (reader.TokenType == JsonTokenType.Number)
{ {
if (reader.TokenType == JsonTokenType.Number) var numberValue = reader.GetInt32();
{ return numberValue.ToString();
var numberValue = reader.GetInt32();
return numberValue.ToString();
}
else if (reader.TokenType == JsonTokenType.String)
{
return reader.GetString();
}
else
{
throw new JsonException();
}
} }
else if (reader.TokenType == JsonTokenType.String)
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{ {
writer.WriteStringValue(value); return reader.GetString();
}
else
{
throw new JsonException();
} }
} }
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
} }

View File

@ -1,8 +1,7 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
public record Header
{ {
public record Header public string Controller { get; init; }
{ public string Text { get; init; }
public string Controller { get; init; } }
public string Text { get; init; }
}
}

View File

@ -1,101 +1,91 @@
using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using WebMVC.Services.ModelDTOs;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels public class Order
{ {
public class Order [JsonConverter(typeof(NumberToStringConverter))]
{ public string OrderNumber { get; set; }
[JsonConverter(typeof(NumberToStringConverter))]
public string OrderNumber { get; set; }
public DateTime Date { get; set; } public DateTime Date { get; set; }
public string Status { get; set; } public string Status { get; set; }
public decimal Total { get; set; } public decimal Total { get; set; }
public string Description { get; set; } public string Description { get; set; }
[Required] [Required]
public string City { get; set; } public string City { get; set; }
[Required] [Required]
public string Street { get; set; } public string Street { get; set; }
[Required] [Required]
public string State { get; set; } public string State { get; set; }
[Required] [Required]
public string Country { get; set; } public string Country { get; set; }
public string ZipCode { get; set; } public string ZipCode { get; set; }
[Required] [Required]
[DisplayName("Card number")] [DisplayName("Card number")]
public string CardNumber { get; set; } public string CardNumber { get; set; }
[Required] [Required]
[DisplayName("Cardholder name")] [DisplayName("Cardholder name")]
public string CardHolderName { get; set; } public string CardHolderName { get; set; }
public DateTime CardExpiration { get; set; } public DateTime CardExpiration { get; set; }
[RegularExpression(@"(0[1-9]|1[0-2])\/[0-9]{2}", ErrorMessage = "Expiration should match a valid MM/YY value")] [RegularExpression(@"(0[1-9]|1[0-2])\/[0-9]{2}", ErrorMessage = "Expiration should match a valid MM/YY value")]
[CardExpiration(ErrorMessage = "The card is expired"), Required] [CardExpiration(ErrorMessage = "The card is expired"), Required]
[DisplayName("Card expiration")] [DisplayName("Card expiration")]
public string CardExpirationShort { get; set; } public string CardExpirationShort { get; set; }
[Required] [Required]
[DisplayName("Card security number")] [DisplayName("Card security number")]
public string CardSecurityNumber { get; set; } public string CardSecurityNumber { get; set; }
public int CardTypeId { get; set; } public int CardTypeId { get; set; }
public string Buyer { get; set; } public string Buyer { get; set; }
public List<SelectListItem> ActionCodeSelectList => public List<SelectListItem> ActionCodeSelectList =>
GetActionCodesByCurrentState(); GetActionCodesByCurrentState();
public List<OrderItem> OrderItems { get; set; } public List<OrderItem> OrderItems { get; set; }
[Required] [Required]
public Guid RequestId { get; set; } public Guid RequestId { get; set; }
public void CardExpirationShortFormat() public void CardExpirationShortFormat()
{ {
CardExpirationShort = CardExpiration.ToString("MM/yy"); CardExpirationShort = CardExpiration.ToString("MM/yy");
}
public void CardExpirationApiFormat()
{
var month = CardExpirationShort.Split('/')[0];
var year = $"20{CardExpirationShort.Split('/')[1]}";
CardExpiration = new DateTime(int.Parse(year), int.Parse(month), 1);
}
private List<SelectListItem> GetActionCodesByCurrentState()
{
var actions = new List<OrderProcessAction>();
switch (Status?.ToLower())
{
case "paid":
actions.Add(OrderProcessAction.Ship);
break;
}
var result = new List<SelectListItem>();
actions.ForEach(action =>
{
result.Add(new SelectListItem { Text = action.Name, Value = action.Code });
});
return result;
}
} }
public enum CardType public void CardExpirationApiFormat()
{ {
AMEX = 1 var month = CardExpirationShort.Split('/')[0];
var year = $"20{CardExpirationShort.Split('/')[1]}";
CardExpiration = new DateTime(int.Parse(year), int.Parse(month), 1);
}
private List<SelectListItem> GetActionCodesByCurrentState()
{
var actions = new List<OrderProcessAction>();
switch (Status?.ToLower())
{
case "paid":
actions.Add(OrderProcessAction.Ship);
break;
}
var result = new List<SelectListItem>();
actions.ForEach(action =>
{
result.Add(new SelectListItem { Text = action.Name, Value = action.Code });
});
return result;
} }
} }
public enum CardType
{
AMEX = 1
}

View File

@ -1,17 +1,16 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels;
public record OrderItem
{ {
public record OrderItem public int ProductId { get; init; }
{
public int ProductId { get; init; }
public string ProductName { get; init; } public string ProductName { get; init; }
public decimal UnitPrice { get; init; } public decimal UnitPrice { get; init; }
public decimal Discount { get; init; } public decimal Discount { get; init; }
public int Units { get; init; } public int Units { get; init; }
public string PictureUrl { get; init; } public string PictureUrl { get; init; }
}
} }

View File

@ -1,12 +1,11 @@
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination namespace Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination;
public class PaginationInfo
{ {
public class PaginationInfo public int TotalItems { get; set; }
{ public int ItemsPerPage { get; set; }
public int TotalItems { get; set; } public int ActualPage { get; set; }
public int ItemsPerPage { get; set; } public int TotalPages { get; set; }
public int ActualPage { get; set; } public string Previous { get; set; }
public int TotalPages { get; set; } public string Next { get; set; }
public string Previous { get; set; }
public string Next { get; set; }
}
} }