How to work with Azure Functions in C#


Azure Features is the serverless compute providing within the Microsoft Azure cloud. Basically, “serverless” means you don’t even want a digital machine to run an Azure Perform. Azure Features are simply an implementation of platform as a service (PaaS), one that’s based mostly on an event-driven programming mannequin. This text presents an introduction to Azure Features, why they’re helpful, and the way we will work with them.

As there are not any servers that it’s important to handle, Azure Features can scale routinely, and also you pay just for the time your code runs. You possibly can leverage Azure Features for occasion processing in actual time, or for scheduled information processing jobs, similar to scheduled information backup or information clean-up. You possibly can even use Azure Features as serverless again ends to cell purposes.

Right here’s a fast look at among the placing options of Azure Features:

  • Versatile code deployment (by means of Azure Portal or GitHub, for instance)
  • Assist for a number of languages (C#, F#, Java, Node.js, or PHP)
  • Assist for exterior dependencies through NuGet or NPM
  • Simple integrations with different Azure companies

To work with the code examples supplied on this article, you must have Visible Studio 2022 put in in your system. For those who don’t have already got a replica, you’ll be able to obtain Visible Studio 2022 right here.

You also needs to have the newest model of Azure Perform Instruments and an lively Azure Subscription. Azure Perform Instruments are included as a part of the Azure improvement workload in Visible Studio 2022.

What are Azure Features? Why do we’d like them?

Azure Features are hosted companies on the Microsoft Azure cloud that execute code on demand, with out requiring the provisioning or administration of infrastructure. You write solely the code you want for the duty at hand, and Azure Features handles every part else.

An Azure Perform may be triggered by an occasion (an HTTP request) or on a schedule (utilizing a CRON expression). You possibly can shortly take a look at capabilities domestically as you write your capabilities earlier than deploying them to Azure.

Advantages and disadvantages of Azure Features

Lowered prices: Some of the compelling causes for utilizing Azure Features is that it dramatically reduces the price of operating purposes. You solely should pay for the assets you might have consumed, and no assets are consumed till your perform executes.

Flexibility: You possibly can create and deploy new event-driven capabilities shortly as your necessities change, and you’ll modify current capabilities as effectively.

Scalability: Azure Features gives scalability by enabling you to shortly spin up new situations of a perform when demand will increase. This eliminates the necessity for manually scaling situations up and down prematurely, a course of that, if demand spikes unpredictably or occasionally, turns into laborious and may show inefficient.

Triggers and bindings in Azure Features

Azure Features use triggers and, optionally, bindings. Triggers are user-defined capabilities that specify how an Azure Perform can be executed. A set off may be outlined by a code attribute and triggered by a queue message, a timer, an HTTP request, a blob, and many others.

Triggers have enter bindings that outline the information obtainable to the code throughout execution. The HTTP request physique is often handed as a JSON object to the Azure Perform’s enter parameter in an HTTP set off.

Binding is a option to join assets to an Azure Perform declaratively. There are two forms of bindings: enter and output. Whereas the previous permits information to be enter into the Azure Perform, the latter permits the Azure Perform to ship information to exterior assets. You possibly can have just one set off for an Azure Perform however a number of bindings.

Forms of triggers in Azure Features

The several types of triggers in Azure Features make it potential so that you can arrange a perform that runs when an replace to a useful resource takes place, similar to an occasion hub set off that sends an e mail alert each time your service is up to date.

HTTP set off: An HTTP set off makes use of an HTTP endpoint to name the perform through an HTTP request. You need to use HTTP triggers to create a serverless net software to obtain webhooks from different companies.

Timer set off: A Timer set off is named on a pre-defined schedule. This schedule may be expressed both in CRON syntax or utilizing intervals. The Timer set off is useful for scheduling any common job, similar to a clean-up job or a weekly e mail report.

Occasion Hubs set off: An Occasion Hubs set off responds to an Occasion Hubs stream message. When utilizing the EventHubTrigger attribute, you’ll be able to bind to the stream of messages from all partitions.

Blob Storage set off: A Blob set off responds to occasions in Azure Blob Storage. A Blob set off can begin an Azure Perform each time a brand new Blob is created or an current Blob is up to date.

Cosmos DB set off: A Cosmos DB set off responds to occasions generated by Azure Cosmos DB. For instance, if you’d like your Azure Perform to be executed when a brand new doc is created within the database, you’ll be able to create a Cosmos DB set off and add the required code to deal with the occasion.

Occasion Grid set off: An Occasion Grid set off responds to Azure Occasion Grid occasions. Occasion Grid is a serverless occasion routing service that means that you can create guidelines that route occasions from Azure companies similar to Blob storage, useful resource teams, and third-party assets, to any vacation spot supported by Occasion Grid.

Queue Storage set off: An Azure Queue Storage set off fires when messages are added to Azure Queue Storage. Azure Queue Storage gives dependable, asynchronous messaging between software parts.

Generic webhook: A webhook is analogous to a user-defined HTTP callback. It gives a light-weight option to be notified by one other service when some even happens. A generic webhook is one more class of set off that’s fired when an HTTP request originates from a service.

GitHub webhook: A GitHub webhook set off is executed when an occasion happens in your GitHub repository, similar to a brand new department is created, an current department is deleted, or code is dedicated or commented.

Service Bus set off: A Service Bus set off responds to messages from an Azure Service Bus queue or subject.

Create an Azure Features software mission in Visible Studio

First off, let’s create a .NET Azure Features software mission in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create an Azure Features mission.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “Azure Features” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window proven subsequent, specify the title and placement for the brand new mission.
  6. Click on Create.
  7. Within the “Create a brand new Azure Features software” display, choose the kind of set off you want to use on your Azure Perform.
  8. Click on Create.

It is best to now have a brand new .NET Azure Features software mission able to go in Visible Studio 2022. We’ll use this mission within the subsequent sections of this text.

Create a brand new Azure Perform

By default, an Azure Perform named Function1 can be created routinely inside a file named Function1.cs. Let’s change the default perform with the next code:

utilizing System;
utilizing System.IO;
utilizing System.Threading.Duties;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Azure.WebJobs.Extensions.Http;
utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.Extensions.Logging;
utilizing Newtonsoft.Json;
namespace Azure_FunctionAppDemo
{
    public static class Demo
    {
        [FunctionName("Demo")]
        public static async Activity<IActionResult> Run(
          [HttpTrigger(AuthorizationLevel.Function, "get",
          "post", Route = null)] HttpRequest request,
            ILogger logger)
        {
            logger.LogInformation("An HTTP triggered Azure Perform.");
            string requestBody = String.Empty;
            utilizing (StreamReader streamReader = new StreamReader(request.Physique))
            {
                requestBody = await streamReader.ReadToEndAsync();
            }
            return new OkObjectResult(!string.IsNullOrEmpty(requestBody));
        }
    }

Confer with the code itemizing above. An Azure Perform is represented by a static class having a static perform known as Run. On this instance, the title of the Azure Perform is Demo. The FunctionName attribute is used to point that the perform is an Azure Perform. Furthermore, it marks the Run methodology because the entry level. The perform title have to be distinctive inside a mission.

The 2 parameters of the Run methodology are of sort HttpRequest and ILogger. The primary parameter lets you work with the HttpRequest object (to retrieve request metadata, for instance). The second parameter lets you log information pertaining to your Azure Perform to a pre-defined log goal.

We all know that Azure Features are executed based mostly on pre-configured triggers. The utilization of the HttpTrigger attribute signifies that the Azure Perform named Demo can be based mostly on an Http set off. Determine 1 under reveals how one can choose the set off on your perform whenever you create your Azure Features software in Visible Studio.

azure functions 01 IDG

Determine 1. While you create a brand new Azure Features software in Visible Studio, you choose the kind of set off you wish to use on your Azure Perform.

Take a look at an Azure Perform domestically

Now that your Azure Perform is prepared, the following step is to run it. You need to use Azure Features Instruments to execute Azure Features domestically in your system. You possibly can simply press F5 to execute and take a look at your Azure Perform. Notice that if Azure Features Instruments shouldn’t be put in, you can be prompted to put in it whenever you attempt to run your perform. Simply settle for the request to obtain and set up the instruments when prompted.

If Azure Features Instruments are put in, the console window will show the URL of your Azure Perform as proven in Determine 2 under.

azure functions 02 IDG

Determine 2. Azure Features Instruments outputs the URL of HTTP-triggered capabilities.

Make an observation of the URL displayed on your Azure Perform. We’ll now reap the benefits of Postman, one of the vital common API testing instruments, to check the perform. While you execute the URL in Postman, you must see output just like that displayed in Determine 3 under.

azure functions 03 IDG

Determine 3: The Azure Perform in motion!

Publish an Azure Perform to Azure

Assuming that you simply’re logged in to Azure, observe the steps outlined under to publish the Azure Features software mission to Azure:

  1. Proper-click on the Azure Features software mission within the Answer Explorer window.
  2. Click on Publish.
  3. Choose Azure because the publish goal.
  4. Choose Azure Perform App (Home windows) as the precise goal.
  5. Click on Subsequent.
  6. Lastly, click on End to finish the method.
azure functions 02 IDG

Determine 4. You possibly can publish your Azure Features software to Microsoft Azure instantly from Visible Studio. Simply be sure to’re logged in to Azure.

You possibly can reap the benefits of Azure Features to implement serverless compute capabilities in Azure. The flexibility to run in a serverless atmosphere makes Azure Features extremely scalable and environment friendly. Azure Features are well-suited for scheduled duties, notifications, and light-weight APIs—any easy job that may be executed each time a specified occasion happens.

Azure Features may be invoked by an HTTP request, as proven right here, or by a webhook, or by an occasion in Azure Cosmos DB, Blob Storage, Cellular Apps, and plenty of different Azure companies. You possibly can even set off an Azure Perform from OneDrive, Excel, or Outlook. And you may retailer the information processed by Azure Features in an Azure storage service, a doc database, or perhaps a SQL database if you wish to.

Lastly, be aware that you need to use Azure Sturdy Features, an extension of Azure Features, to construct sturdy, stateful capabilities that run within the Azure cloud. We’ll check out working with Azure Sturdy Features in a later submit right here.

Copyright © 2022 IDG Communications, Inc.



Supply hyperlink

Leave a Reply

Your email address will not be published.