Portable Class Library is truly a savior when you write code for multiple Microsoft platforms. This means that more code can be shared between different platforms. The latest news, which came in mid-June, is that now there is also support for Azure Mobile Services in PCL.

In the following post, I will implement famous Azure Mobile Services Todo example in the PCL with two clients, Windows 8 and Windows Phone 8.

I have created three projects:

  • Windows 8 Client
  • Windows Phone 8 Client
  • Portable Class Library

I added support for Azure Mobile Services in the Portable Class Library with NuGet. (Search for Azure Mobile Services.) I will also add support for PCL in both the Windows 8 and Windows Phone 8 project. Why? It is because I will extend the example with authenticating against Twitter. To do so requires that you log on and these user interfaces are in the parts of Azure Mobile Services that are platform dependent.

clip_image002

Preview of the new Managed Client for Windows Azure Mobile Services, by Johan Lannstra.

I create a new class called AzureMobileServices in the PCL project.

public class AzureMobileServices
{
    private IMobileServiceTable<TodoItem> todoTable;
    public  MobileServiceClient MobileServiceClient = new MobileServiceClient(
            "https://xxxx.azure-mobile.net/",
            "xxxx"
    );

    public AzureMobileServices()
    {
        todoTable = MobileServiceClient.GetTable<TodoItem>();
    }

    public async Task<TodoItem> InsertTodoItem(TodoItem todoItem)
    {
        await todoTable.InsertAsync(todoItem);
        return todoItem;
    }

    public async Task<ObservableCollection<TodoItem>> RefreshTodoItems()
    {
        try
        {
            return new ObservableCollection<TodoItem>(await todoTable
                .Where(todoItem => todoItem.Complete == false).ToEnumerableAsync());
        }
        catch (MobileServiceInvalidOperationException e)
        {
            return new ObservableCollection<TodoItem>();
        }
    }

    public async Task UpdateCheckedTodoItem(TodoItem item)
    {
        await todoTable.UpdateAsync(item);
    }
}

In this class, I implement all calls to Azure Mobile Services. This is enough if you do not need authentication. However, to support this I have exposed the MobileServiceClient as a public field.

I instantiate this class in the App.xaml.cs file for both Windows 8 and Windows Phone 8. I do it here so I can reach it from the rest of the app.

Here is the code from the Windows 8 app.

sealed partial class App : Application
{
    public AzureMobileServices AzureMobileServices { get; set; }

    /// <summary>
    /// Initializes the singleton application object.  This is the first line of authored code
    /// executed, and as such is the logical equivalent of main() or WinMain().
    /// </summary>
    public App()
    {
        this.InitializeComponent();
        AzureMobileServices = new AzureMobileServices();
        this.Suspending += OnSuspending;
    }
…
}

Then I call methods on this class when I need to communicate with Azure Mobile Services.

Here is code showing how to save a new TodoItem.

private AzureMobileServices _azureMobileServices = ((App)Application.Current).AzureMobileServices;

private async void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    var todoItem = new TodoItem { Text = TextInput.Text };
    await _azureMobileServices.InsertTodoItem(todoItem);
    Items.Add(todoItem);
}

Authentication

To implement this I create a method with the name Authenticate in both Windows 8 and Windows Phone 8 class MainPage. This method is called when the page is first displayed.

This is the Windows 8 implementation.

private MobileServiceUser user;
private async Task Authenticate()
{
    while (user == null)
    {
        string message;
        try
        {
            user = await _azureMobileServices.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.Twitter);
            message = string.Format("You are now logged in - {0}", user.UserId);
        }
        catch (InvalidOperationException)
        {
            message = "You must log in. Login Required";
        }

        var dialog = new MessageDialog(message);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();
    }
}

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    await Authenticate();
    RefreshTodoItems();
}

Download the full example here