Delete Blobs Using Timer Trigger Azure Function In .NET Core

This article demonstrates how to delete blob items using Azure Function. To implement this, we will create a timer trigger Azure function which will periodically look at the container and delete blob items.
 
Prerequisites
  1. Basic Knowledge on Azure Function.
  2. Azure storage account already created.
  3. .NET Core SDK 3.1 installed in your PC.
  4. Azure storage emulator installed.

Create Time Trigger Function From Visual Studio

 
First, we will create Azure Function app empty project from visual studio. Give a solution name and project name as per your wish. Here, I have given project name as "AzFunctions".
 
 
 
Select Empty template here.
 
 
Once newly created solution is loaded, right click on function project => Click on Add => Click on New Azure Function… => Give function name as “DeleteBlobTimerTriggerFunc.cs” => Click on Add => Select “Timer Trigger” => Click on OK.
 
Install required NuGet packages into the function app project. For that, right click on the project => Click on Manage NuGet Packages… => Browse and install one by one.
  • Microsoft.Azure.WebJobs
  • Azure.Storage.Blobs
Add additional parameter into function. Run method as ExecutionContext which will give the possibility to use of ConfigurationBuilder so that Azure function can read storage connection string from JSON file or from function configuration settings on Azure.
 
Below sequential actions will be performed by this function,
  1. Read configuration values.
  2. Get BlobContainerClient reference based on the storage account connection string and container name (here container name is “dummy-messages”).
  3. Get All blobs and delete blob item one by one if exists.
DeleteBlobTimerTriggerFunc.cs
  1. using System;  
  2. using Azure.Storage.Blobs;  
  3. using Azure.Storage.Blobs.Models;  
  4. using Microsoft.Azure.WebJobs;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.Logging;  
  7.   
  8. namespace AzFunctions  
  9. {  
  10.     public static class DeleteBlobTimerTriggerFunc  
  11.     {  
  12.         [FunctionName("DeleteBlobTimerTriggerFunc")]  
  13.         public static void Run([TimerTrigger("%TimerSchedule%")] TimerInfo myTimer,   
  14.             ILogger log,   
  15.             ExecutionContext context)  
  16.         {  
  17.             log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");  
  18.   
  19.             var config = new ConfigurationBuilder()  
  20.                             .SetBasePath(context.FunctionAppDirectory)  
  21.                             .AddJsonFile("local.settings.json"truetrue)  
  22.                             .AddEnvironmentVariables().Build();  
  23.   
  24.             BlobContainerClient blobContainerClient =   
  25.                 new BlobContainerClient(config["CloudStorageAccount"], "dummy-messages");  
  26.   
  27.             var blobs = blobContainerClient.GetBlobs();  
  28.             foreach (BlobItem blobItem in blobs)  
  29.             {  
  30.                 blobContainerClient.DeleteBlobIfExistsAsync(blobItem.Name);  
  31.                 log.LogInformation($"Blob Name {blobItem.Name} is deleted successfully.");  
  32.             }  
  33.         }  
  34.   
  35.     }  
  36. }  
In this function we configured TimerSchedule and this value will read from configuration.
 
Add TimerSchedule value as "0 */3 * * * *" into local.settings.json for local testing.
 
Add CloudStorageAccount values into local.settings.json as well which will required to read storage account connection string
 
This value you can be found from your Azure storage account. For that, login to Azure account => Go to storage account => Click on Access Keys under settings on left menu => You will see two keys there => Copy anyone of the connection sting => Paste that into local.settings.json
  1. "Values": {    
  2. "AzureWebJobsStorage""UseDevelopmentStorage=true",    
  3. "FUNCTIONS_WORKER_RUNTIME""dotnet",    
  4. "CloudStorageAccount""DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.windows.net",   
  5. "TimerSchedule""0 */3 * * * *"   
  6. }    

Test Azure Function in localhost

 
Let’s add some blobs item into container called “dummy-messages”, if it does not exist.
 
Now build and run the function and test in local. You will see the below console window open.
 
 
As TimerSchedule set as 0 */3 * * * * that means every 3 minute(s) starting at minute 0, this function will execute. In the console, you will see  the next 5 scheduled times when function will execute.
 
Let’s wait for 3 minutes, and  after that you will see that function is executed. You can see the respective delete log information in the function console window. Here I added 5 blobs into container. That’s why 5 blobs deleted successfully.
 
 
Now check the container in Azure portal, you will see that all blobs are deleted.
 
 
Awesome! Timer trigger function is working as expected.
 

Deploy Azure Function from Visual Studio 

 
If you want to deploy and configure that function into Azure portal, we can do that easily from Visual Studio. To implement this, you can follow the section “Deploy Azure Function from Visual Studio’ mention in this article.
 
Do remember one thing, once publish is successful from VS, you will see newly created function in Azure portal and then you need to configure new app settings key called – TimerSchedule and CloudStorageAccount in function app.
 
Once the configuration is done, you will see function is executing as per the defined schedule.
 

Conclusion

 
In this article, we deleted sample blob though Azure timer trigger function using .NET Core. Also we tested the function on localhost and deployed to Azure portal. Hope you find this article useful!


Similar Articles