Showing posts with label Azure functions. Show all posts
Showing posts with label Azure functions. Show all posts

Overview of all trigger type in Azure functions

 Overview of all trigger type in Azure functions


Azure Functions are a type of serverless computing that allow developers to run small pieces of code, called functions, without having to worry about managing the infrastructure. Azure Functions can be triggered by a variety of events, or triggers, such as HTTP requests, messages from a queue, or updates to a database. 

Let's dive into the different trigger types available in Azure Functions. 

HTTP Trigger

The HTTP trigger allows you to invoke your Azure Function by making an HTTP request. This is typically used when you want to create a REST API or expose an endpoint that can be called by a client application. The HTTP trigger can be configured to accept different HTTP methods, such as GET, POST, PUT, DELETE, etc. 

Timer Trigger

The timer trigger allows you to run your Azure Function on a schedule. You can specify the schedule using a CRON expression, which allows you to define complex schedules such as "every weekday at 9am and 5pm". The timer trigger is useful for tasks such as periodic data processing or sending out reports on a regular basis. 

Blob Trigger

The blob trigger allows you to run your Azure Function whenever a new or updated blob is added to a storage account. This trigger is useful when you need to process files as they are uploaded, such as converting an image to a thumbnail or processing a video file. 

Queue Trigger

The queue trigger allows you to run your Azure Function whenever a new message is added to a queue in Azure Storage or Azure Service Bus. This trigger is useful for processing messages in a queue, such as sending out email notifications or processing orders. 

Event Grid Trigger

The Event Grid trigger allows you to run your Azure Function in response to an event published by Azure Event Grid. Event Grid is a service that allows you to react to events happening in Azure resources, such as a new virtual machine being created or a storage account being updated. The Event Grid trigger is useful when you want to react to changes happening in Azure resources. 

Service Bus Trigger

The Service Bus trigger allows you to run your Azure Function whenever a new message is added to a queue or topic in Azure Service Bus. This trigger is useful for processing messages in a queue or topic, such as processing orders or sending out notifications. 

Cosmos DB Trigger

The Cosmos DB trigger allows you to run your Azure Function whenever there is a change in the data stored in Cosmos DB. This trigger is useful for reacting to changes in data, such as updating a search index or sending out notifications. 

Durable Functions

Durable Functions are a type of Azure Function that allow you to create stateful workflows. They can be triggered by any of the above trigger types, and are useful when you need to create a workflow that involves multiple steps or when you need to orchestrate a long-running process. 

In conclusion, Azure Functions provide a wide variety of triggers that allow you to run your code in response to different events. By understanding the different trigger types available, you can choose the appropriate one for your specific use case and build powerful serverless applications

Azure functions "XXX was disallowed by policy"


Azure functions "XXX was disallowed by policy"

Azure Functions is a serverless computing platform that allows developers to run small pieces of code, called functions, in the cloud. These functions can be triggered by events such as HTTP requests or database updates, and can be written in a variety of programming languages. While Azure Functions is a powerful tool for building and deploying applications, it can sometimes be difficult to troubleshoot errors that occur during development or deployment. 

One common error that developers encounter when working with Azure Functions is the "XXX was disallowed by policy" error message. This error message typically indicates that an action or operation performed by the function has been blocked by Azure policy. In this blog post, we will explore some common causes of this error message and provide some tips for troubleshooting and resolving the issue. 

  • Check Azure Policy Settings

The first step in troubleshooting the "XXX was disallowed by policy" error is to check the Azure policy settings for your subscription. Azure policy is a service that allows you to create and enforce rules for resources in your subscription. These rules can help you ensure compliance with regulations and industry standards, as well as improve security and manage costs.

To check your Azure policy settings, go to the Azure portal and navigate to the Policies tab. Here, you can view and manage your policy definitions, assignments, and exemptions. Look for any policies that may be blocking the operation or action performed by your function, and adjust the policy settings as needed.

  • Enable Diagnostic Logging

Enabling diagnostic logging can help you identify the cause of the "XXX was disallowed by policy" error message. Diagnostic logs can provide detailed information about the operation or action that triggered the error, as well as any policy violations that occurred.

To enable diagnostic logging, go to the Monitoring tab in the Azure portal and select Diagnostics settings. Here, you can configure diagnostic settings for your function app, including which logs to collect and where to store them.

  • Contact Azure Support

If you have tried all of the above troubleshooting steps and are still unable to resolve the "XXX was disallowed by policy" error message, contact Azure support for assistance. Azure support can help you diagnose and troubleshoot the issue, and may be able to provide additional guidance on how to resolve the issue.


In conclusion, the "XXX was disallowed by policy" error message can be a frustrating issue to encounter when working with Azure Functions. 

By following the troubleshooting steps outlined in this blog post, you can quickly identify and resolve the issue, allowing you to get back to developing and deploying your applications.


Azure functions coding best practices with examples

Azure functions coding best practices with examples

Azure Functions is a serverless compute service that enables developers to build and deploy event-driven, serverless applications at scale. It provides a fully managed, platform-as-a-service (PaaS) environment for building and running microservices-based applications. To help developers build high-quality and scalable Azure Functions, here are some coding best practices to follow:

  • Keep Functions Small and Focused

Each Azure Function should do one specific task and nothing else. Avoid creating a large function that performs multiple tasks, as it can make your code difficult to read, test, and maintain. Instead, break your code into smaller functions that perform individual tasks, and compose them to create more complex workflows.

For example, consider an e-commerce application that sends a confirmation email when a customer places an order. Instead of creating a single function that retrieves order details, composes an email, and sends it, break it into three smaller functions: one to retrieve order details, one to compose an email, and one to send the email.

  • Use Dependency Injection

Azure Functions supports dependency injection (DI), which is a design pattern that enables you to decouple your code by injecting dependencies into functions. It makes your code more modular, testable, and easier to maintain. Use DI to inject dependencies such as database connections, services, and configurations.

For example, let's say you have a function that needs to access a database to retrieve data. Instead of creating a new database connection every time the function is called, use DI to inject the database connection as a dependency.

  • Use Logging and Tracing

Logging and tracing are essential for troubleshooting and monitoring your Azure Functions. Use a logging framework such as Azure Application Insights to log events and exceptions. Use tracing to track the execution path of your functions.

For example, consider a function that retrieves data from a database. Use tracing to track the execution path of the function, such as when it connects to the database, retrieves data, and returns the result. Use logging to record any exceptions that occur during the execution of the function.

  • Use Environment Variables

Use environment variables to store important information such as connection strings, API keys, and passwords. It enables you to change the configuration of your application without modifying your code.

For example, let's say you have a function that connects to a database. Instead of hard-coding the connection string in your code, use an environment variable to store it.

Note: You can store sensitive information in key-vault which is more secure and use in App Setting.

  • Use Async/Await

Azure Functions supports asynchronous programming, which enables you to write code that doesn't block the execution of the function. Use the async/await keywords to write asynchronous code.

For example, consider a function that retrieves data from a database. Use async/await to perform the database query asynchronously, so the function can continue to execute while the query is running.

  • Use Continuous Integration and Deployment

Use continuous integration and deployment (CI/CD) to automate the deployment of your Azure Functions. Use a CI/CD pipeline to build, test, and deploy your code to different environments.

For example, let's say you have a development, staging, and production environment. Use a CI/CD pipeline to build and test your code in the development environment, then deploy it to the staging environment for further testing, and finally deploy it to the production environment when it's ready.

  • Use Appropriate Trigger Types

Choose the appropriate trigger type for your function based on the type of event you want to process. Azure Functions supports various trigger types, including HTTP triggers, blob storage triggers, Cosmos DB triggers, and more.

For example, if you want to process an HTTP request, use an HTTP trigger. If you want to process a file uploaded to a storage account, use a blob storage trigger.

  • Use Appropriate Binding Types

Choose the appropriate binding type for your function based on the type of data you want to access. Azure Functions supports various binding types, including input bindings, output bindings, and trigger bindings.

For example, if you want to read data from a storage account, use an input binding. If you want to write data to a database, use an output binding.

  • Use Durable Functions for Long-Running Workflows

Use Durable Functions to create long-running workflows that can span multiple function invocations. Durable Functions provides an extension to Azure Functions that enables you to write stateful workflows in a serverless environment.

For example, consider a workflow that involves multiple steps, such as processing an order, sending an email notification, and updating a database. Use Durable Functions to create a stateful workflow that can track the progress of each step and handle failures gracefully.

  • Use Azure App Configuration 

Use Azure app configuration to manage the commonalty used App Setting by multiple function app . 

Use environment-specific configuration like Dev/Test/Prod etc.

For example, consider multiple function app that needs to access same database. Use a App configuration to store the database connection string, and use the appropriate configuration value relevant Azure functions such that if you need to update connection string the updating at one place will reflect in all function app.

  • Use Unit Testing

Use unit testing to test the individual functions of your Azure Functions application. Write unit tests to ensure that each function behaves correctly and handles inputs and outputs as expected.

For example, write unit tests for each function to ensure that it returns the expected output given a particular input. Use a testing framework such as NUnit, xUnit, or MSTest to write and run unit tests.


These are some best practices for Azure Functions coding that can help you write high-quality, scalable, and maintainable applications.

Start/stop azure functions through PowerShell and Azure CLI

 

Start/stop azure functions through PowerShell and Azure CLI

Azure Functions is a serverless compute service that enables you to run code on-demand without the need to manage infrastructure. In this blog, we'll discuss how to start and stop Azure Functions using PowerShell and Azure CLI. 

Start/Stop Azure Functions using PowerShell

To start or stop Azure Functions using PowerShell, you can use the Start-AzFunctionApp and Stop-AzFunctionApp cmdlets, respectively. Here's how you can use them: 

To start an Azure Function App, run the following command in PowerShell: 

Start-AzFunctionApp -Name <function-app-name> -ResourceGroupName <resource-group-name>

Replace <function-app-name> and <resource-group-name> with the actual names of your function app and resource group, respectively.

 

To stop an Azure Function App, run the following command in PowerShell: 

Stop-AzFunctionApp -Name <function-app-name> -ResourceGroupName <resource-group-name>

Replace <function-app-name> and <resource-group-name> with the actual names of your function app and resource group, respectively. 


Start/Stop Azure Functions using Azure CLI

To start or stop Azure Functions using Azure CLI, you can use the az functionapp start and az functionapp stop commands, respectively. Here's how you can use them: 

To start an Azure Function App, run the following command in Azure CLI: 

az functionapp start --name <function-app-name> --resource-group <resource-group-name>

Replace <function-app-name> and <resource-group-name> with the actual names of your function app and resource group, respectively. 

To stop an Azure Function App, run the following command in Azure CLI: 

az functionapp stop --name <function-app-name> --resource-group <resource-group-name>

Replace <function-app-name> and <resource-group-name> with the actual names of your function app and resource group, respectively. 

Conclusion

In conclusion, starting and stopping Azure Functions can be done easily using either PowerShell or Azure CLI. By understanding the commands and parameters required to start and stop a function app, you can manage your serverless compute resources with ease and efficiency.


Azure functions PowerShell tips and tricks

Azure functions PowerShell tips and tricks 


Azure Functions is a popular serverless computing platform that allows developers to write and run event-driven functions in the cloud. 

The Azure Functions PowerShell module provides a way to interact with and manage Azure Functions using PowerShell. In this blog, we will explore some tips and tricks to help you get the most out of the Azure Functions PowerShell module.

1. Install the Azure Functions PowerShell Module

To install the Azure Functions PowerShell module, open PowerShell and run the following command:

Install-Module -Name Az.Functions

This command will install the latest version of the Azure Functions PowerShell module from the PowerShell Gallery.

2. Connect to Your Azure Subscription
To connect to your Azure subscription using the Azure Functions PowerShell module, run the following command:

Connect-AzAccount

This command will prompt you to enter your Azure credentials and connect to your subscription.

3. Create a Function App
To create a new Function App using PowerShell, run the following command:

New-AzFunctionApp -ResourceGroupName <resource-group-name> -Name <function-app-name> -Location <location>

This command will create a new Function App in the specified resource group and location.

4. Create a New Function
To create a new function in your Function App, run the following command:

New-AzFunction -ResourceGroupName <resource-group-name> -Name <function-name> -FunctionAppName <function-app-name> -File <path-to-function-file> -Trigger <trigger-type>

This command will create a new function in your Function App with the specified trigger type and code file.

5. Run the Function Locally
To run the function locally using PowerShell, run the following command:

func start

This command will start a local version of the Azure Functions runtime and allow you to test your function.

6. Debug the Function Locally
To debug the function locally using PowerShell, run the following command:

func host start --debug

This command will start the Azure Functions runtime in debug mode, which allows you to use a debugger to step through your code.

7. Deploy the Function to Azure
To deploy the function to Azure using PowerShell, run the following command:

Publish-AzFunctionApp -ResourceGroupName <resource-group-name> -Name <function-app-name> -ArchivePath <path-to-function-zip-file>

This command will package and deploy the function to the specified Function App.

8. Manage Function App Settings
To manage your Function App settings using PowerShell, run the following command:

Get-AzFunctionApp -Name <function-app-name> -ResourceGroupName <resource-group-name> | Set-AzFunctionAppSetting -Name <setting-name> -Value <setting-value>

This command will get the specified Function App and update the specified setting with the specified value.

Conclusion
The Azure Functions PowerShell module provides developers with a powerful way to interact with and manage Azure Functions using PowerShell. By using these tips and tricks, you can get the most out of the Azure Functions PowerShell module and streamline your development workflow. Whether you're a seasoned PowerShell user or just getting started with Azure Functions, the PowerShell module is a valuable tool that can help you build and deploy serverless applications with ease.

Azure functions CLI tips and tricks

 Azure functions CLI tips and tricks


Azure Functions is a popular serverless computing platform that allows developers to write and run event-driven functions in the cloud.

The Azure Functions CLI is a command-line interface that provides developers with a local development experience for creating, testing, and debugging Azure Functions. In this blog, we will explore some tips and tricks to help you get the most out of the Azure Functions CLI.


1. Create a Function Project

To create a new Function Project using the CLI, run the following command:

func init <project-name> 

This command will create a new Function Project in the current directory with the specified name.

2. Create a New Function

To create a new function in your project, run the following command:

func new

This command will prompt you to choose a function template and specify the function name and trigger type.

3. Run the Function Locally

To run the function locally, run the following command:

func start

This command will start a local version of the Azure Functions runtime and allow you to test your function.

4. Debug the Function Locally

To debug the function locally, run the following command:

func host start --debug

This command will start the Azure Functions runtime in debug mode, which allows you to use a debugger to step through your code.

5. Deploy the Function to Azure

To deploy the function to Azure, run the following command:

func azure functionapp publish <function-app-name>

This command will deploy the function to the specified Azure Function App.

6. Add a Binding to a Function

To add a binding to a function, run the following command:

func extensions install --package <package-name>

This command will install the specified package and add the binding to your function.

7. Manage Function App Settings

To manage your Function App settings using the CLI, run the following command:

func azure functionapp list-functions <function-app-name>

This command will list all the functions in the specified Function App and their associated settings.

8. Work with Multiple Environments

To work with multiple environments, you can create a separate Function Project for each environment and use environment variables to configure the settings for each environment.

9. Use a Custom Docker Image

To use a custom Docker image, you can specify the image in your project's Dockerfile and use the following command to deploy the function to Azure:

func azure functionapp publish <function-app-name> --docker-container-image <docker-image-name>

Conclusion

The Azure Functions CLI provides developers with a powerful local development experience for creating, testing, and debugging Azure Functions. By using these tips and tricks, you can get the most out of the Azure Functions CLI and streamline your development workflow. Whether you're a seasoned developer or just getting started with Azure Functions, the CLI is a valuable tool that can help you build and deploy serverless applications with ease.

C# code to start stop azure functions


C# code to start stop azure functions

Azure Functions is a serverless compute service that allows you to run code on-demand without worrying about infrastructure management. With Azure Functions, you can run small pieces of code called "functions" in the cloud. These functions can be triggered by events like changes to data in Azure Storage or incoming HTTP requests.

 In this article, we will learn how to start and stop Azure Functions using C# code. We will use the Azure Management Libraries for .NET to interact with the Azure Functions Management API.

Prerequisites

To follow this article, you will need the following:

  • An Azure account with an active subscription
  • Visual Studio 2019 or later installed on your machine
  • Azure Management Libraries for .NET installed

Step 1: Create an Azure Functions App

First, let's create an Azure Functions App in the Azure Portal. This app will serve as the target for our start and stop functions. 

  1. Go to the Azure Portal and sign in.
  2. Click on the "Create a resource" button and search for "Function App".
  3. Click on "Function App" and then click on the "Create" button.
  4. Fill out the required information, such as subscription, resource group, and app name.
  5. Select the runtime stack and operating system for your functions app.
  6. Choose the hosting plan and storage account that you want to use.
  7. Click on the "Create" button to create the Azure Functions App.

Step 2: Install the Azure Management Libraries for .NET

Next, let's install the Azure Management Libraries for .NET. This will allow us to use the Azure Functions Management API to start and stop our functions.

 Open Visual Studio and create a new C# console application.

  1. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages".
  2. Search for "Microsoft.Azure.Management.Fluent" and install the latest version.
  3. Search for "Microsoft.Azure.Management.AppService.Fluent" and install the latest version.

Step 3: Retrieve the Azure Functions App

Now, let's write the C# code to retrieve our Azure Functions App.

  1. Import the necessary namespaces at the top of your code file:

using Microsoft.Azure.Management.Fluent;

using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.AppService.Fluent;

      2. Add the following code to retrieve the Azure Functions App:

var credentials = SdkContext.AzureCredentialsFactory.FromFile("<path-to-your-credentials-file>");

var azure = Azure

    .Configure()

    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)

    .Authenticate(credentials)

    .WithDefaultSubscription();

var functionApp = azure.AppServices.FunctionApps.GetByResourceGroup("<resource-group-name>", "<function-app-name>");

 The first line of code creates an Azure credentials object using a credentials file. Make sure to replace "<path-to-your-credentials-file>" with the path to your credentials file. 

The next few lines of code configure the Azure Management Libraries for .NET and authenticate with the Azure account associated with your credentials file.

 The last line of code retrieves the Azure Functions App using the resource group name and function app name.

Step 4: Start and Stop Azure Functions

Finally, let's write the C# code to start and stop our Azure Functions.

 

  1. Add the following code to start the Azure Functions
         functionApp.Start();

      2. Add the following code to stop the Azure Functions:

         functionApp.Stop();

That's it! Now you can use this C# code to start and stop your Azure Functions as needed. Make sure to test your code thoroughly before deploying it to production.


Azure functions| function(s) are not visible in the portal

 Azure functions| function(s) are not visible in the portal

Issue:

  •  Portal is not displaying functions.


Solution:

Azure functions (function app) is the container of function like http trigger, timer, blob trigger etc.

Not displaying function on portal after deployment or any other time is very common issue.

Here we are focusing on one scenario only which can be the potential cause of this issue there can be some other scenarios which are not covered here.

 

we are talking about a property which is very frequently used with deployments.

 

WEBSITE_RUN_FROM_PACKAGE

1.       Check value

a.       If WEBSITE_RUN_FROM_PACKAGE = 1

                        i.      Content location is (in KUDU), d:\home\data\SitePackages

1.       Validate if SitePackages folder is available or not?

2.       Validate if folder contains correct files/DLLs which are needed for functions

                      ii.      packagename.txt (Inside folder d:\home\data\SitePackages)

1.       Is it pointing to correct package or not?

2.       There should not be any whitespace in name mentioned inside packagename.txt.

                    iii.      WWWROOT folder

1.       Validate if contents are mounted properly from SitePackages folder to WWWROOT folder

2.       If contents are not mounted properly then you may see one txt file with name “FAILED TO INITIALIZE RUN FROM PACKAGE.txt”



 

b.       If WEBSITE_RUN_FROM_PACKAGE = <Storage account URL>

                        i.      Does Storage account exist?

1.       Yes?

a.       Validate connection string

                                                               i.      Check if connection string is correct or not.

                                                             ii.      Get the connection string from storage account and compare with the app settings value.

b.       Validate SAS expiry

                                                               i.      Check if SAS token is expired or not

c.       Validate connectivity.

                                                               i.      Check if any network or firewall restriction is preventing Azure functions to connect with storage account

d.       Sync trigger

                                                               i.      If functions are not visible after latest deployment the check if sync trigger (which is mandatory) operation was performed post deployment or not.

e.       Managed Identity

                                                               i.      Validate managed identity configurations.

                                                             ii.      Azure Blob Storage can be configured to authorize requests with Azure AD. This means that instead of generating a SAS key with an expiration, you can instead rely on the application's managed identity (Ref)

2.       No?

a.       Storage account is mandatory in this case.

b.   Exit


Hope this helps.

Azure Functions timeout

Azure Functions timeout

Everything about function app timeout

 

Issue:

·       Timeout value of 00:05:00 exceeded by function?

·       What is azure functions timeout?

·       What is azure functions execution timeout?

·       What is default timeout in azure function?

·       Consumption plan timeout?

·       Premium plan timeout?

 

Solution:

What is timeout?  In business logic language, a timeout is a specified period of time that will be allowed to complete an operation and if that operation doesn’t complete within specified period of time then it will throw some exception. Timeouts allow for more efficient usage of limited resources without requiring additional interaction from the agent interested in the goods that cause the consumption of these resources.

A common example is your smart phone turn off backlight after a certain time when idle which you can set.

Similarly, Azure has set the timeout for function app and it is very important to understand it as you can develop/write your business logic and optimize it accordingly.

In Azure functions, timeout means if your business logic or code should be optimized enough to complete with timeout duration otherwise it throws exception like “Timeout value of 00:05:00 exceeded by function”


In Azure functions, timeout varies according to hosting plan and runtime versions.

Azure functions have 3 hosting plans,

  • Consumption plan (Dynamic plan)
  • Premium plan (Elastic premium plan)
  • App Service plan (Dedicated plan
And as of now it has 3 runtime versions,

·       1.x

·       2.x

·       3.x

Where 1,2 and 3 is the major version and x stand for minor version e.g. 2.09234.

Now we know what azure functions execution timeout is? hence we should focus on

·       Default timeout,

·       maximum timeout

for each hosting plan.

You can check this information in the below list.

Azure Functions timeout











That means if you see exception like “Timeout value of 00:05:00 exceeded by function” then you quickly need to check if your function is hitting the default timeout.

Here you have 2 options,

1.      Investigate why your code execution is taking that much of time and optimize your code

2.      Increase the default timeout.

For first case you better know how to optimize the code.

How to modify the default timeout

Azure functions timeout value is stored and handled in host.json file and attribute name is functionTimeout

{

    "functionTimeout": "00:05:00"

}

 

functionTimeout indicated the timeout duration for all the functions and not for the single function.

You can update the default timeout value, save it, and test your function again.

In dedicated app service plan there is no limit but you should keep a fixed upper bound limit as unlimited timeout can have some disadvantages like your execution will keep executing and you will have to pay for it.

For unlimited timeout you can use -1

{

    "functionTimeout": "-1"

}

Important note

Regardless of the function app timeout setting, 230 seconds is the maximum amount of time that an HTTP triggered function can take to respond to a request. This is because of the default idle timeout of Azure Load Balancer. For longer processing times, consider using the Durable Functions async pattern or defer the actual work and return an immediate response.


Function timeout at function level

We know now that we can set function timeout in host.json but it is for all the function inside it. What about setting timeout for one or 2 function only.

While developing the functions from Visual Studio, you can now set the timeout at the function level.

Adding the attribute [Timeout("00:00:10")], above the function definition would set the timeout value for the function.  more details.

I did test the function executions to confirm that it doesn’t affect executions of other functions in the same function app.

With the test deployment I made – I deployed multiple function to the Function App on Azure, with only one of them (say function A) having the timeout set. While executing the functions, we see that A stops after the threshold timeout value and the others continue as expected.

Imp Note: This is for C# language only.

Azure Functions timeout


Output:

Azure functions timeout





Hope this helps. Please let me know if you have any query

References:

https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale

https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json#functiontimeout