Generare e riconoscere codici a barre in AWS Lambda

Categoria del blog: Barcode.NET

22.05.2020

AWS Lambda è una piattaforma di elaborazione serverless basata su eventi fornita da Amazon come parte di Amazon Web Services.

Questo tutorial mostra come creare un progetto AWS Lambda in Visual Studio .NET 2017, generare un'immagine del codice a barre DataMatrix e riconoscere il codice a barre DataMatrix nell'immagine generata nella funzione AWS Lambda.

Per prima cosa, dobbiamo aprire Visual Studio 2017 e creare un nuovo progetto AWS Lambda:
Crea un progetto AWS Lambda in Visual Studio

Successivamente, dobbiamo specificare che la semplice funzione SQS deve essere utilizzata come contenuto per la funzione AWS Lambda:
Utilizza una semplice funzione SQS come contenuto per la funzione AWS Lambda in Visual Studio

Ecco un progetto AWS Lambda creato in Visual Studio 2017:
AWS Progetto Lambda in Visual Studio



Successivamente, dobbiamo aggiungere riferimenti al pacchetto nuget System.Drawing.Common e a Vintasoft.Barcode.dll per .NET Core.
System.Drawing.Common è necessario per l'assemblaggio di Vintasoft.Barcode. L'assemblaggio di Vintasoft.Barcode è necessario per la generazione e il riconoscimento dei codici a barre.
Aggiungi Vintasoft.Barcode.dll nel progetto AWS Lambda in Visual Studio



Successivamente, dobbiamo aprire il codice della funzione AWS Lambda:
Apri il codice della funzione AWS Lambda in Visual Studio

Successivamente, dobbiamo aggiungere il codice per la generazione e il riconoscimento dei codici a barre alla funzione AWS Lambda:
Codice C# per la generazione e il riconoscimento di codici a barre tramite la funzione AWS Lambda

Ecco il codice C# della funzione AWS Lambda, che consente di generare un'immagine con codice a barre DataMatrix e di riconoscere il codice a barre nell'immagine generata:
// 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;
        }
    }
}



Infine, dobbiamo eseguire la nostra funzione AWS Lambda in AWS .NET Mock Lambda Test Tool:
Esegui la funzione AWS Lambda nello strumento di test AWS .NET Mock Lambda

Invia una richiesta SQS alla nostra funzione AWS Lambda:
Invia una richiesta SQS alla nostra funzione AWS Lambda

E guarda il risultato del riconoscimento dei codici a barre usando la funzione AWS Lambda:
Risultato del riconoscimento dei codici a barre usando la funzione AWS Lambda