Azure Mobile Service with Windows Phone

Are you a Windows Phone or Windows Store App developer?
If yes, then this is for you.

When we create an app, we try to store as much possible data on the phone. But with the advancement of data services, it is now easy to store the data on the services. But the question comes as What is Azure Mobile Services and Why do we need it?

What is Azure Mobile Services and Why do we need it?
As stated in the documentation, it allows to add a cloud backend to your app in minutes with the following features:

  • Host a .NET or Node.js web API with 24×7 monitoring and management
  • Use single sign-on with Active Directory, Facebook, Twitter, and Google
  • Push notifications to individual users and dynamic audience segments
  • Store data in SQL, Table Storage, and MongoDB
  • Access on-premises systems, Office 365, and SharePoint
  • Use cloud-based sync to build apps that work offline

How to create Azure Mobile Service? Please note we are going to make use of the .Net backend and Visual Studio.

Step 1: Open the Azure Management Portal and sign in with your Microsoft Live Account.

Step 2: From the left pane, select the third item, Mobile Services. Here you will see your existing Mobile Services, if any.

Step 3: We will try and create the Mobile Services from within Visual Studio.

Step 4: Open Visual Studio and click on File -> New -> Project

AMS1

Project Template

Step 5: Select Cloud from the Left Pane and then select Azure Mobile Service on the right and click OK

Step 6: Once the project is created, you will notice that the project is mostly making use of Web API. This will create all the methods required for CRUD operations.

AMS2

Sample Files

Step 7: In the project, you will get a demo template for a Todo Application. You can go ahead and create Models and Controllers as per your choice as it is done for the Todo Sample.

Step 8: After adding the respective Models and Controllers, you can go ahead and publish the Mobile Service on cloud.

Step 9. But wait, if you want to debug it, you can always do that before publishing. Remember this is a normal MVC Web Application. So our old friend from Keyboard still holds good. So let’s go ahead and press F5

Step 10: If everything goes well, then you will see a page with a smiley. Something like this.

Azure Mobile Service

Azure Mobile Service

Step 11: Now that the Mobile Service is created, you can always play around with it after clicking on the try it out link.

Step 12: It presents with a clean and simple UI showing all the methods available for Rest Calls.

API Documentation

API Documentation

Step 13: If you want to test the Rest Calls, you can click on the links and it will easily allow you to test all the operations. But we are here to go to the next step in connecting this service with a Windows Phone App.

Step 14: Assuming that you have an existing Windows Phone App or you have just created a new Windows Phone App, we will go ahead and open the project.

Step 15: In order to make use of our new Azure Mobile Service, there are some pre-requisites. You have to install Windows Azure Mobile Services package using NuGet.

Step 16: Once installed, we need to add just one line and our App is connected with the Mobile Services. For this open the App.xaml.cs and add this line after the

public partial class App : Application
{
    // Use this when trying to debug locally
    public static MobileServiceClient MobileService = new MobileServiceClient("http://localhost:23846/");
    // Use this when deployed on cloud
    //public static MobileServiceClient MobileService = new MobileServiceClient("", "");
    ...
}

Step 17: Now that our App is ready to make use of Azure Mobile Service, we have use this Code to access Azure Mobile Service

public partial class MainPage : PhoneApplicationPage
{
    private MobileServiceCollection items;
    private IMobileServiceTable speakerTable = App.MobileService.GetTable();

    // Get list of items from the database using AMS
    private async void RefreshCandidateItems()
    {
        items = await speakerTable.ToCollectionAsync();
        ListItems.ItemsSource = items;
    }

    // Insert item to database using AMS
    private async void InsertTodoItem(Speaker speaker)
    {
        await speakerTable.InsertAsync(speaker);
        items.Add(speaker);
    }
    ...
}

Step 18: You can now publish the Azure Mobile Service and get the Application Key.

Step 19: Update the Azure Mobile Service Client in the App and update the Mobile Service Url and Application Key.

Step 20: You App is now successfully connected with the Azure Mobile Service.

Happy Coding!!! 🙂

TechEd India 2014 Recap – Migrating your WP8 Silverlight App to WP8.1 RT

I am very happy to say that I got the chance to present a session on Migrating your WP8 Silverlight App to WP8.1 RT. It was mostly based on the post which I had written earlier. Though, this time I had a good audience who have already tried migrating and faced certain kind of issue. In this post, all I am going to do is push the top 5 questions which I had got there.

Q1: What is the need to migrate? or Why should I migrate?
Though this is the very basic question, but this was one of the most asked questions. Whenever, we here words like Migrating or Upgrading, we start to get a bit scared. Well the only reason is that we as developers want our app to have lots and lots of features and we don’t want to go back one step and then upgrade our code to get the same or even older kind of look. But what we forget is that, deep down when the architecture and platform are released and our apps are already migrated then we can have various advantages. I can name a few:

  • Page Transitions are now native
  • Universal App readiness
  • Debugging

Well, the most important of them all is Universal App readiness. We would love to push our apps to multiple platforms. The only reason we are not doing still is because we don’t have the time. But if you think about it, migrating from WP8 to WP8.1 RT already does more than half of your job. Once migrated, you get the advantage of WP8.1 and most of your code along with UI can be Shared in a SharedProject.

Q2: Any important points to keep in mind?
There are various important things to keep in mind. However, they all vary based on scenarios or the type of App you are migrating or even building new. Let’s jot down a few:

  • Scalability: Not talking about Cloud but Scalability in terms of pushing the same app in multiple platforms.
  • Code Reusability: Want to push your app for Windows Store? Well, the moment you migrated your app, your code is now ready to be shared across for Windows Store App. But what if, you want to make use of Xamarin and push the same code for Android and iOS. You can always extract the methods which can work with common .Net code like Models, HttpClient  etc and push them to a PCL (Portable Class Libraries). Once you do this, your code can easily be shared across platforms.
  • Mobile App and not Web App: Keep in mind that the App you are building is for Mobiles and not Web. When you think like that, then you will always think about the Data consumptions and speed. It is always better to make small Web calls than make a single call and wait for over a minute to get everything. Because, that way user will have to wait for a minute and you do not want to test their patience.
  • Activity Indicator: Activity indicators are anything like Progress Bar on the SystemTray or a simple Progress Image. The only reason to make use of this is to notify the user that something is happening. It’s like telling them “Please be patient”.

Q3: How often to update the App?
This is something that needs to be taken care by the developer. The general way of dealing this is by adding some or the other feature and keep your app updated. Rather than trying to release all the features at once, one should try releasing features coded properly without any issues. That way the user will appreciate your app as well.

Q4: What should I do for plug-ins not available for WP8.1 RT?
This is a tricky situation. It depends on what kind of plugin you have made use of. But still, when you reach a point where the plugin is not available, you can always tweak your design. If the design suits your need, then your app size will go down more because the plugin might be of some big size doing various kind of work but you were making it use for a single feature. Now that your design is tweaked, and your code is yours, you can always add new features to it without worrying about anything.

Q5: Once migrated, should I continue updating the WP8 App?
This is totally up to you. You are the developer. If you think that you have the time and energy to maintain the various version of the same app then there is no issue in that. However, if you are not able to then with a single update, you can notify the user that this will be a last update to this app because now the app is being migrated to WP8.1 and they should consider upgrading their Phone to WP8.1. Also, ensuring them of new features will get your users to come to your app. In case, you think there is a major bug in the WP8 app, then you can always fix that issue.

I believe the QnA had many more questions which were technical, but they were mostly based on my earlier post. This QnA is mostly theoretical where I just talk about the experience and sharing some knowledge based on my experience. In case, you have any questions, feel free to reach out.

Happy Coding!!!

Isolated Storage in WP8 and WP8.1 RT

We have been using IsolatedStorageSettings in our Windows Phone 8 App from a long time.

IsolatedStorageSettings is basically a Key-Value pair mechanism used to store small amounts of data. The data stored are mostly settings or some smaller data related to user or the application. IsolatedStorageSetting has been an integral part of the app’s life cycle since it has always been used to store and retrieve the data.

With the advent of Windows Phone 8.1, we no longer have access to IsolatedStorageSettings class and it’s namespace when creating RT based app. So keeping this in mind, I am writing this post to assist developers who are trying to migrate their app or creating a new WP8.1 RT based app.

From my previous post at ProgramFreaks, I am fetching some of the examples which will make it easier to understand the use of IsolatedStorage. Let’s look at the code below for WP8-Silverlight

// Method to Save data in IsolatedStorageSettings
private void SaveData()
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    //Assuming you have the variable declared in App.Xaml.cs.
    if (!settings.Contains("userName"))
    {
        settings.Add("userName", App.UserName);
    }
    else
    {
        settings["userName"] = App.UserName;
    }
    settings.Save();
}
// Method to Load data from IsolatedStorageSettings
private void LoadData()
{
    if (IsolatedStorageSettings.ApplicationSettings.Contains("userName"))
    {
        //Assuming you to have the variable present in App.Xaml.cs
        App.UserName = IsolatedStorageSettings.ApplicationSettings["userName"] as string;
    }
}

In the above code, we have two methods which are called in the event handlers Application_Deactivated, Application_Closing and Application_Launching, Application_Activated.

On thing to notice is that we always try to store the data as part of ApplicationSettings. Now we will try to do the same in WP8.1 RT.

Let’s look at the code below and see the defference.

private void SaveData()
{
    ApplicationDataContainer settings = Windows.Storage.ApplicationData.Current.LocalSettings;
    //Assuming you have the variable declared in App.Xaml.cs.
    settings.Values["userName"] = App.UserName;
}
// Method to Load data from IsolatedStorageSettings
private void LoadData()
{
    ApplicationDataContainer settings = Windows.Storage.ApplicationData.Current.LocalSettings;
    if (settings.Values.Count <= 0) return;
    {
        //Assuming you to have the variable present in App.Xaml.cs
        App.UserName = settings.Values.ContainsKey("userName")? settings.Values["userName"] as String : String.Empty;
    }
}

In the above code, we have used Windows.Storage.ApplicationData.Current.LocalSettings instead of System.IO.IsolatedStorageSettings.ApplicationSettings. The working principle is almost the same. This also makes use of Key-Value pair mechanism like Dictionary. Although, for RT there is a storage limit in the ApplicationDataContainer.

The name of each setting can be 255 characters in length at most. Each setting can be up to 8K bytes in size and each composite setting can be up to 64K bytes in size.

I am working on a sample to show this. It will be available soon.

26-Aug-2014: Update: Sample is done. You can get the sample at https://github.com/anubhavranjan/WPIsoStorage

Migrating WP8 Silverlight based App to WP8.1 RT

From past one week I was working on migrating my app TV Shows Reminder. To be frank, my findings are, On the XAML side, I can say I have made almost 50% changes where as in the Code Behind, it was almost 40% changes. So a message to all the Devs, just go ahead and start migrating your apps. It doesn’t take a lot to migrate.

TV Shows Reminder is an App that works with the site http://reminders.programfreaks.com where you can search for your favorite TV Shows and then subscribe it right after you are logged in. The site will then send you an email whenever a new episode for the subscribed show is out!

Before migrating, you should list down all the features that your current app has. This will allow you to keep track of the features that you need to migrate. So let’s see all the features that I can think of before migrating.

  • Isolated Storage
  • Social Authentication
    • Facebook
    • Google
    • Microsoft
  • Live Tiles
    • Primary Tiles
    • Secondary Tiles
  • Background Agent
  • Lock screen Notification
  • Web APIs
  • WP Toolkit (Hub Tiles)
  • Appointments
  • System Tray
  • Message Box
  • Device Properties

Since my project architecture contained PCL, it was easier for me to migrate most of my code.

In order to migrate my app from Silverlight to RT, we tend to create a new WP 8.1 RT project.
Once we create the project, for making our task easier we simply start copying and start renaming the files. What we always forget is that the Xaml makes use of the code behind and sometimes we miss updating the references for the class file. Namespaces and class names are very important in this aspect as you entire application is dependent on them. In case you are making use of ReSharper, please suspend it at the moment. Since it confuses the developer with improper suggestions and warnings.

In order to achieve this, I added a new Pivot App (Windows Phone) Project.

Project Template in VS2013

Project Template in VS2013

Once, you add this project, it will automatically create a blank page which will help you in understanding the UI changes that are needed for your App to work properly. Also, you can reuse the newly created page for faster development.

In case you are copying and pasting your .xaml or the .cs code, make sure to update your class references properly.

Let’s look at some of the changes I had done for my app to run. Basically these changes were nothing but updating the class names and their respective namespaces. We will look at some of them below.

My App was also making use of the HubTiles which is present in the WPToolkit. Because the platform is now WinRT, I had to update my layout to display some other controls like Telerik Controls. Thankfully, Telerik provides free controls to MVPs and it has some controls which can be used as a replacement for my HubTile. Otherwise, I will have to make use of some images and text over it.

Also, my app has social authentication using Facebook, Google and Microsoft. In the current scenario, for Facebook , I was making use of the Facebook SDK. This SDK was solely built for Silverlight based apps. Since, all of the providers support OAuth, so I have switched all my authentication to make use of the WebAuthenticationBroker. It makes it easier to migrate the authentication for WP8.1 RT.

As discussed above, I am making use of the IsolatedStorageSettings to store the user’s data for the App. Since, in RT, IsolatedStorage is not available, I had to make use of the LocalSettings and had to store the images in the App Area.

For the live tiles and secondary tiles, I had to update my entire code since tiles in RT have completely different set of implementations than on Silverlight.

I am yet to migrate my Background Agent since it has completely different set of implementations in RT.

Let’s conclude here and look at some of the points to remember

  • Make sure you have updated your namespace and class names.
    • If missed, can give errors in InitializeComponent()
    • Many members of page would not be available
  • It is always better to reuse the xaml given in the new project than just copy pasting the entire code from earlier project.
    • Allows you to make use of the correct markup
    • Can easily view the similarity between the RT and Silverlight markup, thus allowing safe pasting in the xaml
  • The App.xaml.cs has different methods in RT than Silverlight. When  copying methods, it is better to copy the method definition to the appropriate method.
  • Some event names have got changed in the RT, make sure to update them in respective places.
  • Many event handlers in Silverlight were using the base class EventArgs which in RT is replaced by child class RoutedEventArgs as the parameters
  • Don’t forget to check the capabilities section to update the required capabilities.
  • In case of third party controls, check their WinRT counterpart to see if you can make use of those controls in WP8.1 RT.