30 April 2024

Azure Blob Storage

 Azure Blob Storage

Azure Blob Storage is a service from Microsoft Azure that allows you to store large amounts of unstructured data, such as text or binary data, which is accessible from anywhere in the world via HTTP or HTTPS. Integrating Azure Blob Storage with a Web API in C# involves several steps. Here, I’ll guide you through creating a simple Web API that can upload files to Azure Blob Storage, list blobs in a container, and download blobs.


### Step 1: Create an Azure Blob Storage Account
First, you need to create an Azure Storage account through the Azure portal. Once created, obtain the access keys and connection string from the portal, as these will be needed to access your Blob Storage from the API.

### Step 2: Set Up Your Web API Project
1. **Create a new ASP.NET Core Web API project** in Visual Studio.
2. **Install the Azure Storage SDK** by running the following NuGet command:

   ```bash
   Install-Package Azure.Storage.Blobs
   ```

### Step 3: Configure the Storage Connection
Add your storage connection string to the `appsettings.json` file:

```json
{
  "AzureStorageConfig": {
    "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey;EndpointSuffix=core.windows.net"
  }
}
```

### Step 4: Create the Blob Service Client
Create a service class that will handle operations related to Blob storage:

```csharp
using Azure.Storage.Blobs;
using Microsoft.Extensions.Configuration;

public class BlobService
{
    private readonly BlobServiceClient _blobServiceClient;

    public BlobService(IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("AzureStorageConfig");
        _blobServiceClient = new BlobServiceClient(connectionString);
    }

    public async Task UploadFileBlobAsync(string blobContainerName, Stream content, string contentType, string fileName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        await containerClient.CreateIfNotExistsAsync();
        var blobClient = containerClient.GetBlobClient(fileName);
        await blobClient.UploadAsync(content, new Azure.Storage.Blobs.Models.BlobHttpHeaders { ContentType = contentType });
    }

    public async Task<IEnumerable<string>> ListBlobsAsync(string blobContainerName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        var blobs = new List<string>();

        await foreach (var blobItem in containerClient.GetBlobsAsync())
        {
            blobs.Add(blobItem.Name);
        }

        return blobs;
    }

    public async Task<Stream> GetBlobAsync(string blobContainerName, string blobName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        var blobClient = containerClient.GetBlobClient(blobName);
        var downloadInfo = await blobClient.DownloadAsync();

        return downloadInfo.Value.Content;
    }
}
```

### Step 5: Expose API Endpoints
Modify the `Controllers` to use `BlobService`:

```csharp
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class BlobController : ControllerBase
{
    private readonly BlobService _blobService;

    public BlobController(BlobService blobService)
    {
        _blobService = blobService;
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile([FromForm]IFormFile file)
    {
        using (var stream = file.OpenReadStream())
        {
            await _blobService.UploadFileBlobAsync("your-container-name", stream, file.ContentType, file.FileName);
        }
        return Ok();
    }

    [HttpGet("list")]
    public async Task<IActionResult> ListBlobs()
    {
        var blobs = await _blobService.ListBlobsAsync("your-container-name");
        return Ok(blobs);
    }

    [HttpGet("download/{blobName}")]
    public async Task<IActionResult> DownloadBlob(string blobName)
    {
        var stream = await _blobService.GetBlobAsync("your-container-name", blobName);
        return File(stream, "application/octet-stream", blobName);
    }
}
```

### Step 6: Register BlobService in Startup.cs
In `Startup.cs`, add:

```csharp
services.AddSingleton<BlobService>();

Troubleshooting App Service

 Troubleshooting App Service

You can achieve in three ways

1. Activity Logs

2. Diagnose and solve problems

3. Application insights

CICD Pipeline

 CICD Pipeline

CI can be considered as the first stage in producing and delivering code, and CD as the second. CI focuses on preparing code for release (build/test), whereas CD involves the actual release of code (release/deploy).


  1. Create a build pipeline
  2. Build, Test, Publish and Publish Artifacts
  3. Azure Release pipeline

Publish Artifacts meaning - 

 Azure Artifacts enable developers to store and manage their packages and control who they want to share it with.

https://www.youtube.com/watch?v=eOQL0nXQlLs
In this Azure DevOps CI/CD Pipelines Tutorial video, we will show you building a CI/CD pipeline in Azure DevOps for ASP.NET Core applications. We will introduce you to Azure DevOps CI/CD Pipeline and show you how to set up a CI/CD pipeline using Azure. If you're working on an ASP.NET Core application, then you know that it's important to have a ...
www.youtube.com

Continuous Delivery - Manual Trigger

Continuous Deployment - Continuous Deployment

HTML Helpers in MVC

 HTML Helpers in MVC

@Html.TextBox
@Html.Password
@Html.TextArea
@Html.CheckBox
@Html.RadioButton
@Html.DropDownList
@Html.ListBox
@Html.Hidden
@Html.Display
@Html.Editor
@Html.ActionLink
@Html.BeginForm
@Html.Label

Example of TextBox() in Razor view
@Html.TextBox("txtEmplpyeeName", "", new { @class = "form-control" })

Html Result

<input class="form-control" id="txtUserName" name="txtEmplpyeeName" type="text" value=""> 

Convert DataTable to List In C#

 Convert DataTable to List In C#

You can achieve in below three ways

Using a Loop.
Using LINQ.
Using a Generic Method.

Using Linq
List<Student> studentList = new List<Student>();
    studentList = (from DataRow dr in dt.Rows
            select new Student()
            {
                StudentId = Convert .ToInt32 (dr["StudentId"]),
                StudentName = dr["StudentName"].ToString(),
                Address = dr["Address"].ToString(),
                MobileNo = dr["MobileNo"].ToString()
            }).ToList();

Eager Loading, Lazy Loading

Eager Loading, Lazy Loading

Eager Loading helps you to load all your needed entities at once; i.e., all your child entities will be loaded at single database call. This can be achieved, using the Include method, which returs the related entities as a part of the query and a large amount of data is loaded at once.

User usr = dbContext.Users.Include(=> a.UserDetails).FirstOrDefault(=> a.UserId == userId);

Lazy Loading
It is the default behavior of an Entity Framework, where a child entity is loaded only when it is accessed for the first time. It simply delays the loading of the related data, until you ask for it.

User usr = dbContext.Users.FirstOrDefault(=> a.UserId == userId);

Kestrel Server in Dotnet

 Kestrel Server in Dotnet

Kestrel is a cross-platform web server for ASP.NET Core. Kestrel is the recommended server for ASP.NET Core, and it's configured by default in ASP.NET Core project templates.  

ASP.NET Core project templates use Kestrel by default when not hosted with IIS. In the following template-generated Program.cs, the WebApplication.CreateBuilder method calls UseKestrel internally:

var builder = WebApplication.CreateBuilder(args);

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...