Skip to content

Commit e48ab0e

Browse files
Merge pull request #7 from Azure-Samples/sow-dev
Merge sow-dev
2 parents 688efa4 + 64c7d92 commit e48ab0e

File tree

2 files changed

+111
-103
lines changed

2 files changed

+111
-103
lines changed

ImageResizeWebApp/ImageResizeWebApp/Controllers/ImagesController.cs

Lines changed: 46 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -22,31 +22,39 @@ namespace ImageResizeWebApp.Controllers
2222
public class ImagesController : Controller
2323
{
2424
// make sure that appsettings.json is filled with the necessary details of the azure storage
25-
private readonly AzureStorageConfig _storageConfig;
25+
private readonly AzureStorageConfig storageConfig = null;
2626

2727
public ImagesController(IOptions<AzureStorageConfig> config)
2828
{
29-
_storageConfig = config.Value;
29+
storageConfig = config.Value;
3030
}
3131

3232
// POST /api/images/upload
3333
[HttpPost("[action]")]
3434
public async Task<IActionResult> Upload(ICollection<IFormFile> files)
3535
{
36-
string uploadedfileName = string.Empty;
36+
bool isUploaded = false;
37+
3738
bool isQueued = false;
39+
3840
try
39-
{
40-
41+
{
42+
4143
if (files.Count == 0)
44+
4245
return BadRequest("No files received from the upload");
4346

44-
if(_storageConfig.AccountKey == string.Empty || _storageConfig.AccountName == string.Empty)
47+
if (storageConfig.AccountKey == string.Empty || storageConfig.AccountName == string.Empty)
48+
4549
return BadRequest("sorry, can't retrieve your azure storage details from appsettings.js, make sure that you add azure storage details there");
4650

47-
if (_storageConfig.ImageContainer == string.Empty)
51+
if (storageConfig.ImageContainer == string.Empty)
52+
4853
return BadRequest("Please provide a name for your image container in the azure blob storage");
4954

55+
if (storageConfig.QueueName == string.Empty)
56+
57+
return BadRequest("Please provide a name for storage queue");
5058

5159
foreach (var formFile in files)
5260
{
@@ -56,29 +64,37 @@ public async Task<IActionResult> Upload(ICollection<IFormFile> files)
5664
{
5765
using (Stream stream = formFile.OpenReadStream())
5866
{
59-
uploadedfileName = await StorageHelper.UploadFileToStorage(stream, formFile.FileName,_storageConfig);
67+
isUploaded = await StorageHelper.UploadFileToStorage(stream, formFile.FileName, storageConfig);
6068
}
6169

62-
if (uploadedfileName != string.Empty)
70+
if (isUploaded)
6371
{
64-
isQueued = await StorageHelper.CreateQueueItem(uploadedfileName, _storageConfig);
72+
isQueued = await StorageHelper.CreateQueueItem(formFile.FileName, storageConfig);
73+
}
74+
else
75+
{
76+
return BadRequest("There is something went wrong while uploading the image");
6577
}
6678
}
6779
}
6880
else
6981
{
70-
return new UnsupportedMediaTypeResult();
71-
}
82+
return new UnsupportedMediaTypeResult();
83+
}
7284
}
7385

74-
if (uploadedfileName != string.Empty)
86+
if (isUploaded)
7587
{
76-
if(_storageConfig.ThumbnailContainer != string.Empty)
88+
if (storageConfig.ThumbnailContainer != string.Empty)
89+
7790
return new AcceptedAtActionResult("GetThumbNails", "Images", null, null);
91+
7892
else
93+
7994
return new AcceptedResult();
80-
}
95+
}
8196
else
97+
8298
return BadRequest("Look like the image couldnt upload to the storage");
8399

84100

@@ -91,26 +107,29 @@ public async Task<IActionResult> Upload(ICollection<IFormFile> files)
91107

92108
// GET /api/images/thumbnails
93109
[HttpGet("thumbnails")]
94-
public async Task<IActionResult> GetThumbNails(string containerName)
110+
public async Task<IActionResult> GetThumbNails()
95111
{
96-
112+
97113
try
98114
{
99-
if (_storageConfig != null)
100-
{
101-
List<string> thumbnailUrls = await StorageHelper.GetThumbNailUrls(_storageConfig);
102-
return new ObjectResult(thumbnailUrls);
103-
}
104-
else
105-
{
106-
return BadRequest("sorry, can't retrieve your azure storage details from appsettings.js");
107-
}
115+
if (storageConfig.AccountKey == string.Empty || storageConfig.AccountName == string.Empty)
116+
117+
return BadRequest("sorry, can't retrieve your azure storage details from appsettings.js, make sure that you add azure storage details there");
118+
119+
if (storageConfig.ImageContainer == string.Empty)
120+
121+
return BadRequest("Please provide a name for your image container in the azure blob storage");
122+
123+
List<string> thumbnailUrls = await StorageHelper.GetThumbNailUrls(storageConfig);
124+
125+
return new ObjectResult(thumbnailUrls);
126+
108127
}
109128
catch (Exception ex)
110129
{
111130
return BadRequest(ex.Message);
112131
}
113-
132+
114133
}
115134

116135
}

ImageResizeWebApp/ImageResizeWebApp/Helpers/StorageHelper.cs

Lines changed: 65 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -22,120 +22,109 @@ public static bool IsImage(IFormFile file)
2222
return true;
2323
}
2424

25-
string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...
25+
string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" };
2626

27-
// linq from Henrik Stenbæk
2827
return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
2928
}
30-
public static async Task<string> UploadFileToStorage(Stream fileStream, string fileName, AzureStorageConfig _storageConfig)
31-
{
32-
string containerName = Guid.NewGuid().ToString().ToLower();
33-
34-
if (_storageConfig != null)
35-
{
36-
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
3729

38-
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
39-
40-
if (storageAccount != null)
41-
{
42-
// Create the blob client.
43-
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
30+
public static async Task<bool> UploadFileToStorage(Stream fileStream, string fileName, AzureStorageConfig _storageConfig)
31+
{
32+
// Create storagecredentials object by reading the values from the configuration (appsettings.json)
33+
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
4434

45-
CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);
35+
// Create cloudstorage account by passing the storagecredentials
36+
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
4637

47-
await container.CreateIfNotExistsAsync();
38+
// Create the blob client.
39+
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
4840

49-
// Retrieve reference to a blob named "myblob".
50-
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
41+
// Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
42+
CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);
5143

52-
await blockBlob.UploadFromStreamAsync(fileStream);
44+
// Create the container if not already exist
45+
await container.CreateIfNotExistsAsync();
5346

54-
return await Task.FromResult(fileName);
55-
}
47+
// Get the reference to the block blob from the container
48+
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
5649

57-
}
50+
// Upload the file
51+
await blockBlob.UploadFromStreamAsync(fileStream);
5852

59-
return await Task.FromResult(string.Empty);
53+
return await Task.FromResult(true);
6054
}
55+
6156
public static async Task<bool> CreateQueueItem(string imageInfo, AzureStorageConfig _storageConfig)
6257
{
63-
if (_storageConfig != null)
64-
{
65-
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
58+
// Create storagecredentials object by reading the values from the configuration (appsettings.json)
59+
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
6660

67-
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
61+
// Create cloudstorage account by passing the storagecredentials
62+
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
6863

69-
if (storageAccount != null && imageInfo != string.Empty)
70-
{
71-
// Create the queue client.
72-
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
64+
// Create the queue client.
65+
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
7366

74-
// Retrieve a reference to a queue.
75-
CloudQueue queue = queueClient.GetQueueReference(_storageConfig.QueueName);
67+
// Retrieve a reference to a queue.
68+
CloudQueue queue = queueClient.GetQueueReference(_storageConfig.QueueName);
7669

77-
// Create the queue if it doesn't already exist.
78-
await queue.CreateIfNotExistsAsync();
70+
// Create the queue if it doesn't already exist.
71+
await queue.CreateIfNotExistsAsync();
7972

80-
// Create a message and add it to the queue.
81-
CloudQueueMessage message = new CloudQueueMessage(imageInfo);
73+
// Create a message and add it to the queue.
74+
CloudQueueMessage message = new CloudQueueMessage(imageInfo);
8275

83-
await queue.AddMessageAsync(message);
76+
// Add a message to the queue
77+
await queue.AddMessageAsync(message);
8478

85-
return await Task.FromResult(true);
86-
}
87-
88-
}
89-
return await Task.FromResult(false);
79+
return await Task.FromResult(true);
9080
}
81+
9182
public static async Task<List<string>> GetThumbNailUrls(AzureStorageConfig _storageConfig)
9283
{
9384
List<string> thumbnailUrls = new List<string>();
94-
try
95-
{
96-
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
9785

98-
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
86+
// Create storagecredentials object by reading the values from the configuration (appsettings.json)
87+
StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);
9988

100-
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
89+
// Create cloudstorage account by passing the storagecredentials
90+
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
10191

102-
CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ThumbnailContainer);
103-
104-
await container.CreateIfNotExistsAsync();
92+
// Create blob client
93+
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
10594

106-
await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
95+
// Get reference to the container
96+
CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ThumbnailContainer);
10797

108-
// Loop over items within the container and output the length and URI.
109-
int i = 0;
98+
// Create the container if it is not exists
99+
await container.CreateIfNotExistsAsync();
110100

111-
BlobContinuationToken continuationToken = null;
101+
// Set the permission of the container to public
102+
await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
112103

113-
BlobResultSegment resultSegment = null;
104+
BlobContinuationToken continuationToken = null;
114105

115-
//Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
116-
//When the continuation token is null, the last page has been returned and execution can exit the loop.
117-
do
118-
{
119-
//This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter,
120-
//or by calling a different overload.
121-
resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);
106+
BlobResultSegment resultSegment = null;
122107

123-
foreach (var blobItem in resultSegment.Results)
124-
{
125-
thumbnailUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
126-
}
108+
//Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
109+
//When the continuation token is null, the last page has been returned and execution can exit the loop.
110+
do
111+
{
112+
//This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter,
113+
//or by calling a different overload.
114+
resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);
127115

128-
//Get the continuation token.
129-
continuationToken = resultSegment.ContinuationToken;
116+
foreach (var blobItem in resultSegment.Results)
117+
{
118+
thumbnailUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
130119
}
131-
while (continuationToken != null);
132120

133-
return await Task.FromResult(thumbnailUrls);
134-
}
135-
catch (Exception ex)
136-
{
137-
throw ex;
121+
//Get the continuation token.
122+
continuationToken = resultSegment.ContinuationToken;
138123
}
124+
125+
while (continuationToken != null);
126+
127+
return await Task.FromResult(thumbnailUrls);
139128
}
140129
}
141130
}

0 commit comments

Comments
 (0)