How To Trigger Azure Functions

How To Trigger Azure Functions

In this Azure tutorial, we will discuss How To Trigger Azure Functions. Along with this, we will also discuss a few other topics Azure Function Triggers, Create a simple scheduled trigger in Azure Portal, Azure Functions Input, and OutPut Bindings and Azure Function Multiple Output Bindings, Azure Function Multiple Triggers, Azure Function Host Key.

How To Trigger Azure Functions? Trigger plays an important role in the case of Azure Function. The whole process is, once the event fires the trigger, the trigger is the one that then runs the Azure Functions associated with that trigger. There are different types of triggers that are available in Azure. Below we will discuss in detail.

How To Trigger Azure Functions

As we have already discussed, Trigger plays a vital role in the case of Azure Functions. The trigger is the one that invokes the Azure Functions or in other words, Trigger is responsible to start the Azure Function.

How To Trigger Azure Function

Note: One Azure function can have only one trigger. An Azure function cannot have more than one trigger.

Azure Function Triggers

There are different types of triggers provided by Azure that can be used for your Azure Function. Below are the few among them

  • HTTP Trigger: HTTP Trigger is one of the Basic And simple triggers that you can use for your Azure Function. In case the HTTP requests come, this trigger gets fired.
  • Queue Trigger: This is another category of trigger that you can use for your Azure Function, In case any new message comes in an Azure Storage queue, this trigger gets fired.
  • TimerTrigger: If you want your Azure Function to execute in a specified time, you can use the Timmer Trigger for your Azure Function.
  • Service Bus Trigger: Service Bust Trigger gets fired in case a new message comes from a service bus queue.
  • Azure Event Hub Trigger: Event Hub Trigger gets fired in case any events are delivered to the Azure event hub. This trigger is used basically for workflow processing, user experience, etc.
  • Generic Webhook: This is is another category of trigger that gets fired in the case of HTTP requests comes from any service that actually supports the Webhooks.
  • GitHub WebHook: Git Hub Webhook trigger gets fired in case any of the events like Branch created, delete branch, Comment on Commit, etc occurs in your GitHub repositories.
  • Azure Cosmos DB trigger: This is another type of trigger that gets triggered whenever documents get a change in the Document collection.
  • Azure Event Grip Trigger: This is a trigger that gets triggered whenever the event grid receives a new event.

So these are the key triggers that are available for your Azure Function and can be used based on your business needs.

Create a simple scheduled trigger in Azure Portal

Well, here we will discuss How to create a simple scheduled trigger in the Azure Portal. If you will consider a scenario to display a “Welcome” on the computer screen every 5 minutes. Then in that case you can create a timer trigger and set the value for the CORN expression so that the Azure Function will execute at each 5 minutes interval of time.

Follow the below steps for creating a simple scheduled trigger Azure Function in Azure Portal.

Azure Function Timer Trigger

Log in to the Azure Portal (https://portal.azure.com/)

Search for the Function App and click on the search result

Create a simple scheduled trigger in Azure Portal

Now, click on the + Add button to create a function App.

How to Create a simple scheduled trigger in Azure Portal

On the next window, select your correct Subscription, Choose a Resource group or if you don’t have any existing Resource group, you can create a new one by clicking the Create new link, Provide a unique name for the Azure Function App, Choose the code as the Publish option, Choose the .NET Core as the Runtime stack option, You can choose the version option as 3.1 and finally, choose the region for the Function App and then click on the Next: Hosting > button to go to the Hosting tab.

timer trigger azure function example c#

On the Hosting tab, you need to provide an existing storage account and if you don’t have any you can click on the create a new link to create a new storage account. If you don’t do anything also, it will create a new storage account for you. Now the next thing is to select the Operating system, the default option is Windows and choose the plan type, here the default option is consumption (serverless).

How to create timer trigger azure function c#

Keep the other tab values as it is, Now click on the Review + create button, Now it will validate all the values entered and will show you the summary Details and now Finally click on the Create button to create the Azure Function App on the same window.

Now, you can able to see it is showing us Your deployment is complete and you can click on the Go to resource button to see to navigate to the Function App, you have created just now.

timer trigger azure function c#

Now the next is, we will have to add a trigger, To add the trigger, we need to create an Azure Function. Click on the Functions link from the left navigation and then click on the + Add button on the Function app page as highlighted below.

azure function timer trigger

On the New Function window, select the template as Timer trigger as shown below.

timertrigger azure function c#

Provide the name of the Azure timer function and on the Schedule option provide the CORN expression as 0*/5****, which means the Azure function will execute on each 5 minutes interval of time. Then click on the Create Function button to create the Azure Timmer Function.

azure function timer trigger schedule expression

Now your Azure Timer function will be created successfully. Click on the Code + Test option from the left navigation, you can able to see the Azure Function code like below for the run.csx file

using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
azure function triggers

Now you can add the code as per you functionality on this file and then click on the Save button to save the changes, finally click on the Test/Run button to test the Azure function if it is working fine or not. Now if we will try to run this Azure function to make sure it is working fine, click on the Test/Run button and then click on the Run button on the Input window.

Now you can able to see the below logs that show the execution of the Azure Function on the specified time that is you can see the Azure trimmer function executed on each 5 minutes timeline.

how to trigger azure function http

HTTP trigger

As we have already discussed, the HTTP trigger is one of the simple and very useful triggers that are used to handle the HTTP requests and basically use to build the API or services that handle the HTTP requests.

We have already created the Azure Function App, Now let’s create an HTTP triggered Azure Function following the below steps. The Purpose of this Azure Function is When you will provide a value for the name parameter, it will validate with a regular expression and will show you the Output is a valid name or an invalid name.

Navigate again to the Azure Function App that we have created above. On the Azure Function App page, click on the functions option from the left navigation and then click on the + Add button

Http Triggered Azure Function Example

On the new function, select the HTTP trigger Azure function template.

C# Http Triggered Azure Function Example

Now in the next window, Provide a name for the HTTP triggered Azure Function and then choose the Authorization level as function and then click on the Create Function to create the HTTP triggered Azure function.

azure function httprequest

Now it will create the HTTP triggered function successfully. Now you can able to see the run.csx file contains the below code

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
}

Now replace your Azure Function Code with the below code and then click on the Save button to save the modified code changes.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];
    string pattern = @"^[a-zA-Z-.' ]{2,64}$";

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    bool isNameValid = Regex.IsMatch(name, pattern);      
    log.LogInformation("The result for " + name + ": " + isNameValid);

    return name != null && isNameValid
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("This is not a Valid Name");
}

Now click on the Test/Run button to test the Azure function if it is working fine or not. Provide the name value as “@@@@@@@$$$$$” on the Input window and then click on the Run button.

how to trigger azure function

You can able to see, we got the expected output as below with the response code as “400 Bad Request” and the response message as “This is not a Valid Name”.

Creating Azure HTTP triggered function using Azure Portal

Now we will provide a valid name as “Raj” and now we will run the Azure Function and will see the Output. You can able to see below, we got the expected output with the Proper Response Code.

Creating Azure HTTP triggered function C# Azure Portal

Azure Event Hub Trigger

Azure Event Hub trigger provides the option to handle millions of events-based messaging. it can help us to process millions of events in a few seconds.

Event Hub Trigger gets fired in case of any events are delivered to the Azure event hub. The purpose of this trigger is basically for workflow processing, user experience, etc.

A number of events will be created by the Event Hubs that can be processed in different ways. This is used to respond to the event sent to an event hub event stream.

Now lets create an Azure Event Hub trigger Azure function by following the below steps.

Navigate to the Azure Function App that we have created above. Click on the functions option from the left navigation on the Azure Function App page and then click on the + Add button

Azure Event Hub Trigger Azure Function Example

On the new function, select the Azure Event Hub trigger template.

How to create an Azure Event Hub trigger

Now in the next window, Provide a name for the Azure Event Hub trigger and then choose the Event Hub connection as an existing connection or else click on the New link to create a new Event Hub connection. Provide the name for the Event Hub name and Event Hub consumer group then click on the Create Function to create the Azure Event Hub trigger.

How to create Azure Event Hub Trigger

Now if you will click on the Code + Test link and you can able to see the run.csx file and below is the code for this file

#r "Microsoft.Azure.EventHubs"


using System;
using System.Text;
using Microsoft.Azure.EventHubs;

public static async Task Run(EventData[] events, ILogger log)
{
    var exceptions = new List<Exception>();

    foreach (EventData eventData in events)
    {
        try
        {
            string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

            // Replace these two lines with your processing logic.
            log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
            await Task.Yield();
        }
        catch (Exception e)
        {
            // We need to keep processing the rest of the batch - capture this exception and continue.
            // Also, consider capturing details of the message that failed processing so it can be processed again later.
            exceptions.Add(e);
        }
    }

    // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

    if (exceptions.Count > 1)
        throw new AggregateException(exceptions);

    if (exceptions.Count == 1)
        throw exceptions.Single();
}

Now click on the Test/Run and click on the Run button on the Input window button to test the Azure function if it is working fine or not.

Create Azure Event Hub Trigger in Azure Portal

Azure Function Queue Trigger

Azure Function Queue Trigger is another category of Azure function trigger that gets fired in case any new message comes in an Azure storage queue. It delivers the asynchronous messages between application components for the communication. It can store a large number of messages and can be accessed with the help of HTTP or HTTPS protocols. The maximum size of a single message is 64 kb.

Let’s see how to create the Azure function queue trigger using the Azure Portal.

Navigate to the Azure Function App that you have created above and then click on the Functions option from the left navigation on the Azure Function App page and then click on the + Add button to create the new Azure Function Queue trigger.

Azure Function Queue Trigger Azure Function Example

Select the Azure Queue Storage trigger template

How to create Azure Function Queue Trigger

Provide a name for the function and Queue and then select a storage account connection and then click on the Create function button.

create Azure Function Queue Trigger

Now, on the Azure Function page, click on the Code + Test link from the left navigation and you can able to see the run.csx file.

create Azure Function Queue Trigger C#

The run.csx file contains the below code

using System;

public static void Run(string myQueueItem, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}

You can modify the run.csx file based on your business requirement.

Now to check if the function is working fine or not, you can click on the Test/Run button and then click on the Run button on the Input window, Now you can able to see we got the expected response code.

Azure Function Queue Trigger example

Azure Service Bus Trigger

The service Bus Trigger is responsible to provide a response to the messages that come from the service bus queue or topic.

There are two types of Azure Service Bus Triggers are available

  1. Service Bus Queue Trigger: As the name suggests, the Service Bus Queue Trigger works on first in first out messages principle. As soon as the message comes from the service bus, the service bus queue trigger gets fired, and then it calls the Azure Function immediately.
  2. Service Bus Topic Trigger: This type of Azure trigger is responsible for scaling to the numbers of recipients.

Azure Functions Input and OutPut Bindings

Azure Functions bindings can be InPut or OutPut bindings. You can call the Bindings as the connection to the data within your Azure Function.

  • Input Bindings: When an Azure function receives the data that is termed as Input Bindings.
  • Output Bindings: Output Bindings are exactly the opposite of the Input Bindings, this is the data that the Azure function sends.

Azure Function Multiple Output Bindings

Some times you will have some scenarios, where you will have to configure the Azure Function with multiple output bindings. If you will consider a scenario where you will have to create an Azure Function that outputs the message to Azure Queue Storage and the same message you have to output in the Azure Table Storage as well.

You can able to achieve this using the Azure Function. We will see the steps to implement these scenarios using the Azure Portal.

Navigate to the Azure Function App, that you have created above and click on the Functions from the left navigation and create an HTTP trigger function like above.

Once your function is created, click on the Integration option from the left navigation on the Azure Function page.

Azure Function Multiple Output Bindings

Click on the + Add output under the Outputs Option as highlighted below

Azure Functions with Multiple Output Bindings

On the Create Output window, choose the Binding type as Azure Queue storage and Keep the other option as it is (Default values) and click on the Ok button.

Multiple output in Azure Functions with C#

Again, click on the + Add output from the below window.

Multiple output in Azure Functions with C# Example

Again, On the Create Output window, choose the Binding type as Azure Table storage and Keep the other option as it is (Default values) and click on the Ok button.

How to implement Azure Function Multiple Output Bindings

Now the Outputs section looks like below

How to implement Azure Function Multiple Output Bindings C#

Now if you will see your Function.json file it looks like below and contains the below code

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "outputQueueItem",
      "direction": "out",
      "type": "queue",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputTable",
      "direction": "out",
      "type": "table",
      "tableName": "outTable",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Now as per the above code, function.json tells the Azure Function that you now have two output bindings. In this case we want to output to a table named outputTable and a storage queue names outqueue

Now Finally, you need to modify the code of the run.csx file as per the business requirement and then click on the Test/Run button and then click on the Run button from the Input window.

Azure Function Multiple Triggers

As per Microsoft, Till now, there is no plan to supports multiple triggers per single Azure function. You need to create an Azure function for each requirement. If you are thinking you have some common code to use, you keep the common code in a helper method and then call the helper method from each function.

Azure Function Host Key

An Azure Function Host key is a key that is shared by all the Azure functions that are hosted on a particular function app. You can able to retrieve all the keys including the AzureFunction Host key from your Azure Function app.

You may also like following the below articles

Wrapping Up

Well, in this article, we have discussed How To Trigger Azure Functions, Azure Function Triggers, Create a simple scheduled trigger in Azure Portal, Azure Functions Input, and OutPut Bindings and we have also discussed Azure Function Multiple Output Bindings, Azure Function Multiple Triggers, Azure Function Host Key. Hope you have enjoyed this article !!!

Leave a Comment