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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using SerializationDemo.Client.Serialization;
using SerializationDemo.Client.Serialization.Json;
Expand All @@ -9,30 +8,30 @@
namespace SerializationDemo.Client.Clients
{
internal class CachedJsonClient : ClientBase, IClient
{
{
private readonly IByteSerializer _serializer = new JsonByteSerializer();
private readonly HttpClient _client = new HttpClient();
private readonly IDistributedCache _distributedCache;
private const string AllEmployeesKey = "AllEmployees";

public CachedJsonClient()
{
{
var collection = new ServiceCollection();
collection.AddDistributedMemoryCache();
IServiceProvider serviceProvider = collection.BuildServiceProvider();

_distributedCache = serviceProvider.GetService<IDistributedCache>();
_distributedCache = serviceProvider.GetRequiredService<IDistributedCache>();
}

public async Task<List<Employee>> GetAllEmployees()
{
// Find cached item
byte[] objectFromCache = await _distributedCache.GetAsync(AllEmployeesKey);
byte[]? objectFromCache = await _distributedCache.GetAsync(AllEmployeesKey);

if (objectFromCache != null)
{
{
var employees = _serializer.Deserialize<List<Employee>>(objectFromCache);
return employees;
return employees ?? [];
}

return await RefreshCache();
Expand All @@ -43,25 +42,25 @@ private async Task<HttpContent> GetResponseFromApi()
var url = $"{BaseUrl}/api/employees";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = await _client.SendAsync(request);
return response.Content;

return response.Content;
}

public async Task<Employee> CreateEmployee(Employee employee)
public async Task<Employee?> CreateEmployee(Employee employee)
{
var url = $"{BaseUrl}/api/employees";
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new ByteArrayContent(_serializer.Serialize(employee));
request.Content.Headers.Add("Content-Type", "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var response = await _client.SendAsync(request);

if (response.IsSuccessStatusCode)
{
await RefreshCache();
await RefreshCache();
}

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

var cacheEntryOptions = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(10))
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30));
.SetSlidingExpiration(TimeSpan.FromSeconds(10))
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30));

// Cache it
var resultAsByteArray = _serializer.Serialize(await content.ReadAsStringAsync());
var resultAsByteArray = _serializer.Serialize(employees);
await _distributedCache.SetAsync(AllEmployeesKey, resultAsByteArray, cacheEntryOptions);

return _serializer.Deserialize<List<Employee>>(resultAsByteArray);
return employees;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace SerializationDemo.Client.Clients
{
internal interface IClient
{
{
Task<List<Employee>> GetAllEmployees();
Task<Employee> CreateEmployee(Employee employee);
Task<Employee?> CreateEmployee(Employee employee);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
namespace SerializationDemo.Client.Clients
{
internal class JsonClient : ClientBase, IClient
{
{
private readonly IStringSerializer _serializer = new JsonStringSerializer();
private readonly HttpClient _client = new HttpClient();

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

var response = await _client.SendAsync(request);

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

var response = await _client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return _serializer.Deserialize<List<Employee>>(content);

return _serializer.Deserialize<List<Employee>>(content) ?? [];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
namespace SerializationDemo.Client.Clients
{
internal class ProtobufClient : ClientBase, IClient
{
{
private readonly IByteSerializer _serializer = new ProtobufSerializer();
private readonly HttpClient _client = new HttpClient();

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

var response = await _client.SendAsync(request);

Expand All @@ -34,11 +34,11 @@ public async Task<List<Employee>> GetAllEmployees()
var url = $"{BaseUrl}/api/employees";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));

var response = await _client.SendAsync(request);
var content = await response.Content.ReadAsByteArrayAsync();
return _serializer.Deserialize<List<Employee>>(content);

return _serializer.Deserialize<List<Employee>>(content) ?? [];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
namespace SerializationDemo.Client.Clients
{
internal class XmlClient : ClientBase, IClient
{
{
private readonly IStringSerializer _serializer = new XmlSerializer();
private readonly HttpClient _client = new HttpClient();

public async Task<Employee> CreateEmployee(Employee employee)
public async Task<Employee?> CreateEmployee(Employee employee)
{
var url = $"{BaseUrl}/api/employees";
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Content = new StringContent(_serializer.Serialize(employee), Encoding.UTF8, "application/xml");

var response = await _client.SendAsync(request);

if (response.IsSuccessStatusCode)
Expand All @@ -34,11 +34,11 @@ public async Task<List<Employee>> GetAllEmployees()
var url = $"{BaseUrl}/api/employees";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

var response = await _client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return _serializer.Deserialize<List<Employee>>(content);

return _serializer.Deserialize<List<Employee>>(content) ?? [];
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// See https://aka.ms/new-console-template for more information
using SerializationDemo.Client.Clients;
using SerializationDemo.Client.Clients;
using SerializationDemo.Common.Models;


Console.Write("Enter a format name(json, cache, xml, proto): ");
string? format = Console.ReadLine();
format = format?.Trim().ToLower();
Expand All @@ -16,42 +14,42 @@
_ => new JsonClient()
};

Console.WriteLine("Employee list before adding employee.");
Console.WriteLine();
Console.WriteLine("Employee list before adding an employee.");
Console.WriteLine("--------------------------------------");
PrintAllEmployees(client);
CreateEmployee(client);
await PrintAllEmployees(client);
await CreateEmployee(client);
Console.WriteLine();
Console.WriteLine("Employee list after adding employee.");
Console.WriteLine("Employee list after adding an employee.");
Console.WriteLine("--------------------------------------");
PrintAllEmployees(client);
await PrintAllEmployees(client);

static void PrintAllEmployees(IClient client)
static async Task PrintAllEmployees(IClient client)
{
var employees = client.GetAllEmployees().Result;
var employees = await client.GetAllEmployees();
foreach (var employee in employees)
{
Console.WriteLine($"Name:{employee.Name}");
Console.WriteLine($"Address:{employee?.Address?.AddressLine1}, {employee?.Address?.AddressLine2}, {employee?.Address?.City}, {employee?.Address?.Country}");
Console.WriteLine();
Console.WriteLine($"Address:{employee.Address?.AddressLine1}, {employee.Address?.AddressLine2}, {employee.Address?.City}, {employee.Address?.Country}");
Console.WriteLine();
}
}

static void CreateEmployee(IClient client)
static async Task CreateEmployee(IClient client)
{
var employee = new Employee
{
Id = Guid.NewGuid(),
Name = $"TestEmployee6",
Name = "TestEmployee6",
Address = new Address
{
AddressLine1 = $"Street #6",
AddressLine2 = $"District #6",
City = $"Sample City30",
Country = $"Sample Country22",
AddressLine1 = "Street #6",
AddressLine2 = "District #6",
City = "Sample City30",
Country = "Sample Country22",
}
};

var neweEmployee = client.CreateEmployee(employee).Result;
Console.WriteLine($"New employee {neweEmployee?.Name} has been added");
}
var newEmployee = await client.CreateEmployee(employee);
Console.WriteLine($"New employee {newEmployee?.Name} has been added");
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
{
internal interface IByteSerializer
{
T Deserialize<T>(byte[] buffer);
T? Deserialize<T>(byte[] buffer);

byte[] Serialize(object data);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
namespace SerializationDemo.Client.Serialization
{
internal interface IStringSerializer
internal interface IStringSerializer
{
T Deserialize<T>(string text);
T? Deserialize<T>(string text);

string Serialize(object data);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace SerializationDemo.Client.Serialization.Json
public class JsonByteSerializer : IByteSerializer
{
private readonly JsonSerializerOptions _options;

public JsonByteSerializer()
: this(GetDefaultJsonSerializerOptions())
{
Expand All @@ -13,16 +14,11 @@ public JsonByteSerializer()
public JsonByteSerializer(JsonSerializerOptions options)
=> _options = options;

public T Deserialize<T>(byte[] buffer)
{
using var stream = new MemoryStream(buffer);
return JsonSerializer.Deserialize<T>(stream, _options);
}
public T? Deserialize<T>(byte[] buffer)
=> JsonSerializer.Deserialize<T>(buffer, _options);

public byte[] Serialize(object data)
{
return JsonSerializer.SerializeToUtf8Bytes(data, _options);
}
=> JsonSerializer.SerializeToUtf8Bytes(data, _options);

private static JsonSerializerOptions GetDefaultJsonSerializerOptions()
=> new JsonSerializerOptions(JsonSerializerDefaults.Web);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public JsonStringSerializer()
public JsonStringSerializer(JsonSerializerOptions options)
=> _options = options;

public T Deserialize<T>(string text)
public T? Deserialize<T>(string text)
=> JsonSerializer.Deserialize<T>(text, _options);

public string Serialize(object data)
Expand All @@ -23,4 +23,4 @@ public string Serialize(object data)
private static JsonSerializerOptions GetDefaultJsonSerializerOptions()
=> new JsonSerializerOptions(JsonSerializerDefaults.Web);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@ namespace SerializationDemo.Client.Serialization.Protobuf
{
public class ProtobufSerializer : IByteSerializer
{
public T Deserialize<T>(byte[] buffer)
public T? Deserialize<T>(byte[] buffer)
{
using (var stream = new MemoryStream(buffer))
{
return Serializer.Deserialize<T>(stream);
}
using var stream = new MemoryStream(buffer);

return Serializer.Deserialize<T>(stream);
}

public byte[] Serialize(object data)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, data);
stream.Flush();
using var stream = new MemoryStream();
Serializer.Serialize(stream, data);

return stream.ToArray();
}
return stream.ToArray();
}
}
}
Loading
Loading