Create Blob Triggered Azure Functions using .NET 5

Raymond Raymond event 2021-08-24 visibility 2,671
more_vert
Create Blob Triggered Azure Functions using .NET 5

From March 10 2021, Azure Functions supports production applications using .NET 5. It runs a separate worker process to execute the functions, which is very different from the previous library versions of .NET based Azure functions. This article provides an example of creating blob triggered Azure function using .NET 5. This can be commonly used in data warehousing projects on cloud to trigger file loading processes when a file is uploaded into a blob container.

Create the project

Open Visual Studio 2019, create a project using Azure Functions template:

20210824111217-image.png

20210824111434-image.png

As shown in the above screenshot, I am using my local Azure Storage Emulator for storage account and blob-triggers is set as Path.

Once clicked Create button, the project will be created with the following files:

20210824111654-image.png

Now let's explore the project.

Explore the project

Project file *.csproj

The project file use net5.0 as target framework and also specifies Azure Functions version as v3.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="4.0.4" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.0.3" OutputItemType="Analyzer" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.1.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

There are three new libraries for .NET which are different from previous versions since we now use dotnet-isolated runtime:

  • Microsoft.Azure.Functions.Worker
  • Microsoft.Azure.Functions.Worker.Sdk
  • Microsoft.Azure.Functions.Worker.Extensions.Storage

The third one is used for blob triggered applications. You will need to reference other libraries (Microsoft.Azure.Functions.Worker.Extensions.*) for other types of triggers.

Program.cs

This is the entry class of the application. Essentially the .NET Azure Functions application is just as a normal .NET console application. The script file has the following content:

using Microsoft.Azure.Functions.Worker.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

namespace AzureFunctionExample
{
    public class Program
    {
        public static void Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                .Build();

            host.Run();
        }
    }
}

The code snippet constructs a host object and then run it like other .NET applications. 

Most of the ASP.NET core or console application components like options pattern, dependency injections, entity framework and localization/globalization and so on can be used .NET 5 Azure function too. This is a bonus point of using .NET 5 isolated worker runtime. In the other articles of this column, I will discuss more about those techniques. 

host.json

This file contains all the configurations for all the functions in the application. Refer to host.json reference for Azure Functions 2.x | Microsoft Docs for more details. 

local.settings.json

This file will not be included in release production application and is only used for local configurations. For example, database connection strings, blob storage connections or any other environment variables you would use in the application. For production application on Azure, you can directly set them in application configurations.

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
    }
}

In the Values node, there are two keys created:

  • FUNCTIONS_WORKER_RUNTIME: specify the run time for the application. For .NET 5, we need to use dotnet-isolated. This will also applies to the future .NET 6 (Azure Functions V4) releases. 
  • AzureWebJobsStorage: the Azure blob storage account connection string added in the wizard previously. This example uses local emulator.

You can add as many key-values here and they will be passed as environment variables when the application runs. 

Function1.cs

This is the actual function definition file. It adds a default function named Function1. One big difference is that we now use FunctionAttribute instead of FunctionNameAttribute to mark function names in .NET 5 applications.

Let's change the function definition slightly to add value for Connection property of BlobTrigger attribute:

using System;
using System.IO;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace AzureFunctionExample
{
    public static class Function1
    {
        [Function("Function1")]
        public static void Run([BlobTrigger("blob-triggers/{name}", Connection = "AzureWebJobsStorage")] string myBlob, string name,
            FunctionContext context)
        {
            var logger = context.GetLogger("Function1");
            logger.LogInformation($"C# Blob trigger function Processed blob\n Name: {name} \n Data: {myBlob}");
        }
    }
}

The above function will be triggered whenever a blob file is added into blob-triggers container of the specified Azure blob storage (via Connection string). For more details about blob storage trigger and bindings, refer to official documentation: Azure Blob storage trigger and bindings for Azure Functions | Microsoft Docs.

Now let's run the function.

Run the application

We can run the function through two ways:

  • In Visual Studio, click Run button in the menu or press F5 if the Azure Functions project is the default project in the current solution.
    20210824113929-image.png
  • Use command line:
     func host start

Once the application is running, you should be able to see the following terminal window:

20210824114202-image.png

Trigger the application

Since the application is triggered by blob, let's add a file into blob-triggers container of the local storage emulator:

20210824114437-image.png

The above screenshot shows a file named new-file.txt was added into the container.

Going back to the application window, you can see the function Function1 was executed as the following screenshot shows:

20210824114546-image.png

Deploy application to Azure

You can deploy the application using Visual Studio publish wizard.

20210824114905-image.png

Alternatively, you can use Azure DevOps or other CI/CD to build and publish your Azure Functions app to Azure. 

References

Thanks for the good documentations from the authors of the following articles (I referenced some of them as the first function I created experienced many issues though the followed development was rather smooth) :

With Azure Functions, it definitely makes serverless and event-triggered programming so fun and easy. It is being commonly used by me when building Kontext services. I hope you have fun with Azure Functions too! 

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts