
Good day.
We live in a world of total globalization, both in real life and in virtual life. I mean that we want to have the same data, the same settings and the same behavior of programs on different devices. Such synchronization of everything and everyone in our time is easy to achieve with the help of clouds. This is what will be discussed in this article, namely, the crossing of an application for Windows 8 (WinRT) with the Windows Azure cloud for storing data and metadata.
')
Introductory
So, suppose that we have an application for Windows 8 (let it be a service for storing some text records), which:
1) It should display a list of records with minimal information about each of them (for example, a title or a creation date). Let's call it metadata.
2) It should be able to show detailed information about the entry (content) when navigating to a specific item. Let's call it data.
3) Must synchronize data between different devices running Windows 8 (created a record at home, viewed it at work).
The most correct approach I see is to split the data and metadata and store it in different places. This will allow us to quickly obtain small in terms of metadata for display in the form of a list, and load the "heavy" data at the user's request.
In the course of this article, we will become familiar with Windows Azure Mobile Services for storing metadata and Windows Azure Blob Storage for storing data. There is a lot of text and pictures ahead.
Step 1. Working with cloud storage
For more flexible and cross-platform work with Windows Azure Blob Storage, I additionally recommend that you enter another layer as a WCF service that will receive and process requests from mobile clients. Therefore, the first step of this manual will consist of several stages.
Creating the necessary Windows Azure services
First we need to prepare a cloud environment by creating two services in Windows Azure - Cloud Service and Storage. Let's start with the second. Go to the
portal management Windows Azure . At the bottom of the page there is a big button with a plus. Clicking will open a selection of services to create. We need
DATA SERVICES -> STORAGE :

Enter any convenient service name for us, click the checkbox button below and wait until the service receives Online status. After that we go into the settings of our storage and look for the "Mange keys" button with the icon i on board with our eyes and mouse. Click on it and see three fields in front of you. The first one will contain the name of this service, which we assigned to it during the creation, and the second and third will store the access keys. Remember the first of them, he will come in handy soon.
Creation of WCF service
To create a WCF service and its corresponding service in Windows Azure, we will use Visual Studio 2012. I will show the example of the Ultimate version, but the free version of the Web is suitable.
So, open a studio and create a new project with the type of Cloud:

In the window that appears, we will be asked to choose the types of projects that need to be placed in the cloud. We are interested in WCF Service Web Role. Select it and add to the list of created (do not forget to rename):

Visual Studio, after some deliberation, will create two projects for us, one of which will be a WCF service project, and the second a special project for publishing to the Windows Azure cloud. Let's build them a little bit.
In order to painlessly publish our service to the cloud, Visual Studio needs to know exactly which cloud to do it, and also understand that we have this right. To convince her, just right-click on the Cloud project and select the Publish menu item:

If you have not previously published anything to the cloud, then instead of the value WindowsAzureMSDN you will have empty. To make it thick, just
follow the link , download the publication profile and import it using the Import button in Visual Studio. This will allow you to perform operations on cloud services directly from the IDE.
After we have access to the cloud from VS2012, we move on to the next step, where we will create the Cloud Service directly to host our WCF service. On the Common Settings tab, select
Cloud Service -> Create New , and on the Advanced Settings tab, select the existing Storage Account (it should already be available for selection in the list). Ensure that both the Cloud Service and the Storage Account are in the same zone:


After performing these steps, we simply click the Publish button, and the project will leak into the network.
Step 2. Using the repository
First of all, add the connection string to the web.config file of our service. The line looks like this:
DefaultEndpointsProtocol = https; AccountName = service_name; AccountKey = that_the_key_key_ot_StorageWorking with cloud storage can be done in two ways - using the REST API and using the .NET wrapper. In this article I will use the second option as the most simple. Moreover, it was not for nothing that we created our own service.
So, in order to use this functionality, you need to connect the “Windows Azure Storage” package to your NuGet project:

BLOB containers are connected and managed using the client:
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString); _blobClient = storageAccount.CreateCloudBlobClient();
Further work with the repository is quite simple:
// CloudBlobContainer container = BlobClient.GetContainerReference(ContainerName); // , container.CreateIfNotExists(); // "-<id >" CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobNamePrefix + data.Id); // var serializer = new XmlSerializer(typeof(CompositeType)); using (var s = new MemoryStream()) { serializer.Serialize(s, data); s.Seek(0, SeekOrigin.Begin); // blob blockBlob.UploadFromStream(s); }
Similarly, the data can be obtained:
// CloudBlobContainer container = BlobClient.GetContainerReference(ContainerName); // - null if (!container.Exists()) return null; // var blockBlob = container.GetBlockBlobReference(BlobNamePrefix + id); if (!blockBlob.Exists()) return null; // var serializer = new XmlSerializer(typeof(CompositeType)); CompositeType result = null; using (var s = new MemoryStream()) { // blockBlob.DownloadToStream(s); s.Seek(0, SeekOrigin.Begin); result = serializer.Deserialize(s) as CompositeType; } return result;
The above methods were placed in a wrapper class, and the WCF service itself is obsessed with a simple contract of two actions:
[ServiceContract] public interface IBlobService { [OperationContract] CompositeType GetData(int value); [OperationContract] void PutData(CompositeType data); }
!!! Here it is necessary to mention an important, but absolutely non-obvious thing. Blob names of containers and blocks must be in small case. That is, the name
BlobContainer will cause an error when attempting to create, and, for example, a
blob-container will be created without problems.
After we have written the service, we publish it once again to the cloud and after completing this procedure it will be available at
your_service_name.cloudapp.net/BlobService.svc .
Step 3. Mobile services
The previous two steps were aimed at creating an infrastructure for storing “data” - a large amount of information that is not always needed, but on request. Now let's move on to storing “metadata”. To do this, we will use the recent novelty in Windows Azure - Mobile Services.
Creating a new mobile service is as easy as other services in Windows Azure. Again we go to the
management portal , where in the creation menu below we select
COMPUTE -> MOBILE SERVICE and see the wizard in front of us:

We indicate in it the name of the future service, the region of placement (do not forget to be located somewhere in one place), specify the Storage where our data will be stored (you can use an existing one or create a new one) and complete the wizard.
As soon as the service is created, go to its page in the section marked with the cloud icon with a lightning (I do not know the name of it). On this page there are two options -
Create a new Windows Store app and
Connect an existing Windows Store app . The first will allow you to download the archive with the application configured to work with your mobile service, and the second will simply give a piece of code that needs to be embedded into an existing application. In principle, now it does not matter which option you choose. I suggest using the second one and creating the application manually.
In the meantime, we have not done this, let's prepare Mobile Services for use. To do this, first go to the Data section (in the top menu) and add a new table to store the records. You can call it whatever you like, I have TestItem:

This table will later contain the metadata entries entered in the Windows 8 application.
Step 4. Windows 8
It is time to do something for which everything was started. The application for Windows 8 (WinRT) can be created for free in the Express version of Visual Studio 2012 (like the one we used for the WCF service, but now for Win8 applications).
File -> New Project -> Windows Store:

First you need to add the necessary links to the library so that you can enjoy the benefits of Mobile Services. If you noticed, in the previous step, Windows Azure offered us to download and install
Mobile Services SDK . This needs to be done, because with its help we will work with cloud services for mobile devices.
Once the SDK is installed, we can connect it to the project using the standard procedure
Add Reference :

Then we will also include a link to our WCF service. This is also done easily using the standard
Add Service Reference dialog:

As a result of connecting the Service Reference, Visual Studio will create for us a special wrapper class that will look like a regular class with a service contract, but in fact will contact the remote WCF at the specified address.
And finally, add the code for using mobile services, which, as I said above, can be obtained on the page with a little cloud and lightning in Windows Azure. It looks like this:
public static MobileServiceClient MobileService = new MobileServiceClient( "https://***.azure-mobile.net/", "secret_key");
I added this field to the App.xaml page to access mobile services from anywhere in the application.
Step 5. Putting it all together
It is time to connect all the paths in one place and write the code, which, when adding a new record, will place it in the Azure Blob Storage and Mobile Services store.
private async Task PutDataTestWCF(CompositeType data) { // WCF var cli = await Task.Run(() => new BlobServiceClient(new BasicHttpBinding(), new EndpointAddress(CloudServiceEndpoint))); // () await cli.PutDataAsync(data); // await cli.CloseAsync(); // var table = App.MobileService.GetTable<TestItem>(); // var list = await table.Select(x => x.Id == data.Id).ToListAsync(); // , , - if (list != null && list.Count > 0) await table.UpdateAsync(new TestItem() {Id = data.Id, Text = data.Text}); else await table.InsertAsync(new TestItem() {Text = data.Text}); }
Here you should pay attention to a few things. First, all methods that work with the network in one way or another are asynchronous. Even the client class to the WCF service that was automatically generated also contains asynchronous methods (PutDataAsync). This is great because it allows you to make the application more responsive, without forcing the user to watch the blocked interface while the application tries to connect to the Internet.
In addition, work with both services has become quite simple and transparent. What works with WCF, what about Mobile Services, both of them look like simple calls to .Net code, hiding all the details "somewhere out there." I did not write here any abstract layers of data access, but if you get confused and do everything correctly, then we can easily make mocks for testing the application.
Conclusion
In this article, first of all, I wanted to show not how to write Windows 8 applications, but how to embed the ability to work with different types of cloud storage in different ways. I deliberately cited not so much code, since the article turned out to be large and, possibly, difficult to read. Below I attach the archive with the code that can be used for training:
Download archiveIn it, I replaced all references to my service with *** or ****. I think it will be clear what and where it is necessary to substitute so that everything takes off.
In preparing the article and the test application, the following materials were used:
-
Official Blob Storage Guide-
The official guide to working with data in mobile services-
Google ,
Bing ,
Yandex- Own thoughts and guesses
PS A big request to not indifferent minusators - please write the arguments of your cons either in the comments or in a personal. It is important for me to know my flaws in order to correct them in future publications. Thank you very much.