Skip to content

Commit 8a87c10

Browse files
Merge branch 'main' into seo/75608-csharp-concurrent-collections
2 parents 63842c1 + 3c13dae commit 8a87c10

157 files changed

Lines changed: 2758 additions & 1642 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.Extensions.Caching.Distributed;
2-
using Microsoft.Extensions.Caching.Memory;
32
using Microsoft.Extensions.DependencyInjection;
43
using SerializationDemo.Client.Serialization;
54
using SerializationDemo.Client.Serialization.Json;
@@ -9,30 +8,30 @@
98
namespace SerializationDemo.Client.Clients
109
{
1110
internal class CachedJsonClient : ClientBase, IClient
12-
{
11+
{
1312
private readonly IByteSerializer _serializer = new JsonByteSerializer();
1413
private readonly HttpClient _client = new HttpClient();
1514
private readonly IDistributedCache _distributedCache;
1615
private const string AllEmployeesKey = "AllEmployees";
1716

1817
public CachedJsonClient()
19-
{
18+
{
2019
var collection = new ServiceCollection();
2120
collection.AddDistributedMemoryCache();
2221
IServiceProvider serviceProvider = collection.BuildServiceProvider();
2322

24-
_distributedCache = serviceProvider.GetService<IDistributedCache>();
23+
_distributedCache = serviceProvider.GetRequiredService<IDistributedCache>();
2524
}
2625

2726
public async Task<List<Employee>> GetAllEmployees()
2827
{
2928
// Find cached item
30-
byte[] objectFromCache = await _distributedCache.GetAsync(AllEmployeesKey);
29+
byte[]? objectFromCache = await _distributedCache.GetAsync(AllEmployeesKey);
3130

3231
if (objectFromCache != null)
33-
{
32+
{
3433
var employees = _serializer.Deserialize<List<Employee>>(objectFromCache);
35-
return employees;
34+
return employees ?? [];
3635
}
3736

3837
return await RefreshCache();
@@ -43,25 +42,25 @@ private async Task<HttpContent> GetResponseFromApi()
4342
var url = $"{BaseUrl}/api/employees";
4443
var request = new HttpRequestMessage(HttpMethod.Get, url);
4544
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
46-
45+
4746
var response = await _client.SendAsync(request);
48-
49-
return response.Content;
47+
48+
return response.Content;
5049
}
5150

52-
public async Task<Employee> CreateEmployee(Employee employee)
51+
public async Task<Employee?> CreateEmployee(Employee employee)
5352
{
5453
var url = $"{BaseUrl}/api/employees";
5554
var request = new HttpRequestMessage(HttpMethod.Post, url);
5655
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
5756
request.Content = new ByteArrayContent(_serializer.Serialize(employee));
58-
request.Content.Headers.Add("Content-Type", "application/json");
59-
57+
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
58+
6059
var response = await _client.SendAsync(request);
6160

6261
if (response.IsSuccessStatusCode)
6362
{
64-
await RefreshCache();
63+
await RefreshCache();
6564
}
6665

6766
return employee;
@@ -71,16 +70,17 @@ private async Task<List<Employee>> RefreshCache()
7170
{
7271
// If not found, then recalculate response
7372
var content = await GetResponseFromApi();
73+
var employees = _serializer.Deserialize<List<Employee>>(await content.ReadAsByteArrayAsync()) ?? [];
7474

7575
var cacheEntryOptions = new DistributedCacheEntryOptions()
76-
.SetSlidingExpiration(TimeSpan.FromSeconds(10))
77-
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30));
76+
.SetSlidingExpiration(TimeSpan.FromSeconds(10))
77+
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30));
7878

7979
// Cache it
80-
var resultAsByteArray = _serializer.Serialize(await content.ReadAsStringAsync());
80+
var resultAsByteArray = _serializer.Serialize(employees);
8181
await _distributedCache.SetAsync(AllEmployeesKey, resultAsByteArray, cacheEntryOptions);
8282

83-
return _serializer.Deserialize<List<Employee>>(resultAsByteArray);
83+
return employees;
8484
}
8585
}
86-
}
86+
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Clients/IClient.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
namespace SerializationDemo.Client.Clients
44
{
55
internal interface IClient
6-
{
6+
{
77
Task<List<Employee>> GetAllEmployees();
8-
Task<Employee> CreateEmployee(Employee employee);
8+
Task<Employee?> CreateEmployee(Employee employee);
99
}
10-
}
10+
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Clients/JsonClient.cs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,16 @@
77
namespace SerializationDemo.Client.Clients
88
{
99
internal class JsonClient : ClientBase, IClient
10-
{
10+
{
1111
private readonly IStringSerializer _serializer = new JsonStringSerializer();
1212
private readonly HttpClient _client = new HttpClient();
1313

14-
public async Task<Employee> CreateEmployee(Employee employee)
14+
public async Task<Employee?> CreateEmployee(Employee employee)
1515
{
1616
var url = $"{BaseUrl}/api/employees";
1717
var request = new HttpRequestMessage(HttpMethod.Post, url);
18-
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
19-
request.Content = new StringContent(_serializer.Serialize(employee), Encoding.UTF8,"application/json");
18+
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
19+
request.Content = new StringContent(_serializer.Serialize(employee), Encoding.UTF8, "application/json");
2020

2121
var response = await _client.SendAsync(request);
2222

@@ -37,8 +37,8 @@ public async Task<List<Employee>> GetAllEmployees()
3737

3838
var response = await _client.SendAsync(request);
3939
var content = await response.Content.ReadAsStringAsync();
40-
41-
return _serializer.Deserialize<List<Employee>>(content);
40+
41+
return _serializer.Deserialize<List<Employee>>(content) ?? [];
4242
}
4343
}
4444
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Clients/ProtobufClient.cs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@
66
namespace SerializationDemo.Client.Clients
77
{
88
internal class ProtobufClient : ClientBase, IClient
9-
{
9+
{
1010
private readonly IByteSerializer _serializer = new ProtobufSerializer();
1111
private readonly HttpClient _client = new HttpClient();
1212

13-
public async Task<Employee> CreateEmployee(Employee employee)
13+
public async Task<Employee?> CreateEmployee(Employee employee)
1414
{
1515
var url = $"{BaseUrl}/api/employees";
1616
var request = new HttpRequestMessage(HttpMethod.Post, url);
17-
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
17+
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
1818
request.Content = new ByteArrayContent(_serializer.Serialize(employee));
19-
request.Content.Headers.Add("Content-Type", "application/x-protobuf");
19+
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");
2020

2121
var response = await _client.SendAsync(request);
2222

@@ -34,11 +34,11 @@ public async Task<List<Employee>> GetAllEmployees()
3434
var url = $"{BaseUrl}/api/employees";
3535
var request = new HttpRequestMessage(HttpMethod.Get, url);
3636
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
37-
37+
3838
var response = await _client.SendAsync(request);
3939
var content = await response.Content.ReadAsByteArrayAsync();
40-
41-
return _serializer.Deserialize<List<Employee>>(content);
40+
41+
return _serializer.Deserialize<List<Employee>>(content) ?? [];
4242
}
4343
}
4444
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Clients/XmlClient.cs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@
77
namespace SerializationDemo.Client.Clients
88
{
99
internal class XmlClient : ClientBase, IClient
10-
{
10+
{
1111
private readonly IStringSerializer _serializer = new XmlSerializer();
1212
private readonly HttpClient _client = new HttpClient();
1313

14-
public async Task<Employee> CreateEmployee(Employee employee)
14+
public async Task<Employee?> CreateEmployee(Employee employee)
1515
{
1616
var url = $"{BaseUrl}/api/employees";
1717
var request = new HttpRequestMessage(HttpMethod.Post, url);
18-
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
18+
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
1919
request.Content = new StringContent(_serializer.Serialize(employee), Encoding.UTF8, "application/xml");
20-
20+
2121
var response = await _client.SendAsync(request);
2222

2323
if (response.IsSuccessStatusCode)
@@ -34,11 +34,11 @@ public async Task<List<Employee>> GetAllEmployees()
3434
var url = $"{BaseUrl}/api/employees";
3535
var request = new HttpRequestMessage(HttpMethod.Get, url);
3636
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
37-
37+
3838
var response = await _client.SendAsync(request);
3939
var content = await response.Content.ReadAsStringAsync();
40-
41-
return _serializer.Deserialize<List<Employee>>(content);
40+
41+
return _serializer.Deserialize<List<Employee>>(content) ?? [];
4242
}
4343
}
4444
}
Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
// See https://aka.ms/new-console-template for more information
2-
using SerializationDemo.Client.Clients;
1+
using SerializationDemo.Client.Clients;
32
using SerializationDemo.Common.Models;
43

5-
64
Console.Write("Enter a format name(json, cache, xml, proto): ");
75
string? format = Console.ReadLine();
86
format = format?.Trim().ToLower();
@@ -16,42 +14,42 @@
1614
_ => new JsonClient()
1715
};
1816

19-
Console.WriteLine("Employee list before adding employee.");
17+
Console.WriteLine();
18+
Console.WriteLine("Employee list before adding an employee.");
2019
Console.WriteLine("--------------------------------------");
21-
PrintAllEmployees(client);
22-
CreateEmployee(client);
20+
await PrintAllEmployees(client);
21+
await CreateEmployee(client);
2322
Console.WriteLine();
24-
Console.WriteLine("Employee list after adding employee.");
23+
Console.WriteLine("Employee list after adding an employee.");
2524
Console.WriteLine("--------------------------------------");
26-
PrintAllEmployees(client);
25+
await PrintAllEmployees(client);
2726

28-
static void PrintAllEmployees(IClient client)
27+
static async Task PrintAllEmployees(IClient client)
2928
{
30-
var employees = client.GetAllEmployees().Result;
29+
var employees = await client.GetAllEmployees();
3130
foreach (var employee in employees)
3231
{
3332
Console.WriteLine($"Name:{employee.Name}");
34-
Console.WriteLine($"Address:{employee?.Address?.AddressLine1}, {employee?.Address?.AddressLine2}, {employee?.Address?.City}, {employee?.Address?.Country}");
35-
Console.WriteLine();
33+
Console.WriteLine($"Address:{employee.Address?.AddressLine1}, {employee.Address?.AddressLine2}, {employee.Address?.City}, {employee.Address?.Country}");
3634
Console.WriteLine();
3735
}
3836
}
3937

40-
static void CreateEmployee(IClient client)
38+
static async Task CreateEmployee(IClient client)
4139
{
4240
var employee = new Employee
4341
{
4442
Id = Guid.NewGuid(),
45-
Name = $"TestEmployee6",
43+
Name = "TestEmployee6",
4644
Address = new Address
4745
{
48-
AddressLine1 = $"Street #6",
49-
AddressLine2 = $"District #6",
50-
City = $"Sample City30",
51-
Country = $"Sample Country22",
46+
AddressLine1 = "Street #6",
47+
AddressLine2 = "District #6",
48+
City = "Sample City30",
49+
Country = "Sample Country22",
5250
}
5351
};
5452

55-
var neweEmployee = client.CreateEmployee(employee).Result;
56-
Console.WriteLine($"New employee {neweEmployee?.Name} has been added");
57-
}
53+
var newEmployee = await client.CreateEmployee(employee);
54+
Console.WriteLine($"New employee {newEmployee?.Name} has been added");
55+
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Serialization/IByteSerializer.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
{
33
internal interface IByteSerializer
44
{
5-
T Deserialize<T>(byte[] buffer);
5+
T? Deserialize<T>(byte[] buffer);
66

77
byte[] Serialize(object data);
88
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Serialization/IStringSerializer.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
namespace SerializationDemo.Client.Serialization
22
{
3-
internal interface IStringSerializer
3+
internal interface IStringSerializer
44
{
5-
T Deserialize<T>(string text);
5+
T? Deserialize<T>(string text);
66

77
string Serialize(object data);
88
}

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Serialization/Json/JsonByteSerializer.cs‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ namespace SerializationDemo.Client.Serialization.Json
55
public class JsonByteSerializer : IByteSerializer
66
{
77
private readonly JsonSerializerOptions _options;
8+
89
public JsonByteSerializer()
910
: this(GetDefaultJsonSerializerOptions())
1011
{
@@ -13,16 +14,11 @@ public JsonByteSerializer()
1314
public JsonByteSerializer(JsonSerializerOptions options)
1415
=> _options = options;
1516

16-
public T Deserialize<T>(byte[] buffer)
17-
{
18-
using var stream = new MemoryStream(buffer);
19-
return JsonSerializer.Deserialize<T>(stream, _options);
20-
}
17+
public T? Deserialize<T>(byte[] buffer)
18+
=> JsonSerializer.Deserialize<T>(buffer, _options);
2119

2220
public byte[] Serialize(object data)
23-
{
24-
return JsonSerializer.SerializeToUtf8Bytes(data, _options);
25-
}
21+
=> JsonSerializer.SerializeToUtf8Bytes(data, _options);
2622

2723
private static JsonSerializerOptions GetDefaultJsonSerializerOptions()
2824
=> new JsonSerializerOptions(JsonSerializerDefaults.Web);

‎aspnetcore-webapi/SerializationDemo/SerializationDemo.Client/Serialization/Json/JsonStringSerializer.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public JsonStringSerializer()
1414
public JsonStringSerializer(JsonSerializerOptions options)
1515
=> _options = options;
1616

17-
public T Deserialize<T>(string text)
17+
public T? Deserialize<T>(string text)
1818
=> JsonSerializer.Deserialize<T>(text, _options);
1919

2020
public string Serialize(object data)
@@ -23,4 +23,4 @@ public string Serialize(object data)
2323
private static JsonSerializerOptions GetDefaultJsonSerializerOptions()
2424
=> new JsonSerializerOptions(JsonSerializerDefaults.Web);
2525
}
26-
}
26+
}

0 commit comments

Comments
 (0)