title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
21:925 | Now, let’s define the PackagesListDTO class in a new DTOs folder: |
21:926 | namespace WWTravelClubWebAPI80.DTOs; |
21:927 | public record PackagesListDTO |
21:928 | { |
21:929 | public int Id { get; set; } |
21:930 | public string Name { get; set; } |
21:931 | public decimal Price { get; set; } |
21:932 | public int DurationInDays { get; set; } |
21:933 | public DateTime? StartValidityDate { get; set; } |
21:934 | public DateTime? EndValidityDate { get; set; } |
21:935 | public string DestinationName { get; set; } |
21:936 | public int DestinationId { get; set; } |
21:937 | } |
21:938 | |
21:939 | Finally, let’s add the following using clauses to our controller code so that we can easily refer to our DTO and Entity Framework LINQ methods: |
21:940 | using Microsoft.EntityFrameworkCore; |
21:941 | using WWTravelClubWebAPI80.DTOs; |
21:942 | |
21:943 | Now, we are ready to fill the body of the GetPackagesByDate method with the following code. |
21:944 | try |
21:945 | { |
21:946 | var res = await ctx.Packages |
21:947 | .Where(m => start >= m.StartValidityDate |
21:948 | && stop <= m.EndValidityDate) |
21:949 | .Select(m => new PackagesListDTO |
21:950 | { |
21:951 | StartValidityDate = m.StartValidityDate, |
21:952 | EndValidityDate = m.EndValidityDate, |
21:953 | Name = m.Name, |
21:954 | DurationInDays = m.DurationInDays, |
21:955 | Id = m.Id, |
21:956 | Price = m.Price, |
21:957 | DestinationName = m.MyDestination.Name, |
21:958 | DestinationId = m.DestinationId |
21:959 | }) |
21:960 | .ToListAsync(); |
21:961 | return Ok(res); |
21:962 | } |
21:963 | catch (Exception err) |
21:964 | { |
21:965 | return StatusCode(500, err.ToString()); |
21:966 | } |
21:967 | |
21:968 | It is important to remember that we are focusing only on presenting the results of an API exposed using the Swashbuckle.AspNetCore NuGet package. It is not a good practice to make use of the DbContext in a Controller class, and as a software architect, you may define the best architectural design for your application (multi-tier, hexagonal, onion, clean, DDD, and so on). |
21:969 | The LINQ query is like the one contained in the WWTravelClubDBTest project we tested in Chapter 13, Interacting with Data in C# – Entity Framework Core. Once the result has been computed, it is returned with an OK call. The method’s code handles internal server errors by catching exceptions and returning a 500 status code since bad requests are automatically handled before the Controller method is called by the ApiController attribute. |
21:970 | Let’s run the solution. When the browser opens, it is unable to receive any result from our ASP.NET Core website. Let’s modify the browser URL so that it is https://localhost:<previous port>/swagger. It is worth mentioning that you can also configure your local settings file to either launch and go to the Swagger URL automatically, or have Swagger live under the root. |
21:971 | The user interface of the OpenAPI documentation will look as follows: |
21:972 | |
21:973 | Figure 21.15: Swagger output |
21:974 | PackagesListDTO is the model we defined to list the packages, while ProblemDetails is the model that is used to report errors in the event of bad requests. By clicking the GET button, we can get more details about our GET method and we can also test it, as shown in the following screenshot: |
21:975 | |
21:976 | Figure 21.16: GET method details |
21:977 | Pay attention when it comes to inserting dates that are covered by packages in the database; otherwise, an empty list will be returned. The ones shown in the preceding screenshot should work. |
21:978 | Dates must be entered in a correct JSON format; otherwise, a 400 Bad Request error is returned, like the one shown in the following code: |
21:979 | { |
21:980 | `errors`: { |
21:981 | `start`: [ |
21:982 | `The value '2019' is not valid.` |
21:983 | ] |
21:984 | }, |
21:985 | `title`: `One or more validation errors occurred.`, |
21:986 | `status`: 400, |
21:987 | `traceId`: `80000008-0000-f900-b63f-84710c7967bb` |
21:988 | } |
21:989 | |
21:990 | If you insert the correct input parameters, the Swagger UI returns the packages that satisfy the query in JSON format. |
21:991 | That is all! You have implemented your first API with OpenAPI documentation! Now let’s check how easy it can be to implement a serverless solution using Azure Functions. |
21:992 | Implementing Azure Functions to send emails |
21:993 | Here, we will use a subset of the Azure components. The use case from WWTravelClub proposes a worldwide implementation of the service, and there is a chance that this service will need different architecture designs to achieve all the key performance points that we described in Chapter 1, Understanding the Importance of Software Architecture. |
21:994 | If you go back to the user stories that were described in this chapter, you will find that many needs are related to communication. Because of this, it is common to have some alerts provided by emails in the solution. This implementation will focus on how to send emails. The architecture will be totally serverless. The benefits of using an architecture like that are explained below. |
21:995 | The following diagram shows the basic structure of the architecture. To give users a great experience, all the emails that are sent by the application will be queued asynchronously, thereby preventing significant delays in the system’s responses: |
21:996 | |
21:997 | Figure 21.17: Architectural design for sending emails |
21:998 | Basically, when a user does any action that requires sending an alert (1), the alert is posted in a send email request function (2), which stores the request in Azure Queue Storage (3). So, for the user, the alert is already performed at this moment, and they can keep working. However, since we have a queue, no matter the number of alerts sent, they will be processed by the send email function that is triggered (4) as soon as a request is made, respecting the time needed to process the requests, but guaranteeing that the receiver will get the alert (5). Note that there are no dedicated servers that manage Azure Functions for enqueuing or dequeuing messages from Azure Queue Storage. This is exactly what we call serverless, as described in Chapter 16, Working with Serverless - Azure Functions. It is worth mentioning that this architecture is not restricted to only sending emails – it can also be used to process any HTTP POST request. |
21:999 | Now, we will learn, in three steps, how to set up security in the API so that only authorized applications can use the given solution. |
21:1000 | First step — creating an Azure queue storage |
21:1001 | It is quite simple to create storage in the Azure portal. Let us learn how. First, you will need to create a storage account by clicking on Create a resource on the main page of the Azure portal and searching for Storage account. Then, you will be able to set up its basic information, such as Storage account name and Location. Information about Networking and Data protection, as shown in the following screenshot, can be checked in this wizard, too. There are default values for these settings that we will cover the demo: |
21:1002 | |
21:1003 | Figure 21.18: Creating an Azure storage account |
21:1004 | Once you have the storage account in place, you will be able to set up a queue. You will find this option by clicking on the Overview link in the storage account and selecting the Queue service option or by selecting Queues via the Storage account menu. Then, you will find an option to add the queue (+ Queue), where you just need to provide its name: |
21:1005 | |
21:1006 | Figure 21.19: Defining a queue to monitor emails |
21:1007 | The created queue will give you an overview of the Azure portal. There, you will find your queue’s URL and be able to use Storage Explorer: |
21:1008 | |
21:1009 | Figure 21.20: Queue created |
21:1010 | Note that you will also be able to connect to this storage using Microsoft Azure Storage Explorer (https://azure.microsoft.com/en-us/features/storage-explorer/): |
21:1011 | |
21:1012 | Figure 21.21: Monitoring the queue using Microsoft Azure Storage Explorer |
21:1013 | This tool is especially useful if you are not connected to the Azure portal. Let’s move to the second step, where we will create the function that receives the requests to send emails. |
21:1014 | Second step — creating the function to send emails |
21:1015 | Now, you can start programming in earnest, informing the queue that an email is waiting to be sent. Here, we need to use an HTTP trigger. Note that the function is a static class that runs asynchronously. The following code, written in Visual Studio, gathers the request data coming from the HTTP trigger and inserts the data into a queue that will be processed later. It is worth mentioning that the environment variable EmailQueueConnectionString is set in the function app settings, and it contains the information provided by the Azure Queue Storage connection string. |
21:1016 | We have below a code snippet from the function available in the GitHub repository of the book: |
21:1017 | public static class SendEmail |
21:1018 | { |
21:1019 | [FunctionName(nameof(SendEmail))] |
21:1020 | public static async Task<HttpResponseMessage>RunAsync( [HttpTrigger(AuthorizationLevel.Function, `post`)] HttpRequestMessage req, ILogger log) |
21:1021 | { |
21:1022 | var requestData = await req.Content.ReadAsStringAsync(); |
21:1023 | var connectionString = Environment.GetEnvironmentVariable(`EmailQueueConnectionString`); |
21:1024 | var storageAccount = CloudStorageAccount.Parse(connectionString); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.