title
stringlengths
3
46
content
stringlengths
0
1.6k
21:825
Then, we deserialize the message body to get a PurchaseMessage instance and add it to the database:
21:826
var body = ea.Body.ToArray();
21:827
PurchaseMessage? message = null;
21:828
using (var stream = new MemoryStream(body))
21:829
{
21:830
message = PurchaseMessage.Parser.ParseFrom(stream);
21:831
}
21:832
var res = await statistics.Add(new Purchase {
21:833
Cost= message.Cost,
21:834
Id= Guid.Parse(message.Id),
21:835
Location = message.Location,
21:836
Time = new DateTimeOffset(message.Time.ToDateTime(), TimeSpan.Zero),
21:837
PurchaseTime = new DateTimeOffset(message.PurchaseTime.ToDateTime(), TimeSpan.Zero)
21:838
});
21:839
21:840
If the operation fails, the Add operation returns null, so we must send a Nack; otherwise, we must send an Ack:
21:841
if(res != null)
21:842
((EventingBasicConsumer)sender).Model
21:843
.BasicAck(ea.DeliveryTag, false);
21:844
else
21:845
((EventingBasicConsumer)sender).Model
21:846
.BasicNack(ea.DeliveryTag, false, true);
21:847
21:848
That’s all! The full code is in the GrpcMicroServiceRabbitProto subfolder of the ch15 folder in the GitHub repository of this book. You can test the code by setting both the client and server projects as the start project and running the solution. After 1–2 minutes, the database should be populated with new purchases and new daily totals. In a staging/production environment, you can run several copies of both the client and server.
21:849
The GrpcMicroServiceRabbit subfolder in the ch15 folder of the GitHub repository contains another version of the same application that uses the Binaron NuGet package for serialization. It is faster than ProtoBuf, but being .NET-specific, it is not interoperable. Moreover, it has no features to facilitate message versioning. It is useful when performance is critical and versioning and interoperability are not a priority.
21:850
The Binaron version differs in that it has no .proto files or other ProtoBuf stuff, but it explicitly defines a PurchaseMessage .NET class. Moreover, ProtoBuf serialization and deserialization instructions are replaced by the following:
21:851
byte[]? body = null;
21:852
using (var stream = new MemoryStream())
21:853
{
21:854
BinaronConvert.Serialize(purchase, stream);
21:855
stream.Flush();
21:856
body = stream.ToArray();
21:857
}
21:858
21:859
Together with:
21:860
PurchaseMessage? message = null;
21:861
using (var stream = new MemoryStream(body))
21:862
{
21:863
message = BinaronConvert.Deserialize<PurchaseMessage>(stream);
21:864
}.
21:865
21:866
Now that we have created a microservice connected to a message broker, it is also important to learn how to expose packages from WWTravelClub using web APIs. Let’s see this in the next section.
21:867
Exposing WWTravelClub packages using Web APIs
21:868
In this section, we will implement an ASP.NET REST service that lists all the packages that are available for a given vacation’s start and end dates. For didactic purposes, we will not structure the application according to the best practices we have described previously; instead, we will simply generate the results with a LINQ query that will be directly placed in the controller action method. A well-structured ASP.NET Core application has been presented in Chapter 18, Implementing Frontend Microservices with ASP.NET Core.
21:869
Let us make a copy of the WWTravelClubDB solution folder and rename the new folder WWTravelClubWebAPI80. The WWTravelClubDB project was built step by step in the various sections of Chapter 13, Interacting with Data in C# – Entity Framework Core. Let us open the new solution and add a new ASP.NET Core API project to it named WWTravelClubWebAPI80 (the same name as the new solution folder). For simplicity, select No Authentication. Right-click on the newly created project and select Set as StartUp project to make it the default project that is launched when the solution is run.
21:870
Finally, we need to add a reference to the WWTravelClubDB project.
21:871
ASP.NET Core projects store configuration constants in the appsettings.json file. Let’s open this file and add the database connection string for the database we created in the WWTravelClubDB project to it, as shown here:
21:872
{
21:873
`ConnectionStrings`: {
21:874
`DefaultConnection`: `Server=
21:875
(localdb)mssqllocaldb;Database=wwtravelclub;
21:876
Trusted_Connection=True;MultipleActiveResultSets=true`
21:877
},
21:878
...
21:879
...
21:880
}
21:881
21:882
Now, we must add the WWTravelClubDB entity framework database context to Program.cs, as shown here:
21:883
builder.Services.AddDbContext<WWTravelClubDB.MainDBContext>(options =>
21:884
options.UseSqlServer(
21:885
builder.Configuration.GetConnectionString(`DefaultConnection`),
21:886
b =>b.MigrationsAssembly(`WWTravelClubDB`)))
21:887
21:888
The option object settings that are passed to AddDbContext specify the usage of SQL Server with a connection string that is extracted from the ConnectionStrings section of the appsettings.json configuration file with the Configuration.GetConnectionString(`DefaultConnection`) method. The b =>b.MigrationsAssembly(`WWTravelClubDB`) lambda function declares the name of the assembly that contains the database migrations (see Chapter 13, Interacting with Data in C# – Entity Framework Core), which, in our case, is the DLL that was generated by the WWTravelClubDB project. For the preceding code to compile, you should add the Microsoft.EntityFrameworkCore namespace.
21:889
Since we want to enrich our REST service with OpenAPI documentation, let’s add a reference to the Swashbuckle.AspNetCore NuGet package. Now, we can add the following very basic configuration to Program.cs:
21:890
var builder = WebApplication.CreateBuilder(args);
21:891
...
21:892
builder.Services.AddSwaggerGen(c =>
21:893
{
21:894
c.SwaggerDoc(`v2`, new() { Title = `WWTravelClub REST API - .NET 8`, Version = `v2` });
21:895
});
21:896
var app = builder.Build();
21:897
...
21:898
app.UseSwagger();
21:899
app.UseSwaggerUI(c => c.SwaggerEndpoint(`/swagger/v2/swagger.json`, `WWTravelClub REST API - .NET 8`));
21:900
...
21:901
app.Run();
21:902
21:903
Now, we are ready to encode our service. Let’s delete WeatherForecastController, which is automatically scaffolded by Visual Studio. Then, right-click on the Controllers folder and select Add | Controller. Now, choose an empty API controller called PackagesController. First, let’s modify the code as follows:
21:904
[Route(`api/packages`)]
21:905
[ApiController]
21:906
public class PackagesController : ControllerBase
21:907
{
21:908
[HttpGet(`bydate/{start}/{stop}`)]
21:909
[ProducesResponseType(typeof(IEnumerable<PackagesListDTO>), 200)]
21:910
[ProducesResponseType(400)]
21:911
[ProducesResponseType(500)]
21:912
public async Task<IActionResult> GetPackagesByDate(
21:913
[FromServices] WWTravelClubDB.MainDBContext ctx,
21:914
DateTime start, DateTime stop)
21:915
{
21:916
}
21:917
}
21:918
21:919
The Route attribute declares that the basic path for our service will be api/packages. The unique action method that we implement is GetPackagesByDate, which is invoked on HttpGet requests on paths of the bydate/{start}/{stop} type, where start and stop are the DateTime parameters that are passed as input to GetPackagesByDate. The ProduceResponseType attributes declare the following:
21:920
21:921
When a request is successful, a 200 code is returned, and the body contains an IEnumerable of the PackagesListDTO type (which we will soon define) containing the required package information.
21:922
When the request is ill formed, a 400 code is returned. We don’t specify the type returned since bad requests are automatically handled by the ASP.NET Core framework through the ApiController attribute.
21:923
In the case of unexpected errors, a 500 code is returned with the exception error message.
21:924