Xamarin.Forms - Working with Azure Blob Storage

Introduction
 
Xamarin.Forms - Working with Azure Blob Storage 
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 
Azure 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.
 
Store any type of unstructured data—including images, videos, audio, documents and backups. You can write error logs also.
 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
  • Microsft Azure subscription
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Working with Azure Blob Storage
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
 
Create a Storage Account in Azure
 
http://portal.azure.com
 
In this step, you must create a Storage account service in the Azure portal. 
 
 
Xamarin.Forms - Working with Azure Blob Storage
 
After creating a storage account, check your access keys and connection strings.
 
Xamarin.Forms - Working with Azure Blob Storage
 
Setting up the User Interface
 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinBlob"  
  5.              x:Class="XamarinBlob.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <!-- Place new controls here -->  
  9.         <Image Source="banner1.png" HeightRequest="100"/>  
  10.         <Image WidthRequest="200" HeightRequest="150" x:Name="imgChoosed"></Image>  
  11.         <Button x:Name="btnPick" Text="Pick" Clicked="BtnPick_Clicked"></Button>  
  12.         <Button x:Name="btnStore" Text="Upload" Clicked="BtnStore_Clicked"></Button>  
  13.         <Button x:Name="btnGet" Text="Download" Clicked='BtnGet_Clicked'></Button>  
  14.         <Button x:Name="btnDelete" Text="Delete" Clicked="BtnDelete_Clicked"></Button>  
  15.     </StackLayout>  
  16.   
  17. </ContentPage>  
Xamarin.Forms - Working with Azure Blob Storage
 
NuGet Packages
 
Now, add the following NuGet packages.
  1. Xam.Plugin.Media
  2. Microsoft.Azure.Storage.Blob 
Add Microsoft.Azure.Storage.Blob NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "Microsoft.Azure.Storage.Blob" and add the resultant package. Remember to install it for each project (.NET Standard, Android, iOS).
 
Connect your Storage Account
  1. MediaFile file;  
  2.         static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJp**********************ocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";  
  3.         static  CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  
  4.         static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  5.         static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");  
Pick Files
 
In this step, I'm going to upload images.
  1. private async void BtnPick_Clicked(object sender, EventArgs e)  
  2.         {  
  3.             await CrossMedia.Current.Initialize();  
  4.             try  
  5.             {  
  6.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  7.                 {  
  8.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  9.                 });  
  10.                 if (file == null)  
  11.                     return;  
  12.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  13.                 {  
  14.                     var imageStram = file.GetStream();  
  15.                     return imageStram;  
  16.                 });  
  17.             }  
  18.             catch (Exception ex)  
  19.             {  
  20.                 Debug.WriteLine(ex.Message);  
  21.             }  
  22.         }  
Xamarin.Forms - Working with Azure Blob Storage
 
Upload Files
 
Now, write the following code to upload files to Azure blob storage.
  1. private async void BtnStore_Clicked(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             string filePath = file.Path;  
  5.             string fileName = Path.GetFileName(filePath);  
  6.             await cloudBlobContainer.CreateIfNotExistsAsync();  
  7.   
  8.             await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions  
  9.             {  
  10.                 PublicAccess = BlobContainerPublicAccessType.Blob  
  11.             });  
  12.             var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);  
  13.             await UploadImage(blockBlob, filePath);  
  14.         }  
  15.   
  16.  private static async Task UploadImage(CloudBlockBlob blob, string filePath)  
  17.         {  
  18.             using (var fileStream = File.OpenRead(filePath))  
  19.             {  
  20.                 await blob.UploadFromStreamAsync(fileStream);  
  21.             }  
  22.         }  
Xamarin.Forms - Working with Azure Blob Storage
 
Download Files
 
Use the following code to download files from Azure blob storage.
  1. private async void BtnGet_Clicked(object sender, EventArgs e)  
  2.         {  
  3.             string filePath = file.Path;  
  4.             string fileName = Path.GetFileName(filePath);  
  5.             var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");  
  6.             await DownloadImage(blockBlob, filePath);  
  7.         }  
  8.   
  9.  private static async Task DownloadImage(CloudBlockBlob blob, string filePath)  
  10.         {  
  11.             if (blob.ExistsAsync().Result)  
  12.             {  
  13.                 await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);  
  14.             }  
  15.         }  
Delete Files
 
Use the following code to Delete files from Azure blob storage.
  1. private async void BtnDelete_Clicked(object sender, EventArgs e)  
  2.         {  
  3.             var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");  
  4.             await DeleteImage(blockBlob);  
  5.         }  
  6.   
  7.   
  8.  private static async Task DeleteImage(CloudBlockBlob blob)  
  9.         {  
  10.             if (blob.ExistsAsync().Result)  
  11.             {  
  12.                 await blob.DeleteAsync();  
  13.             }  
  14.         }  
Check out Full Code
 
MainPage.xaml.cs
  1. using Xamarin.Forms;  
  2. using Microsoft.Azure.Storage;  
  3. using Microsoft.Azure.Storage.Blob;  
  4. using System.IO;  
  5.   
  6. namespace XamarinBlob  
  7. {  
  8.     public partial class MainPage : ContentPage  
  9.     {  
  10.         MediaFile file;  
  11.         static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJphtzmjnBy0RoyQLgRC8WEvh6ecc9RbWocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";  
  12.         static  CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  
  13.         static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  14.         static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");  
  15.           
  16.         public MainPage()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         private async void BtnPick_Clicked(object sender, EventArgs e)  
  22.         {  
  23.             await CrossMedia.Current.Initialize();  
  24.             try  
  25.             {  
  26.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  27.                 {  
  28.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  29.                 });  
  30.                 if (file == null)  
  31.                     return;  
  32.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  33.                 {  
  34.                     var imageStram = file.GetStream();  
  35.                     return imageStram;  
  36.                 });  
  37.             }  
  38.             catch (Exception ex)  
  39.             {  
  40.                 Debug.WriteLine(ex.Message);  
  41.             }  
  42.         }  
  43.   
  44.         private async void BtnStore_Clicked(object sender, EventArgs e)  
  45.         {  
  46.   
  47.             string filePath = file.Path;  
  48.             string fileName = Path.GetFileName(filePath);  
  49.             await cloudBlobContainer.CreateIfNotExistsAsync();  
  50.   
  51.             await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions  
  52.             {  
  53.                 PublicAccess = BlobContainerPublicAccessType.Blob  
  54.             });  
  55.             var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);  
  56.             await UploadImage(blockBlob, filePath);  
  57.         }  
  58.   
  59.         private async void BtnGet_Clicked(object sender, EventArgs e)  
  60.         {  
  61.             string filePath = file.Path;  
  62.             string fileName = Path.GetFileName(filePath);  
  63.             var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");  
  64.             await DownloadImage(blockBlob, filePath);  
  65.         }  
  66.   
  67.         private async void BtnDelete_Clicked(object sender, EventArgs e)  
  68.         {  
  69.             var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");  
  70.             await DeleteImage(blockBlob);  
  71.         }  
  72.   
  73.         private static async Task UploadImage(CloudBlockBlob blob, string filePath)  
  74.         {  
  75.             using (var fileStream = File.OpenRead(filePath))  
  76.             {  
  77.                 await blob.UploadFromStreamAsync(fileStream);  
  78.             }  
  79.         }  
  80.   
  81.         private static async Task DownloadImage(CloudBlockBlob blob, string filePath)  
  82.         {  
  83.             if (blob.ExistsAsync().Result)  
  84.             {  
  85.                 await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);  
  86.             }  
  87.         }  
  88.   
  89.         private static async Task DeleteImage(CloudBlockBlob blob)  
  90.         {  
  91.             if (blob.ExistsAsync().Result)  
  92.             {  
  93.                 await blob.DeleteAsync();  
  94.             }  
  95.         }  
  96.     }  
  97. }  
Click the "Play" button to try it out.
Xamarin.Forms - Working with Azure Blob Storage
 
I hope you have understood how to use Azure Blob Storage in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)


Similar Articles