Through Azure Functions, we can run piece of code which solves specific problems in the application. Azure Function is used in the same way like a class which requires input, executes the code, and provides the output. The difference between Azure Functions and App Services is that Azure Functions will be charged per second and when code is running only. Whereas Azure App Service will be charged hourly and even if there is no code running.
In this article, we discuss how to create Azure Function with simple example. For this, we will consider same example what we have in previous article, updating the blob file.
First, we need to create Function App. Go to Azure portal (https://portal.azure.com/). Select “Create a resource” and search for Function App.
Click on Create button. Enter all required details and “Review + create” button to review the details and create Function App.
We are creating function app TestFunctionExp under FunctionResourceGrp resource group. It takes couple of minutes to deploy the Function App. Once deployment completed, select “Go to resource” button.
Click on “New function” button, select “In-portal” and click on Continue. Here we are selecting “In-portal” because we are directly creating the function within the portal not from Visual Studio or any other tool.
Select “More templates” and click on “Finish and view templates” button.
Here select “Timer trigger”, enter function name (here we entered UpdateBlobFunction) and CRON expression as “*/5 * * * * *” to run the function for every 5 seconds.
Once it is created, it displays as shown below.
Let’s add our code from previous article in the Run method.
Save and run the function. We will get error as “The name 'CloudStorageAccount' does not exist in the current context”, because here we are using Microsoft.WindowsAzure.Storage assembly but we didn’t imported this dll into Function App.
Let’s import Microsoft.WindowsAzure.Storage.dll file into Function App. Go to Function App (here TestFunctionExp), select “Platform features” and select “Advanced tools (Kudu)”.
Kudo tool opens in new window. Select “PowerShell” option under “Debug console”.
Go to wwwroot folder and create new folder bin in wwwroot folder.
Drag and drop the Microsoft.WindowsAzure.Storage.dll into bin folder.
Now go back to your function “UpdateBlobFunction” and import the dll into your code as shown below.
Here we imported the dll using “#r "..\bin\Microsoft.WindowsAzure.Storage.dll"” command. Save and run the code, it should compile successfully and should update the blob file for every five seconds.