Create an Azure Function Triggered By Blob Storage Using C#

Introduction

 
In this article, we'll give you an illustration of a basic Azure Function that will trigger an occasion when a record gets transferred to Azure Blob storage and furthermore will track and save those qualities in Database utilizing EntityFrameworkCore, Dependency Injection, and SQL Database.
 

Azure Function - Blob Trigger

 
Azure Function is a cloud service available on-demand that provides all the continually updated infrastructure and resources needed to run your application. The Blob storage trigger starts a function when a new or updated blob is detected. The blob contents are provided as input to the function. The Azure blob storage trigger requires a general-purpose storage account. Storage v2 accounts with hierarchical namespaces are also supported.
 
Prerequisites 
 
  • An Azure Storage account
  • SQL Database 
  • Visual Studio with the Azure Development workload enabled. you can also create Azure Function directly in the portal, but the visual studio is preferred when you want easy source control integration.

Create a Storage account in Azure

 
I have already blogged in my previous article that Upload files to Azure blob storage in which I have clearly defined all the steps to create the storage account in azure  Azure Blob Storage.
 

Create an Azure Function using Visual Studio 

 
Open the Visual Studio and click on the create a new project. Choose Azure Functions from the list of available project templates.
 
Create A Azure Function Triggered By Blob Storage Using C# 
 
In the next section, provide your project name and location to store the project in your machine.
 
Create A Azure Function Triggered By Blob Storage Using C#
 
In the following screen, you can choose the target framework for Azure functions (v2 .Net Core) and Blob Trigger as the type of trigger.
 
Create A Azure Function Triggered By Blob Storage Using C# 
 
Even though v3 is the newest version, we're choosing the v2 because some packages are not supporting in v3. Choose the Blob trigger template. On the right-hand side, you can choose the storage account since we already configured the storage account from the portal itself we just need to add the connectionstring in the application itself.
 

we're using EntityFrameworkCore and Dependency Injection to interact with SQL Database

 
However with the recent release of dependency injection support for Azure Functions. working with Entity Framework Core in Azure Functions feels a bit nicer.
 
Required Packages  
 
It's important to select the correct version number that's compatible with the version of .Net you're running on and I've also referenced Microsoft.Azure.Functions.Extensions NuGet package which gives us access to the dependency injection feature.
 
Create A Azure Function Triggered By Blob Storage Using C# 
 
Database - Table schema 
  1. CREATE TABLE [dbo].[FileRecords]  
  2. (  
  3.     [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,   
  4.     [FileName] NVARCHAR(50) NOT NULL,   
  5.     [IsCompleted] BIT NOT NULL,   
  6.     [CreatedTime] DATETIME NOT NULL  
  7. )  
Create an EF Core model for FileRecords item entity and custom DbContext.
 
FileRecord.cs 
 
Since the Id and Created Date values are being generated by the machine dynamically so we defined them in the Model itself.  
  1. using System;  
  2.   
  3. namespace BlobTrigger_AzureFunction.Models  
  4. {  
  5.    public class FileRecords  
  6.     {  
  7.         public Guid Id { getset; } = System.Guid.NewGuid();  
  8.         public string FileName { getset; }  
  9.         public bool IsCompleted { getset; }  
  10.         public DateTime CreatedDate { getset; } = DateTime.UtcNow;  
  11.     }  
  12. }  
AppDbContext.cs
  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace BlobTrigger_AzureFunction.Models  
  4. {  
  5.     public class AppDbContext : DbContext  
  6.     {  
  7.         public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }  
  8.         public DbSet<FileRecords> FileRecords { getset; }  
  9.     }  
  10. }  
Initialize Dependency Injection
 
To set up the dependency injection for our function app we use the FunctionStartup attribute on the assembly to indicate a startup class that will run when the function app starts. Create a startup class and define the  SQL connection string and register a DbContext in the services, which will allow us to inject the AppDbContext  into our function.
 
Startup.cs 
  1. using BlobTrigger_AzureFunction.Models;  
  2. using Microsoft.Azure.Functions.Extensions.DependencyInjection;  
  3. using Microsoft.EntityFrameworkCore;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. [assembly: FunctionsStartup(typeof(BlobTrigger_AzureFunction.Startup))]  
  7.   
  8. namespace BlobTrigger_AzureFunction  
  9. {  
  10.     public class Startup : FunctionsStartup  
  11.     {  
  12.         public override void Configure(IFunctionsHostBuilder builder)  
  13.         {  
  14.             string connectionString = "Your SQL Connection String"//"Data Source= Server name;Integrated Security=true;Database=DatabaseName"  
  15.             builder.Services.AddDbContext<AppDbContext>(  
  16.                 options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString));  
  17.         }  
  18.     }  
  19. }  
Injecting DbContext into a function - Constructor Injection
 
Function1.cs 
  1. public class Function1  
  2.     {  
  3.         #region Property  
  4.         private readonly AppDbContext appDbContext;  
  5.         #endregion  
  6.  
  7.         #region Constructor  
  8.         public Function1(AppDbContext appDbContext)  
  9.         {  
  10.             this.appDbContext = appDbContext;  
  11.         }  
  12.         #endregion  
  13.   
  14.         // ..... function defined here 
  15.     }  
Setting up the connection string for Blob Storage
 
When Azure Function runs, it needs to know how to connect to the blob container. Visual Studio has created a file called local.settings.json, we initially created the Storage account from my previous article there I have mentioned copying the connection string from Access keys. Now we have to add the connection string in local.settings.json  
  1. {  
  2.   "IsEncrypted"false,  
  3.   "Values": {  
  4.     "AzureWebJobsStorage""Your Blob storage connection string",  
  5.     "FUNCTIONS_WORKER_RUNTIME""dotnet"  
  6.   
  7.   }    
  8. }  
In the boilerplate code, there are two important variables created, name and myBlob
 
Create A Azure Function Triggered By Blob Storage Using C#
  • name - holds the name of the file found in the blob container.
  • myBlob - holds the content of the file.
  • filecontainer - actual container name created in blob storage.
  • connection - blob storage connection string.
Saving the Details to Database
  1. using System.IO;  
  2. using BlobTrigger_AzureFunction.Models;  
  3. using Microsoft.Azure.WebJobs;  
  4. using Microsoft.Extensions.Logging;  
  5.   
  6.   
  7. namespace BlobTrigger_AzureFunction  
  8. {  
  9.     public class Function1  
  10.     {  
  11.         #region Property  
  12.         private readonly AppDbContext appDbContext;  
  13.         #endregion  
  14.  
  15.         #region Constructor  
  16.         public Function1(AppDbContext appDbContext)  
  17.         {  
  18.             this.appDbContext = appDbContext;  
  19.         }  
  20.         #endregion  
  21.   
  22.         [FunctionName("Triggerwhenfileuploads")]  
  23.         public void Run([BlobTrigger("filecontainer/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob, string name, ILogger log)  
  24.         {  
  25.             log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");  
  26.             appDbContext.FileRecords.Add(new FileRecords  
  27.             {  
  28.                 FileName = name,  
  29.                 IsCompleted = true  
  30.             });  
  31.              appDbContext.SaveChanges();  
  32.         }  
  33.     }  
  34. }  
Run the function  
 
Press F5 after successful Build. We can see the following details in the command window.
 
Create A Azure Function Triggered By Blob Storage Using C#
 
Let's upload a file in the blob container via the Azure portal and see the result is being updated in the Database.
 
Create A Azure Function Triggered By Blob Storage Using C#
 
After successful upload of a file, here we can see an event is triggered for our function we can see the log in the command window,
 
Create A Azure Function Triggered By Blob Storage Using C# 
 
After executing the function below is the final output with the file name and its size is displayed as defined in the logs,
 
Create A Azure Function Triggered By Blob Storage Using C# 
 
Records being saved in the Database as expected.
 
Create A Azure Function Triggered By Blob Storage Using C#
 
Source Code - Git Hub
 

Summary

 
The new dependency injection feature of Azure Functions makes it very simple to work with Entity Framework Core database contexts within an Azure Functions app, even though there is no explicit EF Core binding for Azure Functions.
 
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
 
Keep learning....!


Similar Articles