-
Nokia Developer Champion
I don’t like to talk too much about my self, I prefer that the passion I put into the posts I write speaks for me (at least, this is what I hope!). But I’m so happy about this new award I’ve received that I would like to share it with everybody else and, especially, with the communities and the people I have the pleasure and the luck to cooperate with.
This award is gifted by Nokia and it’s called Nokia Developer Champion: its philosophy is similar to the Microsoft MVP program’s one, since it recognizes the effort spent to support people and communities about developing apps for Nokia devices (in my case, we’re talking about Windows Phone development). This is my profile page on the Nokia Developer Portal.
I would like to thank you everybody that made this possible and now… let’s continue my job and commitment about Windows Phone, hoping to be part of this amazing group for a long time
in
-
Having fun with Azure Mobile Services – Integrating with Windows 8
In the previous post we’ve introduced Azure Mobile Services and we learned how to configure and create them. If you’ve followed all the steps of the previous post, you should have now a service up & running that allows to interact with a table called Comics, that we’ve created to store information about our favourite comics.
In this post we’ll see how to interact with this service from a Windows 8 application: as I’ve anticipated in the previous post, Windows 8 is the easiest platform to integrate with our service, since Microsoft has released a specific SDK for Windows Store apps. This SDK basically hides all the web requests that, under the hood, are exchanged with the service and automatically serialize and deserialize our data.
The first thing, indeed, is to download the SDK from the following link. After you’ve installed it, it’s time to open Visual Studio 2012 and create a new Windows Store app (you can use the blank template, in this post we’ll simply learn how to communicate with our service, we won’t develop a real application with full graphic).
After installing the SDK you’ll find a library in the Windows – Extensions section of the Add new reference dialog: it’s called Windows Azure Mobile Services Managed Client and you simply have to double click on it to add it to your project.
As I already anticipated, the app will be very simple: no graphic, no user experience, just two buttons, one to store data and one to retrieve it and display it in a ListView. So let’s start by adding them in the XAML of our MainPage:
<StackPanel> <Button Content="Insert data" Click="OnAddNewComicButtonClicked" /> <Button Content="Show data" Click="OnGetItemButtonClicked" /> <ListView> <ListView.ItemTemplate> <DataTemplate> <StackPanel Margin="0, 20, 0, 0"> <TextBlock Text="{Binding Title}" /> <TextBlock Text="{Binding Author}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackPanel>
The code should be simple to understand: with the first button we’re going to store some data in our service; with the second one we’re going to retrieve it and displaying it in the below ListView, which simply shows, one below the other, the title and the author of the comic.
###
Let’s prepare the application
Before starting to do some operation we’ll need to create the class that maps the data we have on our service: since we’ve created a Comic table, we’re going to create a Comic class with, as properties, the columns of our table. Here is the code:
public class Comic { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } }
The second thing to is to initialize the client we’re going to use to do operations with the service: we can do it, for example, in the constructor of our MainPage, by declaring it at class level (so that every method we’re going to write will be able to use it). Initializing the client is very simple:
MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/", "your-application-key");
You’re going to use the class MobileServiceClient (it’s inside the Microsoft.WindowsAzure.MobileServices namespace) that, when it’s initalized, requires two parameters: the first one is the address of your service (the one we have chosen when we have configured our service), the second one is the secret application key. To get your key, simply open the Azure Management Portal and, in the home page of your Azure Mobile Service, choose the option Connect to an exisiting Windows Store app. In the window that will appear you will find, at step 2, the same code I’ve just written, but already filled with the correct data of your service. Just copy and paste it in your application and you’re done!
###
Insert some data
Now that we have the client available, we can start to see how to insert some data in our servie, by managing the event handler of the first button we’ve defined in the XAML. Here is the code:
private async void OnAddNewComicButtonClicked(object sender, RoutedEventArgs e) { MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/", "your-application-key"); Comic comic = new Comic { Title = "Batman Year One", Author = "Frank Miller", }; await client.GetTable<Comic>().InsertAsync(comic); }
First we create a new Comic object, with a title and an author. Then, using the MobileServiceClient object, we get a reference to the Comic table and, in the end, we call the InsertAsync method by passing as parameter the comic object we’ve just created. This operation is awaitable (it can require some time to be executed, since it involves communications with a service over Internet), so we’re going to use the magic keywords async (in the event handler’s signature) and await (before the method, in order to await that the operation is ended before moving on).
If you go back to the Azure Management Portal and you access to your service’s dashboard, in the Data section you’ll find that the new item has just been added.
Using dynamic data to add columns to the table
If you remember what we did in the previous post, after we created our Comics table we’ve added some columns using the Azure management tool. At the same time, I also told you that this step wasn’t really necessary, thanks to a feature called dynamic data, that is able to add new columns to the table by simply adding an item that contains new properties other than the ones already stored.
Let’s see how to use it: first add a new property in your Comic class called Publisher; we’re going to use it to store the publisher’s name of the comic.
public class Comic { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public string Publisher { get; set; } }
Now let’s edit the button’s event handler to add a new Comic object: this time we’ll set also the Publisher’s property of the project before inserting it.
private async void OnAddNewComicButtonClicked(object sender, RoutedEventArgs e) { MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/", "your-application-key"); Comic comic = new Comic { Title = "Watchmen", Author = "Alan Moore", Publisher = "DC Comics" }; await client.GetTable<Comic>().InsertAsync(comic); }
Run this code and you’ll see that, despite the fact that you’re adding a Comic object with a property that is missing in the table, you won’t get any exception. Go back to the Azure dashboard and, in the Data section, you’ll find that a new column called Publisher has been added: obviously, you’ll find a value only for the item you’ve just added, while the previous one will have an empty value.
According to what we’ve learned about the dynamic data we could have avoided, in the last post, to create the columns using the Azure management tool: we could have simply inserted a Comic object with the Title and Author properties and the service would have done everything for us.
###
How to work with the data
At this time it shouldn’t be too hard to understand how to get the data we stored on our service: by using the GetTable<>() method we’ve just seen we get a reference to the table. This table object (which type is **IMobileServiceTable
**) allows to perform operations using LINQ, so that we can filter the data before actually making the request. To get the real data we can use one of the available methods: **ToListAsync()** or **ToEnumerableAsync()**, that returns a collection of the objects stored in the table. Here are some examples of the operations you can do:
private async void OnGetItemButtonClicked(object sender, RoutedEventArgs e) { MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/", "your-application-key"); //get all the comics List<Comic> allComics = await client.GetTable<Comic>().ToListAsync(); //get all the comics which publisher is DC Comics List<Comic> filteredComics = await client.GetTable<Comic>().Where(x => x.Publisher == "DC Comics").ToListAsync(); //get all the comics ordered by title List<Comic> orderedComics = await client.GetTable<Comic>().OrderBy(x => x.Title).ToListAsync(); ComicsList.ItemsSource = allComics; }
In these three examples you can see how to retrieve all the data, how to retrieve filtered data (all the comics with a specific publisher) and how to apply an order criteria to the results.
And if we want to manipulate the data already stored in the table? We can simply use:
- the UpdateAsync method to update an item. We simply have to pass to the method the update object and, using the unique identifier (in our example, the Id property of the Comic class) the already existing item will be overwritten by the new one.
- the DeleteAsync method to delete an item. In this case, we simply have to pass to the method the object to delete: the method will take care to find it in the table and to remove it.
We’ve reached our goal… for the moment
In this post we’ve seen how to integrate our new Azure Mobile Service with a Windows 8 application. In the next post we’ll do the same with a Windows Phone application: things won’t be so easy as we’ve seen in this post, due to the temporary lack of a SDK for Windows Phone, but don’t worry, we’ll have fun anyway
in
-
Having fun with Azure Mobile Services – The setup
Azure Mobile Services is one of the coolest feature that has been recently added on top of Azure. Basically, it’s a simple way to generate and host services that can be used in combination with mobile applications (not only Microsoft made, as we’ll see later) for different purposes: generic data services, authentication or push notification.
It isn’t something new: these services are build on top of the existing Azure infrastructure (the service is hosted by a Web Role and data is stored on a SQL Database), they’re just simpler for the developer to create and to interact with.
In the next posts I’m going to show you how to use Azure Mobile Services to host a simple service that provides some data and how to interact with these data (read, insert, update, etc.) from a Windows 8 and a Windows Phone application. These services are simply REST services, that returns JSON responses and that can be consumed by any application. As you will see, interacting with Windows 8 is really simple: Microsoft has released an add-on for Visual Studio 2012 that adds a library, that can be referenced by a Windows Store app, that makes incredibly easy to do operations with the service.
Windows Phone isn’t supported yet (even if I’m sure that, as soon as the Windows Phone 8 SDK will be released, a library for this platform will be provided too): in this case we’ll switch to “manual mode”, that will be useful to understand how to interact with Azure Mobile Services also from an application not written using Microsoft technology (like an iOS or Android app). In this case, we’ll have to send web requests to the service and parse the response: as we’ll see, thanks to some open source libraries, it won’t be so difficult has it sounds.
Before starting to write some code, let’s see how to configure Azure Mobile Services.
Activating the feature
Of course, the first thing you’ll need is an Azure subscription: if you don’t have, you can subscribe for the free trial by following these instructions.
Then, you’ll need to enable the feature: in fact, since Azure Mobile Services are in a preview stage, they aren’t enabled by default. To do that, you’ll need to access to the Azure Account Management portal and open the Preview features section: you’ll see a list of the features that are available. Click on the Try now button next to the Mobile Services section, confirm the activation and… you’re ready! You should receive within a few minutes a confirm mail and the page should display the message You are active.
Creating the service
Now that the feature is enabled, we can start using it from the new Azure Management portal: press the New button and choose Create in the Mobile Services section. In the first step of the wizard you’ll be asked to choose:
- A name for the service (it will be the first part of the URL, followed by the domain azure-mobile.net (for example, myservice.azure-mobile.net)
- The database to use (actually, you’ll be forced to select Create a new SQL database, unless you already have other SQL Azure instances).
- The region where the service will be hosted: for better performance, choose the closest region to your country. </ul>
The next step is about the database: in the form you’re going to set some important options.
- The name of the database.
- The server where to store the database (use the default option, that is New SQL Database server).
- Login and password of the user that will be used to access to the database.
- The region where the database will be hosted: for better performance, choose the same region that you’ve selected to host the service. </ul>
And you’re done! Your service is up and running! If you go to the URL that you’ve chosen in the first step you’ll see a welcome page. This is the only “real” page you’ll see: we have created a service, not a website, specifically it’s a standard REST service. **As we’ll see in a moment, we’ll be able to do operations on the database simply by using standard HTTP requests.
Let’s create a table
To host our data we need a table: for this example, since I’m a comic addicted, we’ll create a simple table to store comics information, like the title, the author and the publishing year. Creating the table is the only part a little bit tricky: the Azure Mobile Service interface, as we’ll see later, provides built in functions just to create a table, without providing functionalities to change the schema and add new columns.
The first thing is to create the table by choosing the service with just created in the portal (in the Mobile services section), switching to the Data tab and pressing the Create button. You’ll be asked to give to the table a name and to set the permissions: by default, we’ll give full access to any application that has been authorized using the secret application key.
Now it’s time to move to the specific Azure tool to manage our SQL instance: in fact, by default, the table will contain just an Id field, already configured to be an identity column (its value will be auto generated every time a new row is inserted) and to act as the primary key of our table. In the management panel, click on the SQL Databases tab; you’ll find the database you’ve just created in the previous wizard. Click on the Manage button that is placed below: if it’s the first time you connect to this database from your connection, the portal will prompt you to add your IP address to the firewall rules: just say Yes, otherwise you won’t be able to manage it.
Once you’ve added it, you’ll see another confirmation prompt, that this time will ask you if you want to manage your database now: choose Yesand login to the account using the database credentials you’ve created in the first step.
Now you have full access to the database management and we can start creating our table: click on the **database connected to your service (look for the name you’ve chosen in the second step of the wizard), then click on the **Design tab and choose Create new table. If you’re familiar with databases, it should be easy to create what we need: let’s simply add some columns to store our information.
- A title, which is a varchar with label Title
- An author, which is another varchar with label Author </ul> There’s another way to add new columns: by using dynamic data. When this feature is enabled (you can check it in the Configure tab of your mobile service, but it’s enabled by default), you’ll be able to add new columns directly from your application, simply by adding new properties to the class that you’re going to use to map the table. We’ll see how to do this in the next post.
As we’ve seen before, if we call the URL of our service (for example, http://myapp.azure-mobile.net) you’ll see a welcome page: to actually query our tables, we have to do some REST calls. To get the content of a table, we simply need to do a GET using the following URL.
http://myapp.azure-mobile.net/tables/Comic
If everything worked fine, the browser should return you a JSON response with the following format:
{"code":401,"error":"Unauthorized"}
This is the expected behavior: Azure Mobile Services require authentication, to avoid that everyone, just with the URL of your service, is able to access your data. By receiving this kind of error we have a confirmation that the table has been successfully created: otherwise, we would have received an error saying that the requested table doesn’t exist.
{"code":404,"error":"Table 'Comic' does not exist."}
Now that we have setup everything we need, we are ready to write some code: in the next posts we’ll see how to develop a Windows 8 and a Windows Phone application that is able to connect to our service.
- Login and password of the user that will be used to access to the database.
- The server where to store the database (use the default option, that is New SQL Database server).
- The database to use (actually, you’ll be forced to select Create a new SQL database, unless you already have other SQL Azure instances).
in
- A name for the service (it will be the first part of the URL, followed by the domain azure-mobile.net (for example, myservice.azure-mobile.net)
subscribe via RSS