Gerar e reconhecer códigos de barras no AWS Lambda

Categoria do blog: Código de barras.NET

22.05.2020

O AWS Lambda é uma plataforma de computação sem servidor orientada a eventos, fornecida pela Amazon como parte da Amazon Web Services.

Este tutorial mostra como criar um projeto AWS Lambda no Visual Studio .NET 2017, gerar uma imagem de código de barras DataMatrix e reconhecer o código de barras DataMatrix na imagem gerada em uma função AWS Lambda.

Primeiro, precisamos abrir o Visual Studio 2017 e criar um novo projeto AWS Lambda:
Create AWS Lambda project in Visual Studio

Em seguida, precisamos especificar que uma função SQS simples deve ser usada como conteúdo para a função AWS Lambda:
Use simple SQS function as content for AWS Lambda function in Visual Studio

Aqui está um projeto AWS Lambda criado no Visual Studio 2017:
AWS Lambda project in Visual Studio



Em seguida, precisamos adicionar referências ao pacote NuGet System.Drawing.Common e ao arquivo Vintasoft.Barcode.dll para .NET Core.
System.Drawing.Common é necessário para a montagem do Vintasoft.Barcode. A montagem do Vintasoft.Barcode é necessária para a geração e o reconhecimento de códigos de barras.
Add Vintasoft.Barcode.dll to AWS Lambda project in Visual Studio



Em seguida, precisamos abrir o código da função AWS Lambda:
Open code of AWS Lambda function in Visual Studio

Em seguida, precisamos adicionar o código para geração e reconhecimento de código de barras à função AWS Lambda:
C# code for barcode generation and recognition using AWS Lambda function

Aqui está o código C# da função AWS Lambda, que permite gerar uma imagem com código de barras DataMatrix e reconhecer o código de barras na imagem gerada:
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AWSLambda1
{
    public class Function
    {

        /// <summary>
        /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
        /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
        /// region the Lambda function is executed in.
        /// </summary>
        public Function()
        {
        }



        /// <summary>
        /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used
        /// to respond to SQS messages.
        /// </summary>
        public async System.Threading.Tasks.Task FunctionHandler(Amazon.Lambda.SQSEvents.SQSEvent evnt, Amazon.Lambda.Core.ILambdaContext context)
        {
            foreach (var message in evnt.Records)
            {
                await ProcessMessageAsync(message, context);
            }
        }

        private async System.Threading.Tasks.Task ProcessMessageAsync(Amazon.Lambda.SQSEvents.SQSEvent.SQSMessage message, Amazon.Lambda.Core.ILambdaContext context)
        {
            context.Logger.LogLine($"Processed message {message.Body}");

            try
            {
                // create memory stream, where image with barcode will be stored
                using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
                {
                    // create the barcode writer
                    Vintasoft.Barcode.BarcodeWriter barcodeWriter = new Vintasoft.Barcode.BarcodeWriter();
                    // specify that DataMatrix barcode must be created
                    barcodeWriter.Settings.Barcode = Vintasoft.Barcode.BarcodeType.DataMatrix;
                    // specify the barcode value
                    barcodeWriter.Settings.Value = "1234567890987654321";
                    // generate barcode image and save to the memory stream as PNG file
                    barcodeWriter.SaveBarcodeAsImage(mem, Vintasoft.Barcode.BarcodeImageFormat.Png);

                    // create the barcode reader
                    using (Vintasoft.Barcode.BarcodeReader barcodeReader = new Vintasoft.Barcode.BarcodeReader())
                    {
                        // specify that reader must search for DataMatrix barcodes
                        barcodeReader.Settings.ScanBarcodeTypes = Vintasoft.Barcode.BarcodeType.DataMatrix;
                        // specify that reader must search horizontal barcodes only
                        barcodeReader.Settings.ScanDirection = Vintasoft.Barcode.ScanDirection.Horizontal;

                        // read barcodes from image
                        Vintasoft.Barcode.IBarcodeInfo[] infos = barcodeReader.ReadBarcodes(mem);

                        // if barcodes are not detected
                        if (infos.Length == 0)
                        {
                            context.Logger.LogLine($"No barcodes found.");
                        }
                        // if barcodes are detected
                        else
                        {
                            // get information about searched barcodes

                            for (int i = 0; i &lt; infos.Length; i++)
                            {
                                Vintasoft.Barcode.IBarcodeInfo info = infos[i];
                                context.Logger.LogLine(string.Format("Barcode: Type={0}, Value={1}", info.BarcodeType, info.Value));
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                context.Logger.LogLine(string.Format("Error: {0}", ex.Message));
            }

            await System.Threading.Tasks.Task.CompletedTask;
        }
    }
}



Finalmente, precisamos executar nossa função AWS Lambda na ferramenta AWS .NET Mock Lambda Test Tool:
Run AWS Lambda function in AWS .NET Mock Lambda Test Tool

Envie uma solicitação SQS para nossa função AWS Lambda:
Send a SQS request to our AWS Lambda function

E veja o resultado do reconhecimento de código de barras usando a função AWS Lambda:
Result of barcode recognition using AWS Lambda function