Storage Account In Windows Azure

In this session, we are briefly going to discuss how to upload a new file into Azure Account using blob in Storage Account.

File Upload

 
We have used Azure Blob Storage for file upload.
 

Overview of Blob Storage

 
Azure Blob Storage is Microsoft's Object Storage Solution for the cloud. Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data is the data that does not adhere to a data model or definition, such as text or binary data.
 
To use the Blob Storage, you have to create an account on the Azure portal.
 
Navigate to your new Storage Account in the Azure Portal.
  1. Open Windows Azure account and click "Storage Account" in the left menu bar.

    Storage Account In Windows Azure

  2. The selected option will be redirected into Storage Account page and there, you click on "Add".

    Storage Account In Windows Azure

  3. Select the subscription in which you want to create the Storage Account.

  4. Under the Resource Group field, select "Create new". Enter a name for your new resource group, as shown in the following image.

    Storage Account In Windows Azure

  5. Next, enter a name for your storage account. The name you choose must be unique across Azure. The name also must be between 3 and 24 characters in length and can include numbers and lowercase letters only.

  6. Select a location for your storage account or use the default location.

  7. Select "Review + Create" on the bottom of the screen. Do not select "Create" in the next step.

  8. Locate your storage account.

  9. In the Settings section of the storage account overview, select Access keys. Here, you can view your account access keys and the complete connection string for each key.

  10. Find the connection string value under key1 and select the "Copy" button to copy the connection string. You will add the connection string value to an environment variable in the next step.

    Storage Account In Windows Azure

  11. Save storage connection string in the appsettings.json file. Also, add container name for storage.

    Storage Account In Windows Azure

    .NET CODE Implementation

    Use the following code implementation on your Visual Studio framework.
    1. "AzureConnectionStrings": {  
    2.     "StorageConnection""DefaultEndpointsProtocol=https;AccountName=hstorage;AccountKey=1dYm3E5YqDkxZF5MJybdMngkhPaZepzEup7b9vpvW+sTliGn4mwIskRUsYsIpaLJb2LKerOg==;EndpointSuffix=core.windows.net",  
    3.     "appcontainer""h-app"  
    4.   },  
  12. Create the folder name dynamically based on the Application Id.

    Storage Account In Windows Azure

    CODE
    1. #region "Document upload"  
    2. /// <summary>  
    3. ///  document upload  
    4. /// </summary>  
    5. /// <param name="licenseAgreementDocs"></param>  
    6. /// <returns></returns>  
    7. [HttpPost]  
    8. [Route("fileupload")]  
    9. [RequestFormSizeLimit(valueCountLimit: 29283939, Order = 1)]  
    10. public async Task < IActionResult > UploadDocument(FileUpload fileUpload) {  
    11.     //TODO: Retrieve and use Folder TypeName  
    12.     try {  
    13.         if (fileUpload.ApplicationId > 0) {  
    14.             var folderStructure = $” Application - {  
    15.                 fileUpload.ApplicationId  
    16.             }  
    17.             /ownerInfo";  
    18.             // Confirms Upload  
    19.             var uploaded = await this.ApplicationHelper.UploadFile(fileUpload, folderStructure);  
    20.             return Ok(uploaded);  
    21.         }  
    22.         return new JsonResult("Id cannot be null");  
    23.     } catch (Exception ex) {  
    24.         return BadRequest(new JsonResult(ex.Message));  
    25.     }  
    26. }#endregion  
  13. After initialization of container, it will return the blob storage name, URI.

    Storage Account In Windows Azure

    CODE

    This method is used to upload a file from .NET development to Azure Storage Account.
    1. /// <summary>  
    2. /// common upload document  
    3. /// </summary>  
    4. /// <param name="Data"></param>  
    5. /// <param name="FolderPath"></param>  
    6. /// <returns></returns>  
    7. public async Task<FileUploaded> UploadFile(FileUpload Data, string FolderPath)  
    8. {  
    9.    CloudBlockBlob blockBlob;  
    10.    // cleans file name  
    11.    string cFileName = MakeValidFileName(Data.File.FileName);  
    12.   
    13.    // init container  
    14.    var container = await InitFileUpload();  
    15.    // Creating storage directory if not exist  
    16.    var dirPath = container.GetDirectoryReference(FolderPath);  
    17. if (dirPath == null)  
    18. {  
    19.    // Retrieve reference to a blob.  
    20.    blockBlob = container.GetBlockBlobReference(cFileName.AppendTimeStamp());  
    21.    await blockBlob.UploadFromStreamAsync(Data.File.OpenReadStream());  
    22. }  
    23. else  
    24. {  
    25.    // Retrieve reference to a blob.  
    26.    blockBlob = dirPath.GetBlockBlobReference(cFileName.AppendTimeStamp());  
    27.    await blockBlob.UploadFromStreamAsync(Data.File.OpenReadStream());  
    28. }  
    29.   
    30. var extn = FileExtention(blockBlob.Uri.AbsolutePath);  
    31. // Response for storage  
    32. var uploaded = new FileUploaded()  
    33. {  
    34.    MimeType = extn,  
    35.    OriginalFileName = blockBlob.Name,  
    36.    Path = blockBlob.Uri.AbsoluteUri,  
    37. };  
    38.   
    39. var uploadedData = new FileUploaded();  
    40.   
    41. if (uploaded != null)  
    42. {  
    43.   
    44.    uploadedData.Id = uploaded.Id; // Azure storage response id  
    45.    uploadedData.FileName = Data.File.FileName;  
    46.    uploadedData.OriginalFileName = uploaded.OriginalFileName;  
    47.    uploadedData.Path = uploaded.Path;  
    48.    uploadedData.Size = Convert.ToInt32(Data.File.Length);  
    49.    uploadedData.MimeType = Data.File.ContentType;  
    50.    uploadedData.FileType = FileExtention(uploaded.Path);  
    51.    uploadedData.Status = true;  
    52.    uploadedData.OwnerId = Data.OwnerId;  
    53.    uploadedData.ApplicationId = Data.ApplicationId;  
    54.   
    55. }  
    56. return uploadedData;  
    57. }  
    58.   
    59. /// <summary>  
    60. /// cleans filename  
    61. /// </summary>  
    62. /// <param name="name"></param>  
    63. /// <returns></returns>  
    64. public static string MakeValidFileName(string name)  
    65. {  
    66.    string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));  
    67.    string invalidRegStr = string.Format(@"([{0}]*\.+$ )|([{0}]+)", invalidChars);  
    68.    var cname = System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_");  
    69.    return cname.Replace(" ""-").ToLower();  
    70. }  
    71. /// <summary>  
    72. /// Get File extention from file name  
    73. /// </summary>  
    74. /// <returns></returns>  
    75. public string FileExtention(string path)  
    76. {  
    77.    var extn = Path.GetExtension(path);  
    78.    return extn.Substring(1, extn.Length - 1);  
    79. }  
  14. Use this Storage Connection String to file upload. (Helper Class)

    Storage Account In Windows Azure

    CODE

    This will read and connect a trust to Windows Azure through connection strings.
    1. /// <summary>  
    2. /// Initializing Storage and Storage clients  
    3. /// </summary>  
    4. /// <returns></returns>  
    5. public async Task < CloudBlobContainer > InitFileUpload() {  
    6.     // TODO: Storage connection string need to be add in configs  
    7.     string storageConnectionString = _configuration.GetSection("AzureConnectionStrings").GetSection("StorageConnection").Value;  
    8.     // Retrieve storage account from connection string.  
    9.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);  
    10.     // Create the blob client.  
    11.     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
    12.     string appcontainer = _configuration.GetSection("AzureConnectionStrings").GetSection("appcontainer").Value;  
    13.     // Retrieve a reference to a container.  
    14.     CloudBlobContainer container = blobClient.GetContainerReference(appcontainer);  
    15.     // Create the container if it doesn't already exist.  
    16.     await container.CreateIfNotExistsAsync();  
    17.     // TODO: Need set secured permission currently it public  
    18.     await container.SetPermissionsAsync(new BlobContainerPermissions {  
    19.         PublicAccess = BlobContainerPublicAccessType.Blob  
    20.     });  
    21.     return container;  
    22. }  
  15. Save the file name, URI in DB.
I hope this helps.