Skip to content

Commit

Permalink
Azure blob storage for saving files. Make a basic skeleton #10
Browse files Browse the repository at this point in the history
  • Loading branch information
hyunbin7303 committed Mar 1, 2021
1 parent 4c6eec3 commit aac163e
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 26 deletions.
3 changes: 0 additions & 3 deletions ECommerceService/ECommerce.AzureStorage/AzureBlobManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ namespace ECommerce.AzureStorage
{
public class MyFileContainer
{

}

public class AzureBlobManager
{
static public string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
Expand All @@ -34,7 +32,6 @@ static public async void UploadFile(string fileName)
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

}
static public void GetBlobItemsFromContainer(string containerName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace ECommerce.AzureStorage
public class GetBlobRequestDTO
{
[Required]
public string Name { get; private set; }
public string Name { get; set; }

public override string ToString()
{
Expand Down
1 change: 0 additions & 1 deletion ECommerceService/ECommerce.AzureStorage/IImageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ namespace ECommerce.AzureStorage
public interface IImageService
{
Task AddImageToBlobStorageAsync(BlobDTO image);
Task<BlobDTO> GetBlobAsync(GetBlobRequestDTO input);
void DeleteContainer(string containerName);
Task<Entity> GetEntityBlobAsync<Entity>(BlobClient blobJson) where Entity : class, new();
}
Expand Down
70 changes: 57 additions & 13 deletions ECommerceService/ECommerce.AzureStorage/ImageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Azure.Storage.Blobs.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -11,20 +12,62 @@ namespace ECommerce.AzureStorage
{
public class ImageService : IImageService
{
//Source
// https://www.wintellect.com/azure-bits-2-saving-the-image-to-azure-blob-storage/
//https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-container-create?tabs=dotnet

private readonly string _imageRootPath;
private readonly string _container;
private static readonly string _container = "kp-container-";
private readonly string _blobStorageConn;
public ImageService(string containerName, string connectionString = null, string imageRootPath = null)
private BlobServiceClient blobServiceClient = null;
public ImageService(string connectionString = null, string imageRootPath = null)
{
_imageRootPath = imageRootPath ?? "C:\\Users\\Hyunbin\\Desktop\\";
_blobStorageConn = connectionString ?? Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
_container = containerName;
if(_blobStorageConn != null)
{
blobServiceClient = new BlobServiceClient(_blobStorageConn);
}
}
public Task AddImageToBlobStorageAsync(BlobDTO image)
{
throw new NotImplementedException();
}

public async Task BlobDownloadInfoTestAsync(BlobClient blobClient, string filePath)
{
// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension
// so you can compare the files in the data directory
string downloadFilePath = filePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();
using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
await download.Content.CopyToAsync(downloadFileStream);
downloadFileStream.Close();
}
}
public static Task<BlobContainerClient> CreateContainerAsync(BlobServiceClient blobServiceClient, string containerName)
{
var newContainerName = _container + containerName;
try
{
BlobContainerClient container = blobServiceClient.CreateBlobContainer(containerName);
if( container.Exists())
{
return Task.FromResult(container);
}
}
catch(RequestFailedException e)
{
// TODO: Logging in here.
Console.WriteLine("HTTP error code {0}: {1}", e.Status, e.ErrorCode);
Console.WriteLine(e.Message);
}
return null;
}
public void DeleteContainer(string containerName)
{
// Try to delete a container and avoid any potential race conditions that might arise by checking if the container is already deleted or is in the process of being deleted.
Expand All @@ -40,22 +83,23 @@ public void DeleteContainer(string containerName)
// Ignore any errors if the container being deleted or if it has already been deleted
}
}

public Task<BlobDTO> GetBlobAsync(GetBlobRequestDTO input)
public Task<BlobItem> GetBlobAsync(GetBlobRequestDTO input)
{
// var blob = await _fileContainer.getAllBytesAsync(input.Name);
BlobServiceClient blobServiceClient = new BlobServiceClient(_blobStorageConn);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_container);
var blobs = containerClient.GetBlobs();
foreach(BlobItem b in blobs)
{
if(b.Name == input.Name)
{
return Task.FromResult(b);
}
}
return null;
}
public void GetBlobItemsFromContainer(string containerName)
public IEnumerator<BlobItem> GetBlobItemsFromContainer(string containerName)
{
BlobServiceClient blobServiceClient = new BlobServiceClient(_blobStorageConn);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
foreach (BlobItem blobItem in containerClient.GetBlobs())
{
Console.WriteLine("\t" + blobItem.Name);
}
return containerClient.GetBlobs().GetEnumerator();
}
public async Task<Entity> GetEntityBlobAsync<Entity>(BlobClient blobJson) where Entity : class, new()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class GenericRepository<T> : IGenericRepository<T> where T : class
internal DbSet<T> dbSet = null;
public GenericRepository(MainEcommerceDBContext context)
{
this.context = context;
this.context = context ?? throw new ArgumentNullException(nameof(context));
this.dbSet = context.Set<T>();
}
public void Delete(object id)
Expand All @@ -22,9 +22,11 @@ public void Delete(object id)
if (existing == null)
{
throw new ArgumentException(" object doesn't exist.");
return;
}
dbSet.Remove(existing);
else
{
dbSet.Remove(existing);
}
}
public virtual void Delete(T entity)
{
Expand Down Expand Up @@ -86,7 +88,6 @@ public virtual void Update(T obj)
dbSet.Attach(obj);
context.Entry(obj).State = EntityState.Modified;
}

public bool TryGetObject(object id, out object obj)
{
throw new NotImplementedException();
Expand Down
38 changes: 35 additions & 3 deletions ECommerceService/ECommerceService.Test/AzureTest.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
using NUnit.Framework;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using ECommerce.AzureStorage;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ECommerceService.Test
{
Expand All @@ -12,9 +16,37 @@ public void Setup()
{
}
[Test]
public void Test1()
public void GetBlobItemsFromContainer_NullCheck()
{
Assert.Pass();
ImageService imageService = new ImageService();
var check = imageService.GetBlobItemsFromContainer("kp-container");
//foreach (BlobItem blobItem in check)
// Console.WriteLine("\t" + blobItem.Name);
Assert.IsNotNull(check);
}

[Test]
public void GetBlobAsync_FindExistingFileInBlobContainer()
{
ImageService service = new ImageService();
var check = service.GetBlobAsync(new GetBlobRequestDTO{ Name = "KevinPark_Resume.pdf"});
Assert.IsNotNull(check);
}

[Test]
public void CreateContainerAsync_CreateValidContainer()
{
var connStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
BlobServiceClient client = new BlobServiceClient(connStr);
var check = ImageService.CreateContainerAsync(client, "test");
Assert.AreEqual(TaskStatus.RanToCompletion, check.Status);
}

[Test]
public void DeleteContainer_ReturnTrueIfSuccess()
{
ImageService service = new ImageService("kp-container");

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ECommerce.AzureStorage\ECommerce.AzureStorage.csproj" />
</ItemGroup>

</Project>

0 comments on commit aac163e

Please sign in to comment.