Create an Azure Perform Triggered By Blob Storage Utilizing C#
On this article, we’ll offer you an illustration of a primary Azure Perform that can set off an event when a document will get transferred to Azure Blob storage and moreover will monitor and save these qualities in Database using EntityFrameworkCore, Dependency Injection, and SQL Database.
- An Azure Storage account
- SQL Database
- Visual Studio with the Azure Growth workload enabled. you can too create Azure Perform instantly within the portal, however the visible studio is most popular if you need straightforward supply management integration.
Create a Storage account in Azure
Create an Azure Perform utilizing Visual Studio
Open the Visual Studio and click on on the create a brand new challenge. Select Azure Capabilities from the record of accessible challenge templates.
Within the subsequent part, present your challenge identify and placement to retailer the challenge in your machine.
Within the following display, you may select the goal framework for Azure capabilities (v2 .Web Core) and Blob Set off as the kind of set off.
Regardless that v3 is the most recent model, we’re selecting the v2 as a result of some packages usually are not supporting in v3. Select the Blob set off template. On the right-hand aspect, you may select the storage account since we already configured the storage account from the portal itself we simply want so as to add the connectionstring within the software itself.
we’re utilizing EntityFrameworkCore and Dependency Injection to work together with SQL Database
Required Packages
It is essential to pick out the proper model quantity that is appropriate with the model of .Web you are working on and I’ve additionally referenced Microsoft.Azure.Capabilities.Extensions NuGet bundle which supplies us entry to the dependency injection function.
Database – Desk schema
- CREATE TABLE [dbo].[FileRecords]
- (
- [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
- [FileName] NVARCHAR(50) NOT NULL,
- [IsCompleted] BIT NOT NULL,
- [CreatedTime] DATETIME NOT NULL
- )
Create an EF Core mannequin for FileRecords merchandise entity and customized DbContext.
FileRecord.cs
For the reason that Id and Created Date values are being generated by the machine dynamically so we outlined them within the Mannequin itself.
- utilizing System;
- namespace BlobTrigger_AzureFunction.Fashions
- {
- public class FileRecords
- {
- public Guid Id { get; set; } = System.Guid.NewGuid();
- public string FileName { get; set; }
- public bool IsCompleted { get; set; }
- public DateTime CreatedDate { get; set; } = DateTime.UtcNow;
- }
- }
AppDbContext.cs
- utilizing Microsoft.EntityFrameworkCore;
- namespace BlobTrigger_AzureFunction.Fashions
- {
- public class AppDbContext : DbContext
- {
- public AppDbContext(DbContextOptions<AppDbContext> choices) : base(choices) { }
- public DbSet<FileRecords> FileRecords { get; set; }
- }
- }
Initialize Dependency Injection
To arrange the dependency injection for our perform app we use the FunctionStartup attribute on the meeting to point a startup class that can run when the perform app begins. Create a startup class and outline the SQL connection string and register a DbContext within the providers, which can permit us to inject the AppDbContext into our perform.
Startup.cs
- utilizing BlobTrigger_AzureFunction.Fashions;
- utilizing Microsoft.Azure.Capabilities.Extensions.DependencyInjection;
- utilizing Microsoft.EntityFrameworkCore;
- utilizing Microsoft.Extensions.DependencyInjection;
- [assembly: FunctionsStartup(typeof(BlobTrigger_AzureFunction.Startup))]
- namespace BlobTrigger_AzureFunction
- {
- public class Startup : FunctionsStartup
- {
- public override void Configure(IFunctionsHostBuilder builder)
- {
- string connectionString = “Your SQL Connection String”;
- builder.Providers.AddDbContext<AppDbContext>(
- choices => SqlServerDbContextOptionsExtensions.UseSqlServer(choices, connectionString));
- }
- }
- }
Injecting DbContext right into a perform – Constructor Injection
Function1.cs
- public class Function1
- {
- #area Property
- non-public readonly AppDbContext appDbContext;
- #endregion
- #area Constructor
- public Function1(AppDbContext appDbContext)
- {
- this.appDbContext = appDbContext;
- }
- #endregion
- // ….. perform outlined right here
- }
Organising the connection string for Blob Storage
- {
- “IsEncrypted”: false,
- “Values”: {
- “AzureWebJobsStorage”: “Your Blob storage connection string“,
- “FUNCTIONS_WORKER_RUNTIME”: “dotnet”
- }
- }
Within the boilerplate code, there are two essential variables created, identify and myBlob
- identify – holds the identify of the file discovered within the blob container.
- myBlob – holds the content material of the file.
- filecontainer – precise container identify created in blob storage.
- connection – blob storage connection string.
Saving the Particulars to Database
- utilizing System.IO;
- utilizing BlobTrigger_AzureFunction.Fashions;
- utilizing Microsoft.Azure.WebJobs;
- utilizing Microsoft.Extensions.Logging;
- namespace BlobTrigger_AzureFunction
- {
- public class Function1
- {
- #area Property
- non-public readonly AppDbContext appDbContext;
- #endregion
- #area Constructor
- public Function1(AppDbContext appDbContext)
- {
- this.appDbContext = appDbContext;
- }
- #endregion
- [FunctionName(“Triggerwhenfileuploads”)]
- public void Run([BlobTrigger(“filecontainer/{name}”, Connection = “AzureWebJobsStorage”)] Stream myBlob, string identify, ILogger log)
- {
- log.LogInformation($“C# Blob set off perform Processed blobn Identify:{identify} n Measurement: {myBlob.Size} Bytes”);
- appDbContext.FileRecords.Add(new FileRecords
- {
- FileName = identify,
- IsCompleted = true
- });
- appDbContext.SaveChanges();
- }
- }
- }
Run the perform
Press F5 after profitable Construct. We are able to see the next particulars within the command window.
Let’s add a file within the blob container by way of the Azure portal and see the result’s being up to date within the Database.
After profitable add of a file, right here we will see an occasion is triggered for our perform we will see the log within the command window,
After executing the perform under is the ultimate output with the file identify and its dimension is displayed as outlined within the logs,
Information being saved within the Database as anticipated.
Abstract
The brand new dependency injection function of Azure Capabilities makes it quite simple to work with Entity Framework Core database contexts inside an Azure Capabilities app, although there is no such thing as a specific EF Core binding for Azure Capabilities.
Thanks for studying, please let me know your questions, ideas, or suggestions within the feedback part. I respect your suggestions and encouragement.
Continue to learn….!