Universal Windows 10 App with Azure Storage

Universal Windows 10 App with Azure Storage

azureStorageWinApp1

Short introduction

I have shown you some useful examples connected with Universal Windows 10 Apps but today the topic is very important and much more interesting than ever. How to make your data persistence even when your application is closed?

In this case there are many ways to do it but I would like to show you one – Microsoft Azure Storage. You can ask what is Azure Storage?

Let me start from the beginning. Microsoft Azure is cloud provided by Microsoft company, which offers huge amount of services. You can host webstie using Azure Websites or create Azure Storage to collect your app data.

In this example we will use Azure Storage – secured cloud storage for storing and retrieving larg amount of data. We will store photos taken through our application.

What do I need to start?

1) Visual Studio 2015 Community (for free) or higher

2) Microsoft Azure subscription (you can test it for free here)

Let’s start

 1) SIGN IN TO MICROSOFT AZURE PORTAL (AZURE PORTAL):

azureStorageWinApp2

 2) SELECT “NEW” TAB ON THE LEFT SIDE -> “DATA + STORAGE” -> “STORAGE ACCOUNT” -> “CREATE”:

azureStorageWinApp3

 3) TYPE THE NAME FOR YOUR STORAGE (MINE IS “PHOTOSTORAGESAMPLEAPP”) AND SELECT THE LOCATION (MINE IS NORTH EUROPE) AND CLICK CREATE:

azureStorageWinApp4

 4) IT WILL TAKE FEW MINUTES TO CREATE THE STORAGE. FINALLY YOU SHOULD BE ABLE TO SEE YOUR NEWLY CREATED STORAGE:

azureStorageWinApp5

azureStorageWinApp6

 5) YOUR STORAGE IS READY. NOW WE CAN CREATE UNIVERSAL WINDOWS 10 APP TO STORE TAKEN PICTURES:

1) Open Visual Studio and create new Universal Windows App project:

azureStorageWinApp7

azureStorageWinApp8

2) Add NuGet Package to your project called “WindowsAzure.Storage”:

azureStorageWinApp9

azureStorageWinApp10

 6) PREPARE YOUR APP FOR TAKING PICTURES:

Our Universal Windows 10 App must be capable of taking pictures. Let’s create simple UI for taking pictures and displaying them:

1) Open “MainPage.xaml” file and replace default “Grid” element with code below:

 

2) Open “MainPage.xaml.cs” file and change your “MainPage” class to look like below:

<grid background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
       <button x:name="PictureButton" content="Take picture" horizontalalignment="Center" verticalalignment="Bottom" margin="0,0,0,10" click="PictureButton_Click">  
       <img x:name="TakenPicture" horizontalalignment="Center" height="200" verticalalignment="Center" width="200">  
     
/button>
</grid>  
public sealed partial class MainPage : Page  
    {  
        public MainPage()  
        {  
            this.InitializeComponent();  
        }  
  
        private async void addPhoto()  
        {  
            var picker = new Windows.Storage.Pickers.FileOpenPicker();  
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;  
            picker.FileTypeFilter.Add(".jpg");  
            picker.FileTypeFilter.Add(".jpeg");  
            picker.FileTypeFilter.Add(".png");  
  
            StorageFile userPhoto = await picker.PickSingleFileAsync();  
            if (userPhoto != null)  
            {  
                var filestream = await userPhoto.OpenAsync(FileAccessMode.Read);  
                BitmapImage bitmapImage = new BitmapImage();  
                bitmapImage.SetSource(filestream);  
                TakenPicture.Source = bitmapImage;  
                saveUserPhoto(userPhoto);  
            }  
        }  
  
        private CloudStorageAccount createStorageAccountFromConnectionString()  
        {  
            var localSettings = ApplicationData.Current.LocalSettings;  
  
            CloudStorageAccount storageAccount;  
            try  
            {  
                storageAccount = CloudStorageAccount.Parse("--your connection string--");  
            }  
            catch (FormatException)  
            {  
      throw new FormatException("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the application.");  
            }  
            catch (ArgumentException)  
            {  
      throw new ArgumentException("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");  
            }  
  
            return storageAccount;  
        }  
  
        private async void saveUserPhoto(StorageFile photo)  
        {  
            CloudStorageAccount storageAccount = createStorageAccountFromConnectionString();  
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
            CloudBlobContainer container = blobClient.GetContainerReference("photoscontainer");  
            await container.CreateIfNotExistsAsync();  
            CloudBlockBlob blob = container.GetBlockBlobReference(photo.Name);  
            await blob.UploadFromFileAsync(photo);  
            MessageDialog dialog = new MessageDialog("Photo sucessfully uploaded!");  
            await dialog.ShowAsync();  
        }  
  
        private void PictureButton_Click(object sender, RoutedEventArgs e)  
        {  
            addPhoto();  
        }  
    }  

Launch the app and take some picture:

azureStorageWinApp11

azureStorageWinApp12

 7) OUR APP IS READY FOR STRING PICTURES IN MICROSOFT AZURE STORAGE:

Before we do something more I would like to stop at this point for a minute. It’s worth saying a few words about how exactly we will store those pictures.

Azure Storage consists of four sectors for storing data:

a) Azure Blob Storage – to store unstructured data, such as documents and media files.

b)  Azure Table Storage – to store structured NoSQL data

c)  Azure Queue Storage – to reliably store messages

d) SMB-based Azure File Storage – for existing or new applications

In our case we will use Azure Storage Blob. Please look at the picture below. It presents the logical archtecture of storing data using Blob:

azureStorageWinApp13

a) Storage Account – All access to Azure Storage is done through a storage account

b) Container – A container provides a grouping of a set of blobs. All blobs must be in a container

c) Blob – A file of any type and size

 8) UPLOAD FILE TO AZURE STORAGE:

1) Before you can upload something to Azure Storage you must obtain connection string from Azure Portal:

azureStorageWinApp14

2) Now you are able to connect to the Azure Storage from Universal Windows 10 App using method below:

private CloudStorageAccount createStorageAccountFromConnectionString()  
        {  
            var localSettings = ApplicationData.Current.LocalSettings;  
  
            CloudStorageAccount storageAccount;  
            try  
            {  
                storageAccount = CloudStorageAccount.Parse("--your connection string--");  
            }  
            catch (FormatException)  
            {  
                throw new FormatException("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the application.");  
            }  
            catch (ArgumentException)  
            {  
                throw new ArgumentException("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");  
            }  
  
            return storageAccount;  
        }  

3) With correct connection string you can now upload taken picture using method below:

 private async void saveUserPhoto(StorageFile photo)  
    {  
      CloudStorageAccount storageAccount = createStorageAccountFromConnectionString();  
      CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
      CloudBlobContainer container = blobClient.GetContainerReference("photoscontainer");  
      await container.CreateIfNotExistsAsync();  
      CloudBlockBlob blob = container.GetBlockBlobReference(photo.Name);  
      await blob.UploadFromFileAsync(photo);  
      MessageDialog dialog = new MessageDialog("Photo sucessfully uploaded!");  
      await dialog.ShowAsync();  
    }  
 

Note that my container name is: “photoscontainer” and my blob name is the name of taken picture.

4) Remember to enable “Internet (Client & Server) capability in “Package.appxmanifest” file:

azureStorageWinApp15

5) If you have done everything correctly before your app should be able to upload taken picture (or picture from gallery) to Azure Storage:

azureStorageWinApp16

6) You can also check in Azure Portal whether your Azure Storage Container for photos was created:

azureStorageWinApp17

Sum up

Now you know how to use Microsoft Azure Storage to keep your photos and files. This is just the beginning. I strongly recommend reading great documentation for Azure Storage under the links below:

1) Azure Storage Blobs

2) Azure Storage Blob from .NET

Enjoy!

Advertisements