xtrareports-404860-cloud-integration-aws-amazon-lambda-from-web-api.md
This topic shows how to create a REST API application with DevExpress Reporting and deploy it to AWS infrastructure using AWS Lambda. The application generates a report based on user input and exports the report as a PDF.
The guide uses CLI utilities and commands.
aws configure command to specify your AWS Access Key ID, AWS Secret Access Key, and default region name.The deployment recommendations do not apply to all possible configurations and should not be considered comprehensive. We offer these instructions as a getting-started reference. Steps may vary depending on your operating system, installed software, and DevExpress versions. You, the developer, are responsible for the application, database, network, and other configurations based on your client, security, environment, and other requirements. We recommend that you review these settings with your database, network, and IT infrastructure administrators and consider tailoring their recommendations to your case.
Run the following command to create the DXReportingWebApiTest ASP.NET Core Web API project that uses minimal API:
dotnet new webapi -n DXReportingWebApiTest --framework net8.0 --use-minimal-apis --auth None --no-https
For more information on commands and switches, review the following document: .NET default templates for dotnet new - webapi.
Run the following commands:
cd DXReportingWebApiTest
dotnet add package DevExpress.Reporting.Core
dotnet add package DevExpress.Drawing.Skia
The commands install the following NuGet packages:
DevExpress.Reporting.Core This package implements core functionality for DevExpress Reporting.DevExpress.Drawing.Skia This package implements the cross-platform drawing engine based on the Skia Graphics Library. For more information, review the following help topic: DevExpress.Drawing Graphics Library.
To learn more about DevExpress NuGet package installation, review the following help topic: Install NuGet Packages with Command Line Interface (CLI) Tools.
This project implements a GET endpoint named report that performs all the necessary tasks:
// ...
app.MapGet("/report", async ([FromQuery] string firstName, [FromQuery] string lastName) =>
{
using Microsoft.AspNetCore.Mvc;
if(string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName)) {
return Results.Text("Required query parameters are missing: 'firstName', 'lastName'.");
}
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
string resourceName = currentAssembly.GetManifestResourceNames()
.Single(str => str.EndsWith("TestReport.repx"));
using Stream fileStream = currentAssembly.GetManifestResourceStream(resourceName)!;
using var report = new DevExpress.XtraReports.UI.XtraReport();
report.LoadLayoutFromXml(fileStream);
report.Parameters["firstName"].Value = firstName;
report.Parameters["lastName"].Value = lastName;
using var ms = new MemoryStream();
await report.ExportToPdfAsync(ms);
return Results.File(ms.ToArray(), "application/pdf; charset=utf-8", "Ticket.pdf");
});
The code snippet retrieves query string parameters, loads a report template from the assembly resource, passes parameters to the report, exports that report to PDF, and returns the resulting Ticket.pdf file.
The report is a conference ticket that contains the owner’s name from the query string, a linear bar code, and a QR code to verify the quality of the print.
The report is created in DevExpress Report Designer and is saved to the TestReport.repx XML file.
The report contains two parameters, “firstName” and “lastName”, which identify the ticket owner and allow you to use the report as a template.
Copy the TestReport.repx file to the project root folder. Include a report file to the project as a resource. To do this, open the DXReportingWebApiTest.csproj file using a text editor and add the following tags:
<ItemGroup>
<EmbeddedResource Include="TestReport.repx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
In the Program.cs file, add the GET endpoint, whose code is listed in the Task Execution Code section above.
Use the following command to build and run the project:
dotnet run
Open the URL displayed in the console and add the string /swagger to the URL to invoke Swagger UI. To get the resulting PDF file, specify the parameters firstName and lastName. Try it out.
To make your ASP.NET Core Web API deployable on AWS Infrastructure, you must invoke the appropriate service. This will enable Lambda to recognize your API as an AWS Lambda function.
Install the Amazon.Lambda.AspNetCoreServer.Hosting NuGet package:
dotnet add package Amazon.Lambda.AspNetCoreServer.Hosting
Open the Program.cs file and add the following code sample above other service registrations:
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
Delete the weatherforecast endpoint and all related content from the project. The Program.cs file includes the following:
using Microsoft.AspNetCore.Mvc;
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet("/report", async ([FromQuery] string firstName, [FromQuery] string lastName) =>
{
if(string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName)) {
return Results.Text("Required query parameters are missing: 'firstName', 'lastName'.");
}
using var ms = new MemoryStream();
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
string resourceName = currentAssembly.GetManifestResourceNames()
.Single(str => str.EndsWith("TestReport.repx"));
Stream fileStream = currentAssembly.GetManifestResourceStream(resourceName)!;
using var report = new DevExpress.XtraReports.UI.XtraReport();
report.LoadLayoutFromXml(fileStream);
report.Parameters["firstName"].Value = firstName;
report.Parameters["lastName"].Value = lastName;
await report.ExportToPdfAsync(ms);
return Results.File(ms.ToArray(), "application/pdf; charset=utf-8", "Ticket.pdf");
})
.WithName("TestExportFunction");
app.Run();
Navigate to the project root folder and run the following command:
You are prompted to enter runtime environment. Type in dotnet8:
Next you are prompted for the Function Name. This is the internal name that Lambda uses in AWS. Enter TestExportFunction.
The next step prompts you to select an existing IAM role or create a new one. For more information on IAM Roles, review the following document: Lambda execution role.
Enter Memory Size - 256.
Enter Timeout - 30.
Enter Handler. Note that you must enter only the name of the project’s namespace - DXReportingWebApiTest.
When the Lambda function is created, open the AWS Management Console and navigate to the AWS Lambda homepage. Click the name of the newly created function (TestExportFunction). Click on the Configuration tab and select Function URL :
On the Configure Function URL page, select NONE as Auth type and click the Save button.
The Lambda dashboard displays the created URL:
Click the Environment Variables and add the ASPNETCORE_ENVIRONMENT key with the Development value. This action enables Swagger UI.
Click the Function URL link and append the /swagger string to the URL in the browser to invoke Swagger.
Enter the required parameters and click Execute.
Once the request is processed, a link to the PDF file will appear in the Responses section. Click the link to view the result of the Reporting API deployed on AWS Lambda: