Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Starter-no-infra #85

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions .github/workflows/starter-no-infra_web-app-ace-project.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions

name: Build and deploy ASP.Net Core app to Azure Web App - web-app-ace-project

on:
push:
branches:
- starter-no-infra
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up .NET Core
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.x'

- name: Build with dotnet
run: dotnet build --configuration Release

- name: dotnet publish
run: dotnet publish -c Release -o ${{env.DOTNET_ROOT}}/myapp

- name: Install dotnet ef
run: dotnet tool install -g dotnet-ef --version 8.*

- name: Create migrations bundle
run: dotnet ef migrations bundle --runtime linux-x64 -o ${{env.DOTNET_ROOT}}/myapp/migrationsbundle

- name: Upload artifact for deployment job
uses: actions/upload-artifact@v4
with:
name: .net-app
path: ${{env.DOTNET_ROOT}}/myapp

deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: .net-app

- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_0E0274DEC4A44FCE9DA768225516B525 }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_83E53E57F21C46889E9D117FDB69DD7F }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_76FD69D8AE9E4688BA6D248363BB1EB0 }}

- name: Deploy to Azure Web App
id: deploy-to-webapp
uses: azure/webapps-deploy@v3
with:
app-name: 'web-app-ace-project'
slot-name: 'Production'
package: .

83 changes: 83 additions & 0 deletions AzureStorageService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using System.IO;
using System.Threading.Tasks;

public class AzureStorageService
{
private readonly string _connectionString;

public AzureStorageService(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("AzureStorage")
?? throw new ArgumentNullException(nameof(_connectionString), "Azure Storage connection string is not configured.");
}


public string GetBlobUrl(string containerName, string blobName)
{
var blobServiceClient = new BlobServiceClient(_connectionString);
var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = blobContainerClient.GetBlobClient(blobName);

return blobClient.Uri.ToString();
}
// Download a file from Azure Blob Storage
public async Task<Stream> DownloadFileAsync(string containerName, string blobName)
{
var blobServiceClient = new BlobServiceClient(_connectionString);
var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = blobContainerClient.GetBlobClient(blobName);

// Create a MemoryStream to store the downloaded content
var memoryStream = new MemoryStream();
await blobClient.DownloadToAsync(memoryStream);

// Reset the position of the MemoryStream before returning it
memoryStream.Position = 0;

return memoryStream;
}

// Upload a file to Azure Blob Storage
public async Task UploadFileAsync(string containerName, string blobName, Stream fileStream)
{
var blobServiceClient = new BlobServiceClient(_connectionString);
var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = blobContainerClient.GetBlobClient(blobName);

// Upload the file stream to the blob
await blobClient.UploadAsync(fileStream, overwrite: true);
}

public string GenerateBlobSasToken(string blobUrl, string storageAccountName, string storageAccountKey)
{
// Create a BlobServiceClient
var blobServiceClient = new BlobServiceClient(new Uri($"https://{storageAccountName}.blob.core.windows.net"),
new StorageSharedKeyCredential(storageAccountName, storageAccountKey));

// Get a reference to the blob
BlobClient blobClient = blobServiceClient.GetBlobContainerClient("background-images").GetBlobClient("background.jpg");

// Define SAS token permissions and expiry
BlobSasBuilder sasBuilder = new BlobSasBuilder
{
BlobContainerName = "background-images",
BlobName = "background.jpg",
Resource = "b", // "b" for blob, "c" for container
StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5),
ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) // Token validity
};

sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);

// Generate the SAS token
string sasToken = sasBuilder.ToSasQueryParameters(
new StorageSharedKeyCredential(storageAccountName, storageAccountKey))
.ToString();

// Combine the blob URL with the SAS token
return $"{blobClient.Uri}?{sasToken}";
}
}
37 changes: 37 additions & 0 deletions Controllers/FileController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.IO;

public class FileController : Controller
{
private readonly AzureStorageService _azureStorageService;

// Inject the AzureStorageService into the controller through constructor dependency injection
public FileController(AzureStorageService azureStorageService)
{
_azureStorageService = azureStorageService;
}

// An example action method to download a file from Azure Blob Storage
public async Task<IActionResult> Download(string containerName, string blobName)
{
// Call the AzureStorageService to download the file
var fileStream = await _azureStorageService.DownloadFileAsync(containerName, blobName);

// Return the file to the client as a downloadable stream
return File(fileStream, "application/octet-stream", blobName);
}

// An example action method to upload a file to Azure Blob Storage
[HttpPost]
public async Task<IActionResult> Upload(string containerName, string blobName)
{
// Get the uploaded file from the request (assuming a form post with a file)
using var fileStream = Request.Form.Files[0].OpenReadStream();

// Call the AzureStorageService to upload the file
await _azureStorageService.UploadFileAsync(containerName, blobName, fileStream);

return Ok("File uploaded successfully");
}
}
20 changes: 16 additions & 4 deletions Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
using System.Diagnostics;
using DotNetCoreSqlDb.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace DotNetCoreSqlDb.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly AzureStorageService _azureStorageService;

public HomeController(ILogger<HomeController> logger)
public HomeController(ILogger<HomeController> logger, AzureStorageService azureStorageService)
{
_logger = logger;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_azureStorageService = azureStorageService ?? throw new ArgumentNullException(nameof(azureStorageService));
}

public IActionResult Index()
{
string storageAccountName = "acewwwroot";
string storageAccountKey = "rANrk8t68qtk5ooKS4T+gRHGYHGdpFZRGUEz+iEWdVL5l3dwGgo8tAtSsxWPTGLBYqg9/Iz1g3L/+AStRxhgRw=="; // Get this securely from configuration
string blobUrl = "https://acewwwroot.blob.core.windows.net/background-images/background.jpg";

// Generate SAS token URL
string sasUrl = _azureStorageService.GenerateBlobSasToken(blobUrl, storageAccountName, storageAccountKey);

ViewData["BackgroundUrl"] = sasUrl;
return View();
}

Expand All @@ -26,7 +36,9 @@ public IActionResult Privacy()
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
// Using Activity to get the request ID
var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
return View(new ErrorViewModel { RequestId = requestId });
}
}
}
2 changes: 2 additions & 0 deletions DotNetCoreSqlDb.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<ItemGroup>
<!-- include the migrationsbundle file generated by the prepackage hook (see azure.yaml) -->
<Content Include="migrationsbundle" CopyToPublishDirectory="PreserveNewest" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.23.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">
<PrivateAssets>all</PrivateAssets>
Expand All @@ -18,6 +19,7 @@
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="8.0.6" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.2" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="9.0.0" />
</ItemGroup>

</Project>
49 changes: 49 additions & 0 deletions Migrations/20241124175301_AddTodoTable.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions Migrations/20241124175301_AddTodoTable.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace DotNetCoreSqlDb.Migrations
{
/// <inheritdoc />
public partial class AddTodoTable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{

}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{

}
}
}
Loading