Azure Function with C#: A Comprehensive Guide

Azure Function with C#: A Comprehensive Guide

Azure Functions is a serverless computing service provided by Microsoft Azure that allows you to execute code in response to various triggers, without worrying about infrastructure management. This article walks through building an Azure Function using C#, with practical examples.

1. What is an Azure Function?

Azure Functions is a serverless compute service designed for event-driven applications. It allows developers to run code in response to:

• HTTP requests

• Timer schedules

• Queue messages

• Service Bus events

• Blob storage changes, etc.

2. Prerequisites

Before creating an Azure Function using C#, ensure you have:

Microsoft Azure Account.

Visual Studio (2022 or later) or Visual Studio Code with Azure Functions extensions.

Azure Functions Core Tools (for local testing).

.NET SDK installed.

3. Setting up the Azure Function App

1. Create an Azure Function project:

• Open Visual Studio and select Create a New Project.

• Choose Azure Functions and click Next.

• Configure your project name and location.

2. Select a trigger type:

• Select a trigger for your function (e.g., HTTP Trigger, Timer Trigger).

4. Writing the Azure Function in C#

Example 1: HTTP Trigger

This example demonstrates an HTTP-triggered Azure Function that accepts a name as input and returns a greeting.

Code:

using System.IO;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Logging;

using Newtonsoft.Json;

public static class HttpTriggeredFunction

{

[FunctionName("HttpTriggeredFunction")]

public static async Task<IActionResult> Run(

[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,

ILogger log)

{

log.LogInformation("HTTP trigger function processed a request.");

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

if (string.IsNullOrEmpty(name))

{

return new BadRequestObjectResult("Please provide a name in the query string or request body.");

}

return new OkObjectResult($"Hello, {name}! Welcome to Azure Functions with C#.");

}

}

Key Points:

• [FunctionName]: Marks the entry point of the function.

• [HttpTrigger]: Specifies the trigger type, methods, and authorization level.

Example 2: Timer Trigger

A Timer Trigger executes code on a predefined schedule. For instance, running a function every minute:

Code:

using System;

using Microsoft.Azure.WebJobs;

using Microsoft.Extensions.Logging;

public static class TimerTriggeredFunction

{

[FunctionName("TimerTriggeredFunction")]

public static void Run([TimerTrigger("0 /1 *")] TimerInfo myTimer, ILogger log)

{

log.LogInformation($"Timer function executed at: {DateTime.Now}");

}

}

Key Points:

• The cron expression "0 /1 *" indicates execution every minute.

• TimerInfo provides schedule details.

Example 3: Blob Trigger

A Blob Trigger executes when a blob is added or modified in Azure Blob Storage.

Code:

using System.IO;

using Microsoft.Azure.WebJobs;

using Microsoft.Extensions.Logging;

public static class BlobTriggeredFunction

{

[FunctionName("BlobTriggeredFunction")]

public static void Run(

[BlobTrigger("sample-container/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob,

string name,

ILogger log)

{

log.LogInformation($"Blob trigger function processed blob\n Name: {name} \n Size: {myBlob.Length} bytes");

}

}

Key Points:

• BlobTrigger listens to changes in the specified container.

• Replace "sample-container/{name}" with your container path.

5. Local Testing

1. Run your Azure Function locally using F5 in Visual Studio.

2. Use tools like Postman or curl to test HTTP-triggered functions.

3. Use Azure Storage Emulator or Azure Storage Account for Blob triggers.

6. Deploying to Azure

1. Publish from Visual Studio:

• Right-click your project and select Publish.

• Choose Azure and follow the deployment steps.

2. Deploy with Azure CLI:

• Use func azure functionapp publish <FunctionAppName> for deployment.

7. Monitoring and Scaling

Azure Functions provide built-in monitoring via Application Insights. Additionally, they automatically scale based on demand:

Consumption Plan: Auto-scales based on events.

Premium Plan: Scales with enhanced performance and VNET access.

Conclusion

Azure Functions with C# is a robust framework for building event-driven, scalable applications. Whether it’s HTTP, timer, or storage-based triggers, Azure Functions simplifies serverless development, allowing you to focus on writing efficient code.

By following this guide, you can start leveraging Azure Functions in your projects. Happy coding!

Did you find this article valuable?

Support DotNet-Development by becoming a sponsor. Any amount is appreciated!