Introduction to Azure with .NET Examples

Adrián Bailador - Jun 26 - - Dev Community

Microsoft Azure is Microsoft's cloud platform offering powerful tools for developers and businesses to efficiently and securely build, deploy, and manage applications. In this article, we'll explore some key Azure services and provide practical .NET examples to illustrate their use.

Discovering Azure

What is Azure?

Azure is Microsoft's cloud service platform that provides solutions for computing, storage, networking, databases, artificial intelligence, and more. Designed with robust global infrastructure, it enables organizations to scale their applications globally with high availability and security.

Benefits of Using Azure

  1. Scalability: Allows adjusting resources and applications as per changing needs.
  2. High Availability: Offers built-in redundancy globally.
  3. Advanced Security: Complies with strict security standards and regulatory requirements.
  4. Integration with Microsoft Products: Seamlessly integrates with other Microsoft tools and services like Office 365 and Dynamics 365.

Exploring Serverless with Azure Functions

What are Azure Functions?

Azure Functions is a serverless computing service that allows running code snippets in response to events without worrying about underlying infrastructure. Ideal for tasks like data processing, system integrations, and workflow automation.

Practical .NET Example with Azure Functions

Let's create a simple function that responds to HTTP requests with a personalized greeting.

Create an Azure Functions Project in Visual Studio

  1. Open Visual Studio and select "Create a new project". Search for "Azure Functions" and choose "Azure Functions v2 (.NET Core)". Click "Next".

  2. Configure the HTTP trigger by selecting "HTTP trigger" and naming the function HttpTriggerFunction. Set the authorization level to "Function".

Implementing the Function

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

public static class HttpTriggerFunction
{
    [FunctionName("HttpTriggerFunction")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Request received.");

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

        if (string.IsNullOrEmpty(name))
        {
            return new BadRequestObjectResult("Please provide a name in the query string.");
        }

        return new OkObjectResult($"Welcome, {name}!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • HttpTrigger: Defines that the function responds to HTTP requests.
  • ILogger: Logs information about the function execution.
  • HttpRequest: Represents the incoming HTTP request.
  • IActionResult: Returns the function's result as an HTTP response.

Publishing to Azure

Right-click on the project and select "Publish". Follow the instructions to configure your Azure account and deploy the function to your resource group.

Testing the Function on Azure

Use tools like Postman or Curl to send an HTTP request:

curl -X GET "https://<your-azure-function>.azurewebsites.net/api/HttpTriggerFunction?name=Codu"
Enter fullscreen mode Exit fullscreen mode

You should receive the response:

Welcome, Codu!
Enter fullscreen mode Exit fullscreen mode

Data Storage with Azure Blob Storage

What is Azure Blob Storage?

Azure Blob Storage provides scalable and secure cloud storage for unstructured data such as files and media. Essential for storing and accessing large volumes of information globally.

.NET Example Usage with Azure Blob Storage

Let's upload a file to Azure Blob Storage using .NET.

Environment Setup

  1. Install the Azure.Storage.Blobs NuGet package:
   Install-Package Azure.Storage.Blobs
Enter fullscreen mode Exit fullscreen mode
  1. Configure your Azure storage account and obtain the connection string from the portal.

Implementation for Uploading a File

using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Threading.Tasks;

public class BlobStorageExample
{
    private const string connectionString = "YourAzureStorageConnectionString";
    private const string containerName = "example-container";
    private const string blobName = "example-blob.txt";
    private const string localFilePath = "path/to/your/file.txt";

    public static async Task UploadBlobAsync()
    {
        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        await containerClient.CreateIfNotExistsAsync();

        BlobClient blobClient = containerClient.GetBlobClient(blobName);

        using FileStream uploadFileStream = File.OpenRead(localFilePath);
        await blobClient.UploadAsync(uploadFileStream, true);
        uploadFileStream.Close();

        Console.WriteLine($"File uploaded to {blobClient.Uri}");
    }

    public static void Main(string[] args)
    {
        UploadBlobAsync().GetAwaiter().GetResult();
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • BlobServiceClient: Interacts with the Azure Blob service.
  • BlobContainerClient: Provides access to a specific Blob Storage container.
  • BlobClient: Facilitates manipulation of individual blobs within a container.
  • UploadAsync: Method for uploading a file to the blob.

Verifying the File in Azure Blob Storage

To verify that the file has been successfully uploaded, access the Azure portal, navigate to your storage account, and look for the example-container container. You should find example-blob.txt inside. Additionally, you can list blobs in the container with additional code to confirm the operation.

public static async Task ListBlobsAsync()
{
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

    await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
    {
        Console.WriteLine($"Blob name: {blobItem.Name}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Azure provides powerful tools for developers and businesses looking to innovate in the cloud. From Azure Functions for serverless code execution to Azure Blob Storage for scalable data storage and management, these solutions enable building robust and flexible applications.

For more details and resources, visit the Azure official documentation.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .