How to work with Azure Functions in C#

Take advantage of Azure Functions to run small pieces of code that can be triggered by events in the Azure cloud

How to work with Azure Functions in C#
Thinkstock

Azure Functions is the serverless compute offering in the Microsoft Azure cloud. Essentially, you don’t even need a virtual machine (VM) to run an Azure Function. Azure Functions are just an implementation of platform as a service (PaaS), one that is based on an event-driven programming model. This article presents an introduction to Azure Functions, why they are useful, and how we can work with them.

As there are no servers that you have to manage, Azure Functions can scale automatically, and you pay only for the time your code runs. You can leverage Azure Functions for event processing in real time, or for scheduled data processing jobs, such as scheduled data backup or data clean-up. You can even use Azure Functions as serverless back ends to mobile applications.

Here’s a quick glance at some of the striking features of Azure Functions:

  • Flexible code deployment (through Azure Portal or GitHub, for example)
  • Support for multiple languages (C#, F#, Java, Node.js, or PHP)
  • Support for external dependencies via NuGet or NPM
  • Easy integrations with other Azure services

Get started with Azure Functions

In this section we will learn how we can build Azure functions using Visual Studio 2017. To build, test, and deploy Azure Functions, you need Azure Function Tools for Visual Studio 2017. Note that you should ensure that your Visual Studio has all the latest updates applied and that you are using the most recent version of the Azure Functions Tools. Azure Functions Tools is included as part of the Azure development workload of Visual Studio 2017 version 15.5 and onwards.

Assuming that you’re running Visual Studio 2017 version 15.3 or later in your system, follow the steps outlined below to create an Azure Functions Project in Visual Studio 2017.

  1. Open the Visual Studio IDE
  2. Click on File > New > Project (alternatively, you can press the Ctrl-Shift-N keys together to bring up the New Project Window in your Visual Studio IDE)
  3. Select Visual C#
  4. Click on Cloud
  5. Select Azure Functions
  6. Specify a name for your project
  7. Click OK
  8. In the next window, select “Azure Functions v1 (.NET Framework) from the drop-down control
  9. Select the HTTP trigger and choose “Storage Emulator” as the storage account
  10. Select “Anonymous” as the access rights
  11. Click OK

Build a simple Azure Function in C#

Here is what a typical Azure Function looks like. Note the usage of the static keyword.

[FunctionName(“WriteYourFunctionNameHere”)]
        public static void Run([QueueTrigger(“WriteYourQueueNameHere”)] string item, TraceWriter traceWriter)
        {
            //Write your code here.
        }

Note the usage of the [FunctionName] attribute above the Run method. This is our Azure Function – a static method that is available as part of a static class. We will get back to this later.

Now here is an example of a custom Azure Function – a simple one.

[FunctionName(“DemoFunctions”)]
        public static async Task<HttpResponseMessage> Run
            ([HttpTrigger(AuthorizationLevel.Function)]HttpRequestMessage request, TraceWriter traceWriter)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add(“A001”, “Joydip Kanjilal”);
            dictionary.Add(“A002”, “Steve Jones”);
            string key = request.GetQueryNameValuePairs().FirstOrDefault(k => string.Compare(k.Key, “Key”, true) == 0).Value;
            return key == null
                ? request.CreateResponse(HttpStatusCode.BadRequest, “Invalid key specified.”)
                : request.CreateResponse(HttpStatusCode.OK, “Hello “ + dictionary[key]);
        }

In the above example, a Dictionary of string objects is created that stores the author code and names as key-value pairs. If the key that is passed in the query string matches any of the keys in the Dictionary, the author name is returned. If the key specified in the query string is not present in the Dictionary, then the function returns HttpStatusCode 400, i.e. BadRequest.

Test an Azure Function locally

Now that your Azure Function is ready, the next step is to run it. You can take use Azure Functions Core Tools to execute Azure Functions locally in your system. You can just press F5 to execute and test your Azure Function. Note that if Azure Functions Core Tools is not installed, you will be prompted to install it when you try to run your function. Just accept the request to download and install the tools when prompted.

From the Azure Functions runtime output window, copy the provided URL, paste it into your browser’s address bar, and hit Enter. You should specify the key as a query string as shown here:

http://localhost:7071/api/DemoFunctions?Key=A001

And that’s all you have to do. If the key specified is available in the Dictionary, the corresponding name will be displayed in your web browser.

Azure Functions are a great way to write small and simple pieces of code that can be executed whenever a specified event occurs. A trigger can be invoked by an HTTP request, as shown here, or a webhook, or an event in Azure Cosmos DB, Blob Storage, Mobile Apps, and many other Azure services. You can even trigger an Azure Function from OneDrive, Excel, or Outlook. And you can store the data processed by such functions in an Azure storage service, a document database, or even a SQL database if you want to.

Copyright © 2018 IDG Communications, Inc.