Azure

Exploring Azure Features- Bindings

Recap

In my earlier article, we’ve seen how EF Core will be carried out with an HTTP set off. If you have not learn my earlier articles then I extremely encourage you to take action: 

Supply code will be discovered right here

Introduction

Earlier than going into Bindings, we first want to know about Triggers, as Bindings can’t co-exist with out Azure Perform triggers. Now we have already mentioned about several types of triggers in my Azure Perform Introduction article.

Triggers are what could cause a operate to run. A set off defines how the operate is known as upon; nevertheless, each operate has one set off and non-obligatory bindings.

Binding is the connection to knowledge inside your Azure Features. There are two kinds of Bindings

  • Enter Binding: A enter binding is the info that your operate receives.
  • Output Binding: A output binding is the info that your operate sends.

To higher perceive enter and output binding, let’s take an instance.

Azure Perform is about to set off each 5 minutes. The operate reads a picture from the blob container & sends the e-mail to the meant recipients

  • Timer is a Set off
  • Enter Binding is the one which reads the picture from blob container
  • Sending an e mail to a recipient is an output binding

Coding

On this article, we’ll be concentrating solely on Bindings moderately than deploying an software to Azure. Within the upcoming articles, we’ll be trying into a number of methods of deploying our software in Azure.

State of affairs 1

Firstly, I will be extending the code that we’ve carried out within the earlier article; i.e. Azure Perform-HTTP Set off utilizing EF Core. Upon saving the info to the database, Queue can be used as an output binding to save lots of the info to the native storage.

Secondly, one other operate can be created upon insertion of knowledge to the Queue retailer. Right here Queue acts as an enter binding and the queue’s knowledge can be saved within the Blob container as an output Binding.

Conditions

  • Add nuget package- Microsoft.Azure.WebJobs.Extensions.Storage
  • Azure Storage Emulator for testing in native surroundings.

You possibly can obtain the emulator from right here / run it in Docker container by utilizing the beneath steps:

  1. docker pull microsoft/azure-storage-emulator    
  2.   
  3. docker run -p 10000:10000 -p 10001:10001 -p 10002:10002 microsoft/azure-storage-emulator  

Within the earlier article, we’ve seen how worker document has been inserted into database by utilizing HTTP set off.

  1. [FunctionName("SaveEmployee")]  
  2.        public async Activity<ActionResult> SaveEmployeeAsync([HttpTrigger(AuthorizationLevel.Anonymous,"post")] HttpRequest req,  
  3.            ILogger log)  
  4.        {  
  5.            string requestBody = await new StreamReader(req.Physique).ReadToEndAsync();  
  6.            var knowledge= JsonConvert.DeserializeObject<Worker>(requestBody);  
  7.            await employeeContext.Workers.AddAsync(knowledge);  
  8.            await employeeContext.SaveChangesAsync();  
  9.            await empCollector.AddAsync(knowledge);  
  10.            return new OkResult();  
  11.        }  

With a view to have Queue because the Output binding, we have to specify Queue Attribute both within the features technique (in case you might be returning the response as Queue) or you need to use it as a technique parameter within the operate.

Within the above instance, we can’t use response as Queue as a result of we’re already sending HTTP response(200 OK) to the shopper. In such situations, we’ve to make use of the Queue attribute within the features technique parameter utilizing a peculiar interface IAsyncCollector<T> or ICollector<T>. You might need already guessed it, IAsyncCollector<T> for Asynchronous operation whereas, ICollector<T> for Synchronous operation. Nevertheless, on this instance, we’ll be utilizing IAsyncCollector<T>.

IAsyncCollector is an object uncovered in Azure to carry a group of things that may be learn and saved asynchronously.

  1. [FunctionName("SaveEmployee")]  
  2.        public async Activity<ActionResult> SaveEmployeeAsync([HttpTrigger(AuthorizationLevel.Anonymous,"post")] HttpRequest req,  
  3.            [Queue("order")] IAsyncCollector<Worker> empCollector,  
  4.            ILogger log)  
  5.        {  
  6.            string requestBody = await new StreamReader(req.Physique).ReadToEndAsync();  
  7.            var knowledge= JsonConvert.DeserializeObject<Worker>(requestBody);  
  8.            await employeeContext.Workers.AddAsync(knowledge);  
  9.            await employeeContext.SaveChangesAsync();  
  10.            await empCollector.AddAsync(knowledge);  
  11.            return new OkResult();  
  12.        }  

Right here we’re including the info to the Queue utilizing AddAsync technique.

Please make it possible for AzureWebJobsStorage is utilizing the dev storage within the native.settings.json file.

“AzureWebJobsStorage”: “UseDevelopmentStorage=true”

With these modifications, we’ll be capable of see worker data within the native Queue storage by utilizing emulator.

Now, we have to implement Queue as a enter binding and the queue’s knowledge can be saved in Blob container as an output. Right here, we have to create a brand new Queue operate set off class:

  1. [FunctionName("QueueTrigger")]  
  2.         public void QueueTriggerAndBlobOutput(  
  3.             [QueueTrigger("order", Connection = "AzureWebJobsStorage")] Worker worker,  
  4.             [Blob("employee/{rand-guid}.json")] TextWriter textWriter)  
  5.         {  
  6.             textWriter.WriteLine($"id:{worker.Id}");  
  7.             textWriter.WriteLine($"Identify:{worker.Identify}");  
  8.             textWriter.WriteLine($"Age:{worker.Age}");  
  9.             textWriter.WriteLine($"Metropolis:{worker.Metropolis}");  
  10.             textWriter.WriteLine($"State:{worker.State}");  
  11.         }  

Within the above pattern, QueueTrigger is used as an enter binding. We’re specifying the Queue identify (worker) and connection string within the QueueTrigger attribute.

Blob container is used as output binding by specifying the Blob attribute. Right here, “worker” is the identify of the blob container and for each queue set off, a brand new guid id can be generated within the container.

See how straightforward it’s to implement these storages within the Azure Features, and it helps to eradicate boilerplate code.

State of affairs 2

Slightly than utilizing the earlier EF core instance, I am utilizing a less complicated instance.

Firstly, upon triggering of HTTP request, the HTTP request physique can be despatched as a request to Server Bus-Queue by utilizing an output binding.

Secondly, after the message is shipped to the server bus queue, operate can be triggered and the info can be logged within the software.

Conditions

  • Add nuget package- Microsoft.Azure.WebJobs.Extensions.ServiceBus
  • Create a brand new Azure service bus queue by referring to my article right here
  1. [FunctionName("HttpToServiceBusQueue")]  
  2.         
  3.         public static async Activity<IActionResult> Run(  
  4.             [HttpTrigger(AuthorizationLevel.Anonymous, "get""post", Route = null)] HttpRequest req,  
  5.             [ServiceBus("testqueue",Connection ="connectionString")] IAsyncCollector<string> outputEvents,  
  6.             ILogger log)  
  7.         {  
  8.             log.LogInformation("C# HTTP set off operate processed a request.");  
  9.   
  10.             string identify = req.Question["name"];  
  11.   
  12.             string requestBody = await new StreamReader(req.Physique).ReadToEndAsync();  
  13.             dynamic knowledge = JsonConvert.DeserializeObject(requestBody);  
  14.             identify = identify ?? knowledge?.identify;  
  15.             await outputEvents.AddAsync(requestBody);  
  16.             string responseMessage = string.IsNullOrEmpty(identify)  
  17.                 ? "This HTTP triggered operate executed efficiently. Go a identify in the question string or in the request physique for a personalised response."  
  18.                 : $"Hey, {identify}. This HTTP triggered operate executed efficiently.";  
  19.             return new OkObjectResult(responseMessage);  
  20.         }  

Now we have used ServiceBus attribute as an output binding; nevertheless, you’ll want to specify the queue identify (created in Azure) and the connection string from the “Shared Entry Insurance policies” within the Azure portal.

  1. [FunctionName("servicebusQueue")]  
  2.      public static void Run([ServiceBusTrigger("testqueue", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log)  
  3.      {  
  4.          log.LogInformation($"C# ServiceBus queue set off operate processed message: {myQueueItem}");  
  5.      }  

I am simply logging the info that we obtained from the ServiceBus queue.

Lastly, we’ve managed to place all of the code modifications in place.

I hope you just like the article. In case you discovered this text attention-grabbing, kindly like and share it.

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button