Upload
glenn-stephens
View
420
Download
3
Embed Size (px)
Citation preview
Azure Mobile Storage
Azure Storage in the Mobile World@glenntstephens
Welcome everyoneWhat will we cover?
In case we’ve not met...
I train developers To be Xamarin certified mobile
developers for Xamarin University
I develop appsABBA – Always Be Building
Apps
I play musicIn case you want to discuss
anything else. Politics, Comedy and Jackie Chan movies are good too
The need for Storage
Server Rule #1
From little things...
ASP.NET Server
File Storage
Databases
The two ways we’ll look atBlob Storage is what we’ll be looking for
1. Calling using WebApi2. Calling directly from a mobile app
Looking at the APIBlobContainer storage
Azure Storage API Housekeeping• Before we access it via the API:• Ensure the Azure Account is setup• Ensure we have a container setup
• Like many Azure services, the Portal has great documentation• Have a look at the services you can connect to
Common Scenarios• Here is our mobile app day-to-day:• Upload a file to the server• Download the file from the server (if authorisation is
required)• Get the public URL for a file (if its public)• Delete a file• List the files in the container
Encapsulate all the things• You will need to connect
in. • I find its easy to make a
façade to manage storage for Access• CloudHop
Common Scenario: Connecting• We need to connect to the container public class AzureStorageHelper { string settingName; string containerName; bool isPublic;
CloudBlobContainer container = null;
public AzureStorageHelper(string settingName, string containerName, bool isPublic = true) { this.settingName = settingName; this.containerName = containerName; this.isPublic = isPublic; }
Getting the Blob container (1/2)• Its access to the blob container that lets you perform
all the operations you need:
public CloudBlobContainer GetBlobContainer(){ if (container != null) return container;
var connStr = GetConnectionString(); var storageAccount = CloudStorageAccount.Parse(connStr); var blobClient = storageAccount.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference(this.containerName);
Getting the Blob container (2/2)• Its access to the blob container that lets you perform
all the operations you need: if (blobContainer.CreateIfNotExists()) { blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = isPublic ? BlobContainerPublicAccessType.Blob : BlobContainerPublicAccessType.Off }); }
container = blobContainer; return blobContainer;}
Common Scenario: Uploading• Uploading a single file to the container
public string UploadBlob(string filename, Stream stream){ if (stream.Length == 0) throw new ApplicationException("There was no content for the file");
var reference = GetBlobContainer() .GetBlockBlobReference(filename);
reference.UploadFromStream(stream);
return reference.Uri.AbsoluteUri;}
Note: The non-async mechanisms are used for this demo for simplicity. Use the async version for real power. Learn async if you haven’t used it before
Common Scenario: Downloading• Two options here• For public collections, provide the Url• For private collections use the API
Downloading to a stream• For when you want to manage the resources a little
more elegantlypublic void DownloadToStream(string name, Stream stream){ Uri ur = new Uri(name); string fname = Path.GetFileName(ur.LocalPath);
var foundFile = GetBlobContainer().GetBlockBlobReference(fname); foundFile.DownloadToStream(stream);}
Common Scenario: The public Url• Gather the Url from the source• Use HttpClient or other mechanisms to download the
resource
public string UriForFile(string filePath){ return container.ServiceClient.BaseUri.AbsoluteUri + containerName + "/"+ filePath;}
Common Scenario: Listing the files• Need to find what is there• I tend to use Guids as a way of keeping the files
uniquepublic List<string> ListAllBlobs(){ return GetBlobContainer() .ListBlobs() .Select(item => item.Uri.ToString()) .ToList();}
Common Scenario: Deleting a file• When you need to make sure the file is no longer there
public void DeleteBlob(string name){ Uri ur = new Uri(name); string fname = Path.GetFileName(ur.LocalPath);
var foundFile = GetBlobContainer().GetBlockBlobReference(fname);
if (foundFile != null) foundFile.Delete();}
Exposing it via Web Api[HttpPost][Route("api/ImageService/UploadNewImage")]public async Task<IHttpActionResult> DirectImageUpload(){if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider);
var file = provider.Contents.First(); var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var stream = await file.ReadAsStreamAsync(); GetAzureStorageConnection().UploadBlob(filename, stream);
return Ok();}
Connecting from a mobile app• Easiest way is to use HttpClient to connect to the URL
to access the file contained in the Blob• If it is an image, you could use other mechanisms such
as Xamarin.Forms Image and ImageSource classes
DemonstrationLets run some code
Azure Mobile ServicesBlobContainer direct from the device
The Mobile App• Moments - Like a Snapchat application.• Credit goes to Pierce Boggan from the Xamarin team
for building the application.
What is Moments?• A snapchat clone built on
Xamarin.Forms• https://github.com/pierceboggan/Moments
• Connects to Azure for several services• Azure Mobile Services• Azure Storage
• Currently on the Android Play Store• Will be on the iOS Store at
some point Follow @pierceboggan on Twitter for updates on the app news
Moments DemoLets run it and see...
The Project Setup• Xamarin.Forms project• Services for the app indicate data access or implemented
capabilities such as Camera access• FriendService, AccountService for AMS Data Access• MobileServiceClientFactory for mobile access• MomentService for uploading an image and storing the moment on
the service• Custom renderers for iOS and Android for Camera Access• Shared Project setup
• Better approach for Azure and Xamarin.Forms• This configuration is not ideal for XAML though
A look at the code• Core Access:• Using Identity Service to identify users• Using AMS to store data
• Services:• Moment Service
• SendMoment• DestroyMoment• GetMoments
Code AnalysisLets see some code
Review• Most mobile apps need some level of server capability.• Especially connected apps
• Storage is an essential service that needs to be managed• Azure Storage gives you that capability to easily run it
regardless of the way you need to execute it• Using it in any configuration can be easily done using
Azure• Mobile Apps• WebApi or Web Apps
Resources• http://azure.microsoft.com/en-us/documentation/services/storage/• http://azure.microsoft.com/en-us/documentation/videos/azure-storage-5-minute-over
view/
• http://manage.windowsazure.com• http://developer.xamarin.com/guides/cross-platform/azure/• https://github.com/pierceboggan/Moments
ThanksKeep in touch via twitter @glenntstephens or email: [email protected]