Browse Source

Migrates from Newtonsoft.Json to System.Text.Json (#1658)

* Included System.Text.Json related changes

* Fixed order details summary in WebMVC

* Updated custom JsonConverter
pull/1662/head
Sumit Ghosh 3 years ago
committed by GitHub
parent
commit
19baeb7069
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 206 additions and 133 deletions
  1. +0
    -1
      src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj
  2. +6
    -3
      src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderApiClient.cs
  3. +1
    -1
      src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs
  4. +6
    -3
      src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderApiClient.cs
  5. +1
    -1
      src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs
  6. +0
    -1
      src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj
  7. +1
    -2
      src/BuildingBlocks/EventBus/EventBus/EventBus.csproj
  8. +5
    -5
      src/BuildingBlocks/EventBus/EventBus/Events/IntegrationEvent.cs
  9. +8
    -8
      src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.cs
  10. +1
    -2
      src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj
  11. +6
    -6
      src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.cs
  12. +1
    -2
      src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj
  13. +8
    -5
      src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs
  14. +1
    -2
      src/Services/Basket/Basket.API/Basket.API.csproj
  15. +6
    -3
      src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs
  16. +1
    -1
      src/Services/Basket/Basket.API/Startup.cs
  17. +3
    -3
      src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs
  18. +1
    -2
      src/Services/Catalog/Catalog.API/Catalog.API.csproj
  19. +2
    -1
      src/Services/Catalog/Catalog.API/Startup.cs
  20. +1
    -1
      src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/OrderStartedIntegrationEvent.cs
  21. +5
    -5
      src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs
  22. +3
    -3
      src/Services/Ordering/Ordering.API/Application/Models/CustomerBasket.cs
  23. +1
    -2
      src/Services/Ordering/Ordering.API/Ordering.API.csproj
  24. +2
    -3
      src/Services/Ordering/Ordering.API/Startup.cs
  25. +3
    -3
      src/Services/Ordering/Ordering.FunctionalTests/OrderingScenarios.cs
  26. +3
    -5
      src/Services/Webhooks/Webhooks.API/Model/WebhookData.cs
  27. +2
    -2
      src/Services/Webhooks/Webhooks.API/Services/WebhooksSender.cs
  28. +11
    -5
      src/Tests/Services/Application.FunctionalTests/Services/IntegrationEventsScenarios.cs
  29. +17
    -7
      src/Tests/Services/Application.FunctionalTests/Services/Ordering/OrderingScenarios.cs
  30. +2
    -2
      src/Web/WebMVC/Controllers/TestController.cs
  31. +6
    -3
      src/Web/WebMVC/Extensions/SessionExtensions.cs
  32. +18
    -9
      src/Web/WebMVC/Services/BasketService.cs
  33. +15
    -12
      src/Web/WebMVC/Services/CatalogService.cs
  34. +11
    -5
      src/Web/WebMVC/Services/OrderingService.cs
  35. +1
    -1
      src/Web/WebMVC/ViewModels/BasketItem.cs
  36. +34
    -0
      src/Web/WebMVC/ViewModels/Converters/NumberToStringConverter.cs
  37. +5
    -7
      src/Web/WebMVC/ViewModels/Order.cs
  38. +1
    -2
      src/Web/WebSPA/WebSPA.csproj
  39. +2
    -2
      src/Web/WebhookClient/Pages/RegisterWebhook.cshtml.cs
  40. +5
    -2
      src/Web/WebhookClient/Services/WebhooksClient.cs

+ 0
- 1
src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj View File

@ -24,7 +24,6 @@
<PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" /> <PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />


+ 6
- 3
src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderApiClient.cs View File

@ -2,9 +2,9 @@
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
{ {
@ -24,14 +24,17 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket) public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket)
{ {
var uri = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft(); var uri = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
var content = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, content); var response = await _apiClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var ordersDraftResponse = await response.Content.ReadAsStringAsync(); var ordersDraftResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OrderData>(ordersDraftResponse);
return JsonSerializer.Deserialize<OrderData>(ordersDraftResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
} }
} }

+ 1
- 1
src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs View File

@ -107,7 +107,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator
services.Configure<UrlsConfig>(configuration.GetSection("urls")); services.Configure<UrlsConfig>(configuration.GetSection("urls"));
services.AddControllers() services.AddControllers()
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options => services.AddSwaggerGen(options =>
{ {


+ 6
- 3
src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderApiClient.cs View File

@ -2,9 +2,9 @@
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models; using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services
{ {
@ -24,14 +24,17 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services
public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket) public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket)
{ {
var url = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft(); var url = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
var content = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(url, content); var response = await _apiClient.PostAsync(url, content);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var ordersDraftResponse = await response.Content.ReadAsStringAsync(); var ordersDraftResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OrderData>(ordersDraftResponse);
return JsonSerializer.Deserialize<OrderData>(ordersDraftResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
} }
} }

+ 1
- 1
src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs View File

@ -130,7 +130,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator
services.Configure<UrlsConfig>(configuration.GetSection("urls")); services.Configure<UrlsConfig>(configuration.GetSection("urls"));
services.AddControllers() services.AddControllers()
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options => services.AddSwaggerGen(options =>
{ {


+ 0
- 1
src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj View File

@ -25,7 +25,6 @@
<PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" /> <PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />


+ 1
- 2
src/BuildingBlocks/EventBus/EventBus/EventBus.csproj View File

@ -5,8 +5,7 @@
<RootNamespace>Microsoft.eShopOnContainers.BuildingBlocks.EventBus</RootNamespace> <RootNamespace>Microsoft.eShopOnContainers.BuildingBlocks.EventBus</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<ItemGroup>
</ItemGroup> </ItemGroup>
</Project> </Project>

+ 5
- 5
src/BuildingBlocks/EventBus/EventBus/Events/IntegrationEvent.cs View File

@ -1,10 +1,10 @@
using Newtonsoft.Json;
using System;
using System;
using System.Text.Json.Serialization;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events
{ {
public record IntegrationEvent public record IntegrationEvent
{
{
public IntegrationEvent() public IntegrationEvent()
{ {
Id = Guid.NewGuid(); Id = Guid.NewGuid();
@ -18,10 +18,10 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events
CreationDate = createDate; CreationDate = createDate;
} }
[JsonProperty]
[JsonInclude]
public Guid Id { get; private init; } public Guid Id { get; private init; }
[JsonProperty]
[JsonInclude]
public DateTime CreationDate { get; private init; } public DateTime CreationDate { get; private init; }
} }
} }

+ 8
- 8
src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.cs View File

@ -4,8 +4,6 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Extensions; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Extensions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Polly; using Polly;
using Polly.Retry; using Polly.Retry;
using RabbitMQ.Client; using RabbitMQ.Client;
@ -15,6 +13,7 @@ using System;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
{ {
@ -89,9 +88,11 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
_logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id); _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);
channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct"); channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct");
var message = JsonConvert.SerializeObject(@event);
var body = Encoding.UTF8.GetBytes(message);
var body = JsonSerializer.SerializeToUtf8Bytes(@event, @event.GetType(), new JsonSerializerOptions
{
WriteIndented = true
});
policy.Execute(() => policy.Execute(() =>
{ {
@ -272,8 +273,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
{ {
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
if (handler == null) continue; if (handler == null) continue;
dynamic eventData = JObject.Parse(message);
using dynamic eventData = JsonDocument.Parse(message);
await Task.Yield(); await Task.Yield();
await handler.Handle(eventData); await handler.Handle(eventData);
} }
@ -282,7 +282,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
var handler = scope.ResolveOptional(subscription.HandlerType); var handler = scope.ResolveOptional(subscription.HandlerType);
if (handler == null) continue; if (handler == null) continue;
var eventType = _subsManager.GetEventTypeByName(eventName); var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var integrationEvent = JsonSerializer.Deserialize(message, eventType, new JsonSerializerOptions() { PropertyNameCaseInsensitive= true});
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await Task.Yield(); await Task.Yield();


+ 1
- 2
src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj View File

@ -8,8 +8,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Autofac" Version="6.1.0" /> <PackageReference Include="Autofac" Version="6.1.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" /> <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Polly" Version="7.2.1" /> <PackageReference Include="Polly" Version="7.2.1" />
<PackageReference Include="RabbitMQ.Client" Version="6.2.1" /> <PackageReference Include="RabbitMQ.Client" Version="6.2.1" />
</ItemGroup> </ItemGroup>


+ 6
- 6
src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.cs View File

@ -5,11 +5,10 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
public class EventBusServiceBus : IEventBus public class EventBusServiceBus : IEventBus
@ -36,7 +35,7 @@
public void Publish(IntegrationEvent @event) public void Publish(IntegrationEvent @event)
{ {
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, "");
var jsonMessage = JsonConvert.SerializeObject(@event);
var jsonMessage = JsonSerializer.Serialize(@event);
var body = Encoding.UTF8.GetBytes(jsonMessage); var body = Encoding.UTF8.GetBytes(jsonMessage);
var message = new Message var message = new Message
@ -165,7 +164,8 @@
{ {
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
if (handler == null) continue; if (handler == null) continue;
dynamic eventData = JObject.Parse(message);
using dynamic eventData = JsonDocument.Parse(message);
await handler.Handle(eventData); await handler.Handle(eventData);
} }
else else
@ -173,7 +173,7 @@
var handler = scope.ResolveOptional(subscription.HandlerType); var handler = scope.ResolveOptional(subscription.HandlerType);
if (handler == null) continue; if (handler == null) continue;
var eventType = _subsManager.GetEventTypeByName(eventName); var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var integrationEvent = JsonSerializer.Deserialize(message, eventType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent }); await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
} }


+ 1
- 2
src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj View File

@ -12,8 +12,7 @@
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>


+ 8
- 5
src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs View File

@ -1,6 +1,6 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Newtonsoft.Json;
using System; using System;
using System.Text.Json;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
@ -13,8 +13,11 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF
{ {
EventId = @event.Id; EventId = @event.Id;
CreationTime = @event.CreationDate; CreationTime = @event.CreationDate;
EventTypeName = @event.GetType().FullName;
Content = JsonConvert.SerializeObject(@event);
EventTypeName = @event.GetType().FullName;
Content = JsonSerializer.Serialize(@event, @event.GetType(), new JsonSerializerOptions
{
WriteIndented = true
});
State = EventStateEnum.NotPublished; State = EventStateEnum.NotPublished;
TimesSent = 0; TimesSent = 0;
TransactionId = transactionId.ToString(); TransactionId = transactionId.ToString();
@ -32,8 +35,8 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF
public string TransactionId { get; private set; } public string TransactionId { get; private set; }
public IntegrationEventLogEntry DeserializeJsonContent(Type type) public IntegrationEventLogEntry DeserializeJsonContent(Type type)
{
IntegrationEvent = JsonConvert.DeserializeObject(Content, type) as IntegrationEvent;
{
IntegrationEvent = JsonSerializer.Deserialize(Content, type, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }) as IntegrationEvent;
return this; return this;
} }
} }


+ 1
- 2
src/Services/Basket/Basket.API/Basket.API.csproj View File

@ -29,8 +29,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" /> <PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />


+ 6
- 3
src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs View File

@ -1,10 +1,10 @@
using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis; using StackExchange.Redis;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories
{ {
@ -43,12 +43,15 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Reposit
return null; return null;
} }
return JsonConvert.DeserializeObject<CustomerBasket>(data);
return JsonSerializer.Deserialize<CustomerBasket>(data, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket basket) public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket basket)
{ {
var created = await _database.StringSetAsync(basket.BuyerId, JsonConvert.SerializeObject(basket));
var created = await _database.StringSetAsync(basket.BuyerId, JsonSerializer.Serialize(basket));
if (!created) if (!created)
{ {


+ 1
- 1
src/Services/Basket/Basket.API/Startup.cs View File

@ -62,7 +62,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
}) // Added for functional tests }) // Added for functional tests
.AddApplicationPart(typeof(BasketController).Assembly) .AddApplicationPart(typeof(BasketController).Assembly)
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options => services.AddSwaggerGen(options =>
{ {


+ 3
- 3
src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs View File

@ -1,9 +1,9 @@
using Basket.FunctionalTests.Base; using Basket.FunctionalTests.Base;
using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Newtonsoft.Json;
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -68,7 +68,7 @@ namespace Basket.FunctionalTests
Quantity = 1 Quantity = 1
}); });
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
} }
string BuildCheckout() string BuildCheckout()
@ -89,7 +89,7 @@ namespace Basket.FunctionalTests
RequestId = Guid.NewGuid() RequestId = Guid.NewGuid()
}; };
return JsonConvert.SerializeObject(checkoutBasket);
return JsonSerializer.Serialize(checkoutBasket);
} }
} }
} }

+ 1
- 2
src/Services/Catalog/Catalog.API/Catalog.API.csproj View File

@ -54,8 +54,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" /> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.16.0" /> <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.16.0" />
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" /> <PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />


+ 2
- 1
src/Services/Catalog/Catalog.API/Startup.cs View File

@ -140,7 +140,8 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
services.AddControllers(options => services.AddControllers(options =>
{ {
options.Filters.Add(typeof(HttpGlobalExceptionFilter)); options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddNewtonsoftJson();
})
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddCors(options => services.AddCors(options =>
{ {


+ 1
- 1
src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/OrderStartedIntegrationEvent.cs View File

@ -7,7 +7,7 @@ namespace Ordering.API.Application.IntegrationEvents.Events
// An Integration Event is an event that can cause side effects to other microsrvices, Bounded-Contexts or external systems. // An Integration Event is an event that can cause side effects to other microsrvices, Bounded-Contexts or external systems.
public record OrderStartedIntegrationEvent : IntegrationEvent public record OrderStartedIntegrationEvent : IntegrationEvent
{ {
public string UserId { get; set; }
public string UserId { get; init; }
public OrderStartedIntegrationEvent(string userId) public OrderStartedIntegrationEvent(string userId)
=> UserId = userId; => UserId = userId;


+ 5
- 5
src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs View File

@ -5,15 +5,15 @@ using System;
namespace Ordering.API.Application.IntegrationEvents.Events namespace Ordering.API.Application.IntegrationEvents.Events
{ {
public record UserCheckoutAcceptedIntegrationEvent : IntegrationEvent public record UserCheckoutAcceptedIntegrationEvent : IntegrationEvent
{
{
public string UserId { get; } public string UserId { get; }
public string UserName { get; } public string UserName { get; }
public string City { get; set; } public string City { get; set; }
public string Street { get; set; } public string Street { get; set; }
public string State { get; set; } public string State { get; set; }
public string Country { get; set; } public string Country { get; set; }


+ 3
- 3
src/Services/Ordering/Ordering.API/Application/Models/CustomerBasket.cs View File

@ -7,10 +7,10 @@ namespace Ordering.API.Application.Models
public string BuyerId { get; set; } public string BuyerId { get; set; }
public List<BasketItem> Items { get; set; } public List<BasketItem> Items { get; set; }
public CustomerBasket(string customerId)
public CustomerBasket(string buyerId, List<BasketItem> items)
{ {
BuyerId = customerId;
Items = new List<BasketItem>();
BuyerId = buyerId;
Items = items;
} }
} }
} }

+ 1
- 2
src/Services/Ordering/Ordering.API/Ordering.API.csproj View File

@ -54,8 +54,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" /> <PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Microsoft.NETCore.Platforms" Version="5.0.0" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="5.0.0" />


+ 2
- 3
src/Services/Ordering/Ordering.API/Startup.cs View File

@ -172,9 +172,8 @@
}) })
// Added for functional tests // Added for functional tests
.AddApplicationPart(typeof(OrdersController).Assembly) .AddApplicationPart(typeof(OrdersController).Assembly)
.AddNewtonsoftJson()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
;
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddCors(options => services.AddCors(options =>
{ {


+ 3
- 3
src/Services/Ordering/Ordering.FunctionalTests/OrderingScenarios.cs View File

@ -1,7 +1,7 @@
using Newtonsoft.Json;
using System.Net;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebMVC.Services.ModelDTOs; using WebMVC.Services.ModelDTOs;
using Xunit; using Xunit;
@ -55,7 +55,7 @@ namespace Ordering.FunctionalTests
{ {
OrderNumber = "-1" OrderNumber = "-1"
}; };
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
} }
} }
} }

+ 3
- 5
src/Services/Webhooks/Webhooks.API/Model/WebhookData.cs View File

@ -1,5 +1,5 @@
using Newtonsoft.Json;
using System;
using System;
using System.Text.Json;
namespace Webhooks.API.Model namespace Webhooks.API.Model
{ {
@ -15,9 +15,7 @@ namespace Webhooks.API.Model
{ {
When = DateTime.UtcNow; When = DateTime.UtcNow;
Type = hookType.ToString(); Type = hookType.ToString();
Payload = JsonConvert.SerializeObject(data);
Payload = JsonSerializer.Serialize(data);
} }
} }
} }

+ 2
- 2
src/Services/Webhooks/Webhooks.API/Services/WebhooksSender.cs View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Webhooks.API.Model; using Webhooks.API.Model;
@ -23,7 +23,7 @@ namespace Webhooks.API.Services
public async Task SendAll(IEnumerable<WebhookSubscription> receivers, WebhookData data) public async Task SendAll(IEnumerable<WebhookSubscription> receivers, WebhookData data)
{ {
var client = _httpClientFactory.CreateClient(); var client = _httpClientFactory.CreateClient();
var json = JsonConvert.SerializeObject(data);
var json = JsonSerializer.Serialize(data);
var tasks = receivers.Select(r => OnSendData(r, json, client)); var tasks = receivers.Select(r => OnSendData(r, json, client));
await Task.WhenAll(tasks.ToArray()); await Task.WhenAll(tasks.ToArray());
} }


+ 11
- 5
src/Tests/Services/Application.FunctionalTests/Services/IntegrationEventsScenarios.cs View File

@ -3,12 +3,12 @@ using FunctionalTests.Services.Catalog;
using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.eShopOnContainers.Services.Catalog.API.Model; using Microsoft.eShopOnContainers.Services.Catalog.API.Model;
using Microsoft.eShopOnContainers.Services.Catalog.API.ViewModel; using Microsoft.eShopOnContainers.Services.Catalog.API.ViewModel;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -35,7 +35,7 @@ namespace FunctionalTests.Services
var basket = ComposeBasket(userId, originalCatalogProducts.Data.Take(3)); var basket = ComposeBasket(userId, originalCatalogProducts.Data.Take(3));
var res = await basketClient.PostAsync( var res = await basketClient.PostAsync(
BasketScenariosBase.Post.CreateBasket, BasketScenariosBase.Post.CreateBasket,
new StringContent(JsonConvert.SerializeObject(basket), UTF8Encoding.UTF8, "application/json")
new StringContent(JsonSerializer.Serialize(basket), UTF8Encoding.UTF8, "application/json")
); );
// WHEN the price of one product is modified in the catalog // WHEN the price of one product is modified in the catalog
@ -74,7 +74,10 @@ namespace FunctionalTests.Services
{ {
//get the basket and verify that the price of the modified product is updated //get the basket and verify that the price of the modified product is updated
var basketGetResponse = await basketClient.GetAsync(BasketScenariosBase.Get.GetBasketByCustomer(userId)); var basketGetResponse = await basketClient.GetAsync(BasketScenariosBase.Get.GetBasketByCustomer(userId));
var basketUpdated = JsonConvert.DeserializeObject<CustomerBasket>(await basketGetResponse.Content.ReadAsStringAsync());
var basketUpdated = JsonSerializer.Deserialize<CustomerBasket>(await basketGetResponse.Content.ReadAsStringAsync(), new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
itemUpdated = basketUpdated.Items.Single(pr => pr.ProductId == productId); itemUpdated = basketUpdated.Items.Single(pr => pr.ProductId == productId);
@ -96,14 +99,17 @@ namespace FunctionalTests.Services
{ {
var response = await catalogClient.GetAsync(CatalogScenariosBase.Get.Items); var response = await catalogClient.GetAsync(CatalogScenariosBase.Get.Items);
var items = await response.Content.ReadAsStringAsync(); var items = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PaginatedItemsViewModel<CatalogItem>>(items);
return JsonSerializer.Deserialize<PaginatedItemsViewModel<CatalogItem>>(items, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
private string ChangePrice(BasketItem itemToModify, decimal newPrice, PaginatedItemsViewModel<CatalogItem> catalogProducts) private string ChangePrice(BasketItem itemToModify, decimal newPrice, PaginatedItemsViewModel<CatalogItem> catalogProducts)
{ {
var catalogProduct = catalogProducts.Data.Single(pr => pr.Id == itemToModify.ProductId); var catalogProduct = catalogProducts.Data.Single(pr => pr.Id == itemToModify.ProductId);
catalogProduct.Price = newPrice; catalogProduct.Price = newPrice;
return JsonConvert.SerializeObject(catalogProduct);
return JsonSerializer.Serialize(catalogProduct);
} }
private CustomerBasket ComposeBasket(string customerId, IEnumerable<CatalogItem> items) private CustomerBasket ComposeBasket(string customerId, IEnumerable<CatalogItem> items)


+ 17
- 7
src/Tests/Services/Application.FunctionalTests/Services/Ordering/OrderingScenarios.cs View File

@ -2,8 +2,8 @@
using FunctionalTests.Services.Basket; using FunctionalTests.Services.Basket;
using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Newtonsoft.Json;
using System; using System;
using System.Text.Json;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
@ -53,7 +53,10 @@ namespace FunctionalTests.Services.Ordering
async Task<Order> TryGetOrder(string orderNumber, HttpClient orderClient) async Task<Order> TryGetOrder(string orderNumber, HttpClient orderClient)
{ {
var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders); var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders);
var orders = JsonConvert.DeserializeObject<List<Order>>(ordersGetResponse);
var orders = JsonSerializer.Deserialize<List<Order>>(ordersGetResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return orders.Single(o => o.OrderNumber == orderNumber); return orders.Single(o => o.OrderNumber == orderNumber);
} }
@ -67,7 +70,10 @@ namespace FunctionalTests.Services.Ordering
{ {
//get the orders and verify that the new order has been created //get the orders and verify that the new order has been created
var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders); var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders);
var orders = JsonConvert.DeserializeObject<List<Order>>(ordersGetResponse);
var orders = JsonSerializer.Deserialize<List<Order>>(ordersGetResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (orders == null || orders.Count == 0) if (orders == null || orders.Count == 0)
{ {
@ -79,7 +85,11 @@ namespace FunctionalTests.Services.Ordering
var lastOrder = orders.OrderByDescending(o => o.Date).First(); var lastOrder = orders.OrderByDescending(o => o.Date).First();
int.TryParse(lastOrder.OrderNumber, out int id); int.TryParse(lastOrder.OrderNumber, out int id);
var orderDetails = await orderClient.GetStringAsync(OrderingScenariosBase.Get.OrderBy(id)); var orderDetails = await orderClient.GetStringAsync(OrderingScenariosBase.Get.OrderBy(id));
order = JsonConvert.DeserializeObject<Order>(orderDetails);
order = JsonSerializer.Deserialize<Order>(orderDetails, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
order.City = city; order.City = city;
if (IsOrderCreated(order, city)) if (IsOrderCreated(order, city))
@ -110,7 +120,7 @@ namespace FunctionalTests.Services.Ordering
Quantity = 1 Quantity = 1
} }
}; };
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
} }
string BuildCancelOrder(string orderId) string BuildCancelOrder(string orderId)
@ -119,7 +129,7 @@ namespace FunctionalTests.Services.Ordering
{ {
OrderNumber = orderId OrderNumber = orderId
}; };
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
} }
string BuildCheckout(string cityExpected) string BuildCheckout(string cityExpected)
@ -140,7 +150,7 @@ namespace FunctionalTests.Services.Ordering
RequestId = Guid.NewGuid() RequestId = Guid.NewGuid()
}; };
return JsonConvert.SerializeObject(checkoutBasket);
return JsonSerializer.Serialize(checkoutBasket);
} }
} }
} }

+ 2
- 2
src/Web/WebMVC/Controllers/TestController.cs View File

@ -2,9 +2,9 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Newtonsoft.Json;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text.Json;
namespace WebMVC.Controllers namespace WebMVC.Controllers
{ {
@ -40,7 +40,7 @@ namespace WebMVC.Controllers
BasketId = _appUserParser.Parse(User).Id BasketId = _appUserParser.Parse(User).Id
}; };
var content = new StringContent(JsonConvert.SerializeObject(payload), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");
var response = await _client.CreateClient(nameof(IBasketService)) var response = await _client.CreateClient(nameof(IBasketService))


+ 6
- 3
src/Web/WebMVC/Extensions/SessionExtensions.cs View File

@ -1,17 +1,20 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text.Json;
public static class SessionExtensions 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, JsonConvert.SerializeObject(value));
session.SetString(key,JsonSerializer.Serialize(value));
public static T GetObject<T>(this ISession session, string key) public static T GetObject<T>(this ISession session, string key)
{ {
var value = session.GetString(key); var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
return value == null ? default(T) :JsonSerializer.Deserialize<T>(value, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
} }

+ 18
- 9
src/Web/WebMVC/Services/BasketService.cs View File

@ -1,13 +1,13 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebMVC.Infrastructure; using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs; using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services namespace Microsoft.eShopOnContainers.WebMVC.Services
{ {
@ -38,14 +38,17 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await response.Content.ReadAsStringAsync(); var responseString = await response.Content.ReadAsStringAsync();
return string.IsNullOrEmpty(responseString) ? return string.IsNullOrEmpty(responseString) ?
new Basket() { BuyerId = user.Id } : new Basket() { BuyerId = user.Id } :
JsonConvert.DeserializeObject<Basket>(responseString);
JsonSerializer.Deserialize<Basket>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
public async Task<Basket> UpdateBasket(Basket basket) public async Task<Basket> UpdateBasket(Basket basket)
{ {
var uri = API.Basket.UpdateBasket(_basketByPassUrl); var uri = API.Basket.UpdateBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
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);
@ -57,8 +60,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
public async Task Checkout(BasketDTO basket) public async Task Checkout(BasketDTO basket)
{ {
var uri = API.Basket.CheckoutBasket(_basketByPassUrl); var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
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);
@ -80,7 +83,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
}).ToArray() }).ToArray()
}; };
var basketContent = new StringContent(JsonConvert.SerializeObject(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);
@ -88,7 +91,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Basket>(jsonResponse);
return JsonSerializer.Deserialize<Basket>(jsonResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
} }
public async Task<Order> GetOrderDraft(string basketId) public async Task<Order> GetOrderDraft(string basketId)
@ -97,7 +103,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _apiClient.GetStringAsync(uri); var responseString = await _apiClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<Order>(responseString);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response; return response;
} }
@ -113,7 +122,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
Quantity = 1 Quantity = 1
}; };
var basketContent = new StringContent(JsonConvert.SerializeObject(newItem), System.Text.Encoding.UTF8, "application/json");
var basketContent = new StringContent(JsonSerializer.Serialize(newItem), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, basketContent); var response = await _apiClient.PostAsync(uri, basketContent);
} }


+ 15
- 12
src/Web/WebMVC/Services/CatalogService.cs View File

@ -2,12 +2,11 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebMVC.Infrastructure; using WebMVC.Infrastructure;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services namespace Microsoft.eShopOnContainers.WebMVC.Services
{ {
@ -34,7 +33,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri); var responseString = await _httpClient.GetStringAsync(uri);
var catalog = JsonConvert.DeserializeObject<Catalog>(responseString);
var catalog = JsonSerializer.Deserialize<Catalog>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return catalog; return catalog;
} }
@ -48,15 +50,15 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var items = new List<SelectListItem>(); var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true }); items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var brands = JsonDocument.Parse(responseString);
var brands = JArray.Parse(responseString);
foreach (var brand in brands.Children<JObject>())
foreach (JsonElement brand in brands.RootElement.EnumerateArray())
{ {
items.Add(new SelectListItem() items.Add(new SelectListItem()
{ {
Value = brand.Value<string>("id"),
Text = brand.Value<string>("brand")
Value = brand.GetProperty("id").ToString(),
Text = brand.GetProperty("brand").ToString()
}); });
} }
@ -71,14 +73,15 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var items = new List<SelectListItem>(); var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true }); items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var catalogTypes = JsonDocument.Parse(responseString);
var brands = JArray.Parse(responseString);
foreach (var brand in brands.Children<JObject>())
foreach (JsonElement catalogType in catalogTypes.RootElement.EnumerateArray())
{ {
items.Add(new SelectListItem() items.Add(new SelectListItem()
{ {
Value = brand.Value<string>("id"),
Text = brand.Value<string>("type")
Value = catalogType.GetProperty("id").ToString(),
Text = catalogType.GetProperty("type").ToString()
}); });
} }


+ 11
- 5
src/Web/WebMVC/Services/OrderingService.cs View File

@ -1,12 +1,12 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels; using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebMVC.Infrastructure; using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs; using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services namespace Microsoft.eShopOnContainers.WebMVC.Services
{ {
@ -31,7 +31,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri); var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<Order>(responseString);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response; return response;
} }
@ -42,7 +45,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri); var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<List<Order>>(responseString);
var response = JsonSerializer.Deserialize<List<Order>>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response; return response;
} }
@ -57,7 +63,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
}; };
var uri = API.Order.CancelOrder(_remoteServiceBaseUrl); var uri = API.Order.CancelOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonConvert.SerializeObject(order), System.Text.Encoding.UTF8, "application/json");
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent); var response = await _httpClient.PutAsync(uri, orderContent);
@ -77,7 +83,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
}; };
var uri = API.Order.ShipOrder(_remoteServiceBaseUrl); var uri = API.Order.ShipOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonConvert.SerializeObject(order), System.Text.Encoding.UTF8, "application/json");
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent); var response = await _httpClient.PutAsync(uri, orderContent);


+ 1
- 1
src/Web/WebMVC/ViewModels/BasketItem.cs View File

@ -3,7 +3,7 @@
public record BasketItem public record BasketItem
{ {
public string Id { get; init; } public string Id { get; init; }
public string 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 OldUnitPrice { get; init; } public decimal OldUnitPrice { get; init; }


+ 34
- 0
src/Web/WebMVC/ViewModels/Converters/NumberToStringConverter.cs View File

@ -0,0 +1,34 @@
using System;
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 override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number)
{
var numberValue = reader.GetInt32();
return numberValue.ToString();
}
else if (reader.TokenType == JsonTokenType.String)
{
return reader.GetString();
}
else
{
throw new JsonException();
}
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
}

+ 5
- 7
src/Web/WebMVC/ViewModels/Order.cs View File

@ -1,16 +1,17 @@
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations; using Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using WebMVC.Services.ModelDTOs; using WebMVC.Services.ModelDTOs;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels namespace Microsoft.eShopOnContainers.WebMVC.ViewModels
{ {
public class Order public class Order
{
{
[JsonConverter(typeof(NumberToStringConverter))]
public string OrderNumber { get; set; } public string OrderNumber { get; set; }
public DateTime Date { get; set; } public DateTime Date { get; set; }
@ -53,11 +54,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.ViewModels
public List<SelectListItem> ActionCodeSelectList => public List<SelectListItem> ActionCodeSelectList =>
GetActionCodesByCurrentState(); GetActionCodesByCurrentState();
// See the property initializer syntax below. This
// initializes the compiler generated field for this
// auto-implemented property.
public List<OrderItem> OrderItems { get; } = new List<OrderItem>();
public List<OrderItem> OrderItems { get; set; }
[Required] [Required]
public Guid RequestId { get; set; } public Guid RequestId { get; set; }


+ 1
- 2
src/Web/WebSPA/WebSPA.csproj View File

@ -94,8 +94,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />
</ItemGroup> </ItemGroup>


+ 2
- 2
src/Web/WebhookClient/Pages/RegisterWebhook.cshtml.cs View File

@ -2,12 +2,12 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Formatting; using System.Net.Http.Formatting;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebhookClient.Models; using WebhookClient.Models;
using System.Text.Json;
namespace WebhookClient.Pages namespace WebhookClient.Pages
{ {
@ -66,7 +66,7 @@ namespace WebhookClient.Pages
} }
else else
{ {
RequestBodyJson = JsonConvert.SerializeObject(payload);
RequestBodyJson = JsonSerializer.Serialize(payload);
ResponseCode = (int)response.StatusCode; ResponseCode = (int)response.StatusCode;
ResponseMessage = response.ReasonPhrase; ResponseMessage = response.ReasonPhrase;
GrantUrl = granturl; GrantUrl = granturl;


+ 5
- 2
src/Web/WebhookClient/Services/WebhooksClient.cs View File

@ -1,9 +1,9 @@
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebhookClient.Models; using WebhookClient.Models;
using System.Text.Json;
namespace WebhookClient.Services namespace WebhookClient.Services
{ {
@ -22,7 +22,10 @@ namespace WebhookClient.Services
var client = _httpClientFactory.CreateClient("GrantClient"); var client = _httpClientFactory.CreateClient("GrantClient");
var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks"); var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks");
var json = await response.Content.ReadAsStringAsync(); var json = await response.Content.ReadAsStringAsync();
var subscriptions = JsonConvert.DeserializeObject<IEnumerable<WebhookResponse>>(json);
var subscriptions = JsonSerializer.Deserialize<IEnumerable<WebhookResponse>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return subscriptions; return subscriptions;
} }
} }


Loading…
Cancel
Save