This page looks best with JavaScript enabled

Serverless QR Code Generator

 ·  ☕ 3 min read  ·  🥓🥓🥓 werkn

Requirements

You’ll require the following to be installed before continuing:

  • Active Azure AD subscription
  • Visual Studio 2019 with support for ASP.NET / Serverless
  • Be logged into Azure AD from Visual Studio
  • Have Access to Azure CLI

What Were Building

Were going to be creating a serverless endpoint that takes a string (containing a GUID) and generates a QR code using the ZXing library which is then uploaded to blob storage. Configuration will be done via Visual Studio.

Setting Up the Project

  1. Launch Visual Studio and Create a new project.

  2. From the project templates select Azure Functions. Click Next.

  3. Under Project Name and Solution Name enter QRCodeGenerator (You could also put them in the same directory). Click Next.

  4. On the next screen from the drop down select target framework, I’m using .NET Core 3 (LTS). Select Http trigger. For Storage account select Browse and select either an active storage account or add one. Under Authorization level select Function. Click Create.

Adding Dependencies

We need to add a few dependencies to our newly created project using NuGet.

Begin by selecting Tools->NuGet Package Manager->Package Manager Console. Enter the following:

1
2
3
4
Install-Package Microsoft.Azure.WebJobs.Extensions.Storage -Version 5.0.0
Install-Package Microsoft.NET.Sdk.Functions -Version 3.0.13
Install-Package System.Drawing.Common -Version 6.0.0
Install-Package ZXing.Net -Version 0.16.6

Note: You could use newer packages but this solution may break.

Update Our Function

  1. Rename Function1.cs to QRCodeGenerator.cs.

  2. Replace the contents of QRCodeGenerator.cs with:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using ZXing;
using System.Drawing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace QRCodeGenerator
{
    public static class QRCodeGenerator
    {
        //adapted from: https://www.codeguru.com/dotnet/dynamically-generating-qr-codes-in-c/#
        private static byte[] GenerateQRCode(string text)
        {
            var barcodeWriter = new BarcodeWriter();
            barcodeWriter.Format = BarcodeFormat.QR_CODE;
            //create our QR code
            var result = barcodeWriter.Write(text);
            Image qrCodeAsBitmap = new Bitmap(result);

            //pull byte array out of memory, we provide this to Blob outputFile Stream
            using (var stream = new MemoryStream())
            {
                qrCodeAsBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return stream.ToArray();
            }
        }

        [FunctionName("QRCodeGenerator")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "generate/{filename}")] HttpRequest req,
            [Blob("qrcodes/{filename}", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream outputFile,
            ILogger log)
        {
            //grab our filename from the path + route (..../api/qrcodes/{filename})
            string filename = req.Path.ToString();
            filename = filename.Substring(filename.LastIndexOf('/') + 1);

            //create our guid, which is just the supplied filename
            string guid = filename.Substring(0, filename.LastIndexOf("."));

            //convert text to QR code as byte array, remove ".xxx" extension we grabbed from the path
            byte[] output = GenerateQRCode(guid);

            //write the result to blob storage container 'qrcodes' as {filename}
            await outputFile.WriteAsync(output, 0, output.Length);

            //return the name of the newly created files blob storage url, site in bytes and the guid we encoded
            return new OkObjectResult(
                JsonConvert.SerializeObject(
                    new { Filename = filename, SizeBytes = output.Length, EncodedText = guid }
                )
            );
        }
    }
}

Create Blob Storage Container

We need to add container qrcodes to the storage account we used/or created earlier.

Note: To check the currenlty created storage accounts you can run the following: az storage account list | grep name

  1. Launch Azure CLI and run the following (remember to update to your storage account name). I’m running mine from WSL but the instructions should be the same outside of shell differences.
1
az storage container create --name qrcodes --account-name <your-storage-container> --auth-mode login

You should now have everything needed to test the serverless QR code generator using the local debugger. When your satisfied with the functionality you can deploy to Azure using Visual Studio Publish… action.

Share on

Ryan Radford
WRITTEN BY
werkn
Developer / IT Guy / Tinkerer