[Windows 8] Windows Azure Mobile Services: a backend for your Windows Store application!October 16th, 2012 | Posted by in .NET | Windows 8 | WinJS | WinRT | Read: 2,947
Microsoft has released recently Windows Azure Mobile Services, a set of tools allowing developers to get backend, authentication and notification for the Windows Store (and Windows Phone) applications.
Activate Windows Azure Mobile Services
The feature is currently in preview so to activate it, you need to go here and activate the feature:
For now, the feature is free but you need a valid Azure subscription to use it (thanks to my MSDN account, I’ve been able to set up my Azure account).
Create your first application
Once the feature has been activated, this one is available directly in your management portal. So go to https://manage.windowsazure.com and click on “Mobile Services” to see the list of all the services you’ve created:
Here, you can see that I’ve already created a mobile services but let’s take a look at how you can create your own. On the bottom of the screen, click on “New” and click on “Create”:
In the screen that appear, you’re asking to indicate the URL of your service (this one ends with “.azure-mobile.net”), the database that you want to use (a new one or a database you’ve already created) and the region. As the feature is still in preview, you’ll notice that there are only 2 regions available: West US and East US:
Don’t worry if you’re setting an URL that is already in use: the system will let you know that point:
Next, you’re asking the credentials to connect (or create) to the database:
Once this is done, you can click on your service and you’re redirected to the Dashboard page, where you can see some stats about usage:
First thing you need to do is to create/add some tables to the database you’ve specified for your mobile service. For that, click on the “Data” tab and click on “Add a table” to create a new table:
On the screen that appear, you can create a new table and set the different permissions needed to perform select and CRUD operations:
There are 4 kind of permissions, each of them is explained here:
- Everyone: This means that any request for the operation against the table is accepted. This option leaves your data wide-open for everyone to access.
- Anybody with the Application Key: The application key is required to perform the operation. The application key is distributed with the application. Because this key is not securely distributed, it cannot be considered a security token. To secure access to your mobile service data, you must instead authenticate users before accessing.
- Only Authenticated Users: Only authenticated users are permitted to perform the operation. Scripts can be used to further restrict access to tables based on an authenticated user.
- Only Scripts and Admins: The operation requires the service master key, which limits the operation only to registered scripts or to administrator accounts.
You may notice that you’ve not specified the columns of the table. You can click on the table name to see its details but even here, on the “Columns” tab, you just see the columns, you’re not able to add them. By default, you don’t need to predefine the schema of tables in your database. Mobile Services automatically adds columns to a table based on the data you insert. To change this dynamic schema behavior, use the Dynamic Schema setting on the Configure tab:
Your data are ready, it’s now time to access them through your Windows Store application!
Access to your backend using Windows Store application
Before being able to access your data via Mobile Services, you need to install the Mobile Services SDK (available here). Once this is done, you can start by adding a reference to the SDK:
Then, you have to declare a variable, of type MobileServiceClient, that define a way to access to your Mobile Service:
The constructor takes 2 parameters:
- The URL from the Mobile Service. This one can be found on the left part of the Dashboard screen
- The ApplicationKey, which can be found if you click on the “Manage Keys” button:
Now, you need to define a class that represent the table you’ve created before. The technique here is quite similar to the one you can use if you use an ORM tool: you define a class for each table of the database. In our case, we need to define the Users class (be careful, the table already have an column named “id‘”):
You’re now ready to perform the basic operations . For example, if you want to query the table, just use the following code:
The method ToEnumerableAsync will convert the results to an enumerable object. You can also use the method ToCollectionView to get a CollectionView object from the results. The IMobileServiceTable<T> interface contains a lot of useful methods that you can use to get/insert/update/delete data from the Mobile Service:
So if you want to insert an item, you need to use the InsertAsync method:
Unfortunately, if you execute this code, you’ll encounter the following error:
Why are you unauthorized ? To understand this error, just remember the permissions we’ve set for the Users table:
So, as you can see, only scripts (server side components) and administrators are allowed to insert data. So how to make the difference between users and admins? Simply go the “Manage Keys” screen and look for the “Master Key”:
Previously, to create our MobileServiceClient object, we’ve used the Application Key but if we change it by the Master Key and re-execute the code, all will work fine and going to the table details screen will show you the item correctly added:
Here are some code samples to retrieve data:
First query will get all users where date of birth is previous to today. Second one use LookupAsync, taking in parameter the index of the item you want to retrieve.
So, as you can see, using Mobile Service is really simple and allow anyone to have a SQL Azure Database as a backend for any Windows Store application. But you can do more and that’s what we’ll see just now!
Execution of scripts during operations
If you go the details page of the table Users, you can see the “Scripts” tab:
- insert/update: Take in parameter the item that you want to insert/update, the user who submitted the query and the request, used to execute the operation and to notify the user by sending an response.
- del (delete): Take in parameter the id of the item to delete from the database
- read: Take in parameter the query that will be executed against the table, , the user who submitted the query and the request, used to execute the operation and to notify the user by sending an response.
For the request object, there are 2 methods that you can use:
- execute, that will execute the operation
- respond: that will report the response to the user. If you want to return an error to the user, you need to use this method, passing in parameters the error to displayed or the HTTP code and response to display to the user.
For your information, here is the full list of all the HTTP code available:
- OK: 200
- CREATED: 201
- ACCEPTED: 202
- NO_CONTENT: 204
- BAD_REQUEST: 400
- UNAUTHORIZED: 401
- FORBIDDEN: 403
- NOT_FOUND: 404
- CONFLICT: 409
- INTERNAL_SERVER_ERROR: 500
For example, if you want to perform a check (server side) of the data submitted, you can do it here:
Now, if you try to execute this code:
You’ll have the following error:
Complete document about server scripts can be found here: http://msdn.microsoft.com/en-US/library/windowsazure/jj554226.
Authenticate users in your Windows Store application
A common (and useful) scenario that need to be implemented in some application is the authentication of users. Thanks to Mobile Services, we can use the infrastructure provided by Microsoft and use it in our Windows Store application to allow connection through Live Services, Facebook, Twitter and Google.
First, you need to register your application on the Windows Store. Go to the Dev Center – Windows Store Apps and click on App name:
Type a name for your app in App name, click Reserve app name, and then click Save:
Now, in Visual Studio, right-click on your project in Solution Explorer click Store, and then click Associate App with the Store…:
Once connected, on the screen entitled “Associate Your App with the Windows Store”, select the app that you registered in step 2, click Next, and then click Associate:
Doing this steps allow you to update the application manifest to store the required information.
Now, go to the Live Connect Developer Center and, on My applications tab, and click your app in the My applications list:
Click Edit settings, then API Settings and make a note of the value of Client secret:
In Redirect domain, enter the URL of your mobile service (you can found it on the left your Dashboard) and click Save:
Go back to the Management Portal, click the Identity tab, enter the Client secret obtained from Windows Store, and click Save:
Your Mobile Service and your application are now configured to work with Live Connect: it’s time to add authentication to the app.
Start by download and install the Live SDK for Windows:
In the Project menu in Visual Studio, click Add Reference, then expand Windows, click Extensions, check Live SDK, and then click OK:
Once this is done, add the following code which help you to log on an user using Live Connect:
(Don’t forget to update the Redirect domain URL before to continue).
Finally, add this code that will update the first user of your database:
Unfortunately; if you execute the code, you’ll get another Unauthorized error:
Indeed, once again, the problem occurs because the Users table is configured to allow update only to authenticate users. So, before calling the UpdateUser method, add the following code which will authenticate the user:
Once the Authenticate method is called, the app display a screen asking confirmation to user (for security purpose):
After you’ve been successfully authenticated, the update method can be executed without any problems and entry is updated in database.
Send push notifications to your Windows Store application
Push notifications are another good technique to make your application feel more “Windows 8 compliant”. Using them with Mobile Services is really simple again. If you have done all previous tasks correctly, just go to Live Connect Developer Center and under API Settings, make a note of the values of Client secret and Package security identifier (SID):
In Windows Azure Management Portal, click Mobile Services, click your app and click the Push tab. Enter the Client secret and Package SID values obtained before, and then click Save:
Now, you’re ready to add push notifications to your app. First, we need to get a notification channel and store it in the database so add the following code in App.xaml.cs:
Then, at the top of the OnLaunched event handler in App.xaml.cs, add the following call to the new AcquirePushChannel method:
The channel will be store in the database and, thanks to the technique of dynamic schema, we just need to add the corresponding property to the Users object:
Now, just add a new item in the database, and don’t forget to set its Channel property:
Depending of the type of notification you want to use, you might need to edit the manifest file to specify if the application is capable to receive Toast notifications or not (in our case, it’s yes):
Code in application is finished but, as you can see, we don’t have written any code related to push notifications yet. This is because this part is done on the server side, using the scripts executed during the operations (read/write/delete/update).
Our previous “Insert” script was this one:
We’ll modify it to ask the server to send a push notification when the request is executed:
As you can see, when the request is executed, we send a Toast notification, the number 4 (which accept up to 3 lines of text). Of course, all others kind of notifications (I mean badge and tile) are available if you need/want them. Just save your script and execute your application: if you have performed all the steps correctly, you should received a notification:
Here is a more complex Insert script, which use the Table object to access the number of items in the Users table and push a notification using the value:
Executing this script show a new toast notification:
And values returns by the read method of the Table object is good:
As you can see, Windows Azure Mobile Services is really simple to use and provide a lot of great features. Advanced developers might regrets that they don’t have access to the code of the methods provided but I think it can really useful in some scenarios so don’t hesitate to take a look at it: I’m sure you’ll appreciate it!