共用方式為


Getting started with Azure Storage on Xamarin

Xamarin allows developers to use a shared C# codebase to create iOS, Android, and Windows Store apps with native user interfaces.

This tutorial shows you how to use Azure Storage Blobs with a Xamarin.Android application. If you want to learn about Azure Storage before diving into the code, see Next Steps at the end of this document.

Create an Azure Storage account

To use Azure storage, you'll need a storage account. You can create a storage account by following these steps. (You can also create a storage account by using the Azure service management client library or the service management REST API.)

1. Log into the Azure Management Portal.

2. At the bottom of the navigation pane, click NEW.

clip_image001[1]

3. Click DATA SERVICES, then STORAGE, and then click QUICK CREATE.

clip_image002

4. In URL, type a subdomain name to use in the URI for the storage account. The entry can contain from 3-24 lowercase letters and numbers. This value becomes the host name within the URI that is used to address Blob, Queue, or Table resources for the subscription.

5. Choose a Region/Affinity Group in which to locate the storage. If you will be using storage from your Azure application, select the same region where you will deploy your application.

6. Optionally, you can select the type of replication you desire for your account. Geo-redundant replication is the default and provides maximum durability. For more details on replication options, see Azure Storage Redundancy Options and the Azure Storage Team Blog.

7. Click CREATE STORAGE ACCOUNT.

Generate a Shared Access Signature

Unlike other Azure Storage client libraries, you cannot not authenticate access to an Azure Storage account using account keys. This is done in order to prevent your account credentials from being distributed to users that may download your app. Instead, we encourage the use of Shared Access Signatures (SAS) which won’t expose your account credentials.

In this getting started you will be using Azure PowerShell to generate a SAS token. Then you will create a Xamarin app that will use the generated SAS.

First, you’ll need to install Azure PowerShell. Check out this guide to learn how to install Azure PowerShell.

Next, open up Azure PowerShell and run the following commands. Remember to replace “ACCOUNT_NAME”and “ACCOUNT_KEY==” with your actual credentials. Replace “CONTAINER_NAME” with a name of your choosing.

 PS C:\> $context = New-AzureStorageContext -StorageAccountName "ACCOUNT_NAME" -StorageAccountKey "ACCOUNT_KEY=="
 PS C:\> New-AzureStorageContainer CONTAINER_NAME -Permission Off -Context $context
 PS C:\> $now = Get-Date 
 PS C:\> New-AzureStorageContainerSASToken -Name CONTAINER_NAME -Permission rwdl -ExpiryTime $now.AddDays(1.0) -Context $context -FullUri

The output of the shared access signature URI for the new container should be similar to the following:

https://storageaccount.blob.core.windows.net/sascontainer?sv=2012-02-12\&se=2013-04-13T00%3A12%3A08Z\&sr=c\&sp=wl\&sig=t%2BbzU9%2B7ry4okULN9S0wst%2F8MCUhTjrHyV9rDNLSe8g%3Dsss

Once you run the code, the shared access signature that you created on the container will be valid for the next day. The signature grants full access (i.e. read, write, delete, list) to blobs within the container.

If you’d like to learn an alternate method for generating a SAS, please check out our SAS tutorial for .NET.

Create a new Xamarin Application

For this tutorial, we'll be creating our Xamarin application in Visual Studio.

  1. Download and install Visual Studio
  2. Download and install Xamarin
  3. Open Visual Studio
  4. Select File > New > Project > Android > Blank App(Android)
  5. OK
  6. Right-click your project> Manage NuGet Packages > Search for Azure Storage and install Azure Storage 4.4.0-preview.

You should now have an app that allows you to click a button and increment a counter.

Working with Containers

The following code will perform a series of container operations with the SAS URI that you generated.

First add the following using statements:

 using System.IO;
 using System.Text;
 using System.Threading.Tasks;
 using Microsoft.WindowsAzure.Storage.Blob;
  

Next, add a line for your SAS token. Replace “SAS_URI” string with the SAS URI that you generated in Azure PowerShell. Also, add a line for a call to the UseContainerSAS method that we’ll create. Note, the async keyword has also been added before the delegate.

 public class MainActivity : Activity
 {
     int count = 1;
     string sas = "SAS_URI";
     protected override void OnCreate(Bundle bundle)
     {
         base.OnCreate(bundle);
  
         // Set our view from the "main" layout resource
         SetContentView(Resource.Layout.Main);
  
         // Get our button from the layout resource, and attach an event to it
         Button button = FindViewById<Button>(Resource.Id.MyButton);
  
         button.Click += async delegate {
             button.Text = string.Format("{0} clicks!", count++);
             await UseContainerSAS(sas);
         };
     }

Add a new method, UseContainerSAS, under the OnCreate method.

 static async Task UseContainerSAS(string sas)
 {
     //Try performing container operations with the SAS provided.
  
     //Return a reference to the container using the SAS URI.
     CloudBlobContainer container = new CloudBlobContainer(new Uri(sas));
     string date = DateTime.Now.ToString();
     try
     {
         //Write operation: write a new blob to the container. 
         CloudBlockBlob blob = container.GetBlockBlobReference("sasblob_" + date + ".txt");
  
         string blobContent = "This blob was created with a shared access signature granting write permissions to the container. ";
         MemoryStream msWrite = new 
         MemoryStream(Encoding.UTF8.GetBytes(blobContent));
         msWrite.Position = 0;
         using (msWrite)
         {
             await blob.UploadFromStreamAsync(msWrite);
         }
         Console.WriteLine("Write operation succeeded for SAS " + sas);
         Console.WriteLine();
     }
     catch (Exception e)
     {
         Console.WriteLine("Write operation failed for SAS " + sas);
         Console.WriteLine("Additional error information: " + e.Message);
         Console.WriteLine();
     }
     try
     {
         //Read operation: Get a reference to one of the blobs in the container and read it. 
         CloudBlockBlob blob = container.GetBlockBlobReference("sasblob_” + date + “.txt");
         string data = await blob.DownloadTextAsync();
  
         Console.WriteLine("Read operation succeeded for SAS " + sas);
         Console.WriteLine("Blob contents: " + data);
     }
     catch (Exception e)
     {
         Console.WriteLine("Additional error information: " + e.Message);
         Console.WriteLine("Read operation failed for SAS " + sas);
         Console.WriteLine();
     }
     Console.WriteLine();
     try
     {
         //Delete operation: Delete a blob in the container.
         CloudBlockBlob blob = container.GetBlockBlobReference("sasblob_” + date + “.txt");
         await blob.DeleteAsync();
  
         Console.WriteLine("Delete operation succeeded for SAS " + sas);
         Console.WriteLine();
     }
     catch (Exception e)
     {
         Console.WriteLine("Delete operation failed for SAS " + sas);
         Console.WriteLine("Additional error information: " + e.Message);
         Console.WriteLine();
     }
 }

Run Application

You can now run this application in an emulator or Android device.

Although this getting started focused on Android, you can use the “UseContainerSAS” code in your iOS or Windows Store applications as well. Xamarin also allows developers to create Windows Phone apps however, our library does not yet support this.

Next Steps

In this getting started, you learned how to use Azure Blob Storage and SAS with a Xamarin application. As a further exercise, a similar pattern could be applied to generate a SAS token for an Azure Table or Azure Queue to perform Table and Queue operations.

Learn more about Blobs, Tables, and Queues by checking out the following links:

Introduction to Microsoft Azure Storage
How to use Blob Storage from .NET
How to use Table Storage from .NET
How to use Queue Storage from .NET

Comments

  • Anonymous
    August 06, 2015
    Hi, I'm having difficulties using the Microsoft.WindowsAzure.Storage package. It seems like the package is not loaded correctly since I'm not able to include using statements like using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; Any ideas?