Getting Started with Xamarin.Forms and Azure Mobile App Service

Jeff Hopper .NET, Azure, Cloud, Development Technologies, Mobile, Tutorial, Xamarin 2 Comments

Attention: The following article was published over 6 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

Earlier this month my friend Ryan introduced us to Getting Started with Xamarin Forms and Prism. In that post, Ryan started a mobile application to display blog posts which he called SimpleBlog.

In this article, I would like to continue that demonstration by adding a back-end server to persist and share these blogs. This will be accomplished using Azure’s Mobile App Service which falls within its free tier services.

Yes, you did read that right: you can spin up an Azure account and have access to try out many of Azure’s features. For instance, the example I am going to walk you through today can be hosted indefinitely without costing you anything, and to that, you could add nine more web, mobile, or API services. See https://azure.microsoft.com/en-us/free/ for more information.

But wait, there’s more. Are you looking for additional resources including limited access to training services like Xamarin University and Pluralsight? Check out https://www.visualstudio.com/dev-essentials/ where there are even more free goodies available for your learning and experimenting pleasure.

There is no way I am going to be able to cover all the possibilities available in an Azure Mobile App service, much less what Azure has to offer. My intent in this post is to help “whet your appetite” on the possibilities by giving a quick overview of just two great frameworks that play great together: the Microsoft.Azure.Mobile.Client mobile framework tied to an Azure Mobile Apps Service.

As mentioned above, I would like to jump off of Ryan’s SimpleBlog demo. This has been forked at https://github.com/HopperTech/SimpleBlog. The master branch of this repo has remained the same as where Ryan left off in his post. The additions outlined below have been applied to the develop branch. Feel free to clone this repo and follow along.

Persisting the SimpleBlog

Last we saw of SimpleBlog, it was displaying a list of Blogs on both Android and iOS devices using the shared SimpleBlog .NET Standard library. The blogs had been hardcoded in the MainPageViewModel.cs class to help facilitate the rapid development of the UI without needing to spend time waiting on a server response. Now that SimpleBlog looks just right, let’s take this application to the next level and retrieve these blogs from a hosted service. Doing so will open up a lot of potentials, such as sharing blogs across users or adding a web application for our editor and administrators.

Note: If you are following along at home, the following steps assume that you have already created an Azure account. Reference the above links if you need help in doing so.

Azure Mobile App Service

Creating the Azure Mobile App Service

Let’s jump right in and create our new Azure Mobile App Service. In order to accomplish this there are several paths available to us. But, to keep this simple, we’ll use Azure’s Mobile Apps Quickstart. This can be accomplished by:

  • Navigating to http://portal.azure.com
  • Choose “Create a Resource”
  • Enter “Mobile Apps Quickstart” in the Search the Marketplace
  • Select the found Mobile Apps Quickstart.
  • Tap the “Create” button

You should now see the Mobile App Create form that needs to be filled out. Following is a brief description of each field.

  • App Name: The App name needs to be globally unique across azurewebsites.net. This means you will need to choose something different than KH-SimpleBlog.
  • Subscription: Unless you have a reason to do otherwise, keep the default value here.
  • Resource Group: This is the Resources collection this service should be part of. Unless you have already created other Resource Groups you will want to create one now.
  • App Service Plan / Location: The App Service plan is the PaaS VM that can host one or more applications. As shown in the following image you can choose the Free pricing tier that allows up to 10 web, mobile, or API apps. See the following image for the options I chose for creating the App Service Plan for this demo.
  • Application Insights: Application Insights is “an extensible Application Performance Management (APM) service for web developers”. This topic is well outside the scope of this blog but is well worth your time to investigate further.

Once each selection has been made, you should see just the Mobile App blade (the leftmost blade displayed above) where you can choose to Create the Mobile App Service. Azure will take a few minutes to perform its magic to create and configure everything needed to host our blogs.

While waiting, you could open the notification bell in the upper-right corner and watch the proverbial “paint dry”. Once completed, you can either click on the resource link in the notification pop-up or select “All Resources” in the menu on the left.

From here, choose the Name: KH-SimpleBlog Type: App Service

Reviewing What Has Been Created

Our new Mobile App Service is now open which allows us to dig through the different options.

One thing to note is that a Mobile App Service is pretty much the same as a Web App or an API App. The only differences are within some configurations and the code that has been deployed for us. At this point, we could deploy our own hand-rolled API or open Visual Studio and create an Azure Mobile App.

For this rapid prototype, we will continue with the Mobile App Service Quickstart that we just created. This option has deployed an instance of the Node.js application https://github.com/azure/azure-mobile-apps-node, which gives us access to Azure’s Easy Table and Easy API tools built right into the portal. Which you can see if you scroll down the menu and select “Easy Table”.

You should now see the following:

Notice the warning at the top-right of the page. One of the things the QuickStart has configured for us is an embedded SQLite database. As pointed out in the warning, this configuration is not recommended for production, but will work great for our rapid prototyping purposes.

The good news is that this is easily changed either by clicking through the “Click here to create an SQL Azure data connection”, or navigating to the “Data connections” option. That will be left as an exercise for the reader.

Creating the Blogs Table

Now, for the main reason this service has been created: adding a persistence layer for our Blogs. If you have been playing along at home, or are just very observant of the above image, you will notice there is a todoitem table already created for us. This is another byproduct of using the Mobile Apps Quckstart.

For full disclosure, you could scroll up the menu to the Quickstart option. From here, there is download access to the code base for several types of mobile applications, including a Xamarin.Forms example that does not include Prism. These are all todo applications, the new hello world introduction app, and have been configured to read and write to the todoitem table. Feel free to get sidetracked and poke around in those applications. Absolutely no offense taken.

Getting back to where we were, oh yeah: creating a table to persist our Blogs. This can be accomplished by clicking “Add” at the top of the Easy tables blade.

This will present the following form, which for this exercise, will only require us to fill in the Table Name field. Permissions is outside the scope of this post, but it is encouraging to see the ability to apply permissions for all methods. We will definitely need to come back to this.

Now that our table is created, we can begin adding columns from our Blog model. As hinted above, Easy tables will create the API to perform CRUD actions against this table. All we will need to do is match the Blog table schema with our application’s Blog model. To facilitate this, I have arranged each screen side by side.

In the Blog table schema (on the left) the top five columns have been created as part of the Easy Table. These will be used by the Microsoft.Azure.Mobile.Client package to manage CRUD actions between the client and the server, including offline data synchronization. That will need to be a topic for another day.

Below these default columns, the three Blog model fields have been added. If you’ve been playing along at home, you’ll notice that there were actually four properties in our original Blog model. The original CreateDate property logically matches with the Easy table’s createdAt, just a slight difference in naming. Adding a Newtonsoft’s JSON.Net JsonProperty attribute, we are able to create the binding between the property and the column. The Id property has also been added to the Blog model. To preserve the naming convention in each environment, the JsonProperty attribute has also been added.

Okay, to level set with what we’ve done so far:

  • Created an Azure Mobile App Service
  • Created an Easy table Blog schema, which also provides an API to manage these records
  • Updated the Blog model to match the Blog schema.

Updating the Application Logic

Now let’s add the client-side logic to tie all of this together.

Microsoft.Azure.Mobile.Client package

The first thing is to add the Microsoft.Azure.Mobile.Client nuget package to all projects in our solution. This will provide the client-side access to the Azure Mobile Apps service, whether using the Node or .NET flavors. And as we saw earlier, our client can be written using Swift, Objective-C, Java, Cordova, or C#. Now that is a fair amount of flexibility.

One word of warning, I did experience some weird build errors in the Android project after adding this project. These errors were corrected by upgrading the Xamarin.Forms package to version 3.0.

Repository

To encapsulate our access to the App service, let’s first create a simple repository.

SimpleBlogRepository.cs
using Microsoft.WindowsAzure.MobileServices;
using SimpleBlog.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SimpleBlog.Services
{
    public class SimpleBlogRepository
    {
        MobileServiceClient _client;
        IMobileServiceTable<Blog> _blogTable;

        public SimpleBlogRepository()
        {
            this._client = new MobileServiceClient("https://kh-simpleblog.azurewebsites.net");
            this._blogTable = _client.GetTable<Blog>();
        }

        public async Task<List<Blog>> GetBlogsAsync()
        {            
            var blogs = await _blogTable.ToListAsync();

            return blogs; // blogs.ToListAsync().Result;
        }
    }
}

Some points of interest:

  • The MobileServiceClient will handle all of our interactions with the server. So this class is initialized with the Azure Mobile Service App domain we created earlier. In this walkthrough we are using “https://kh-simpleblog.azurewebsites.net”
  • This client now has access to any table defined within our Mobile App Service domain.
    Any CRUD operation can now be applied against the blogTable reference. In this example, we are only retrieving all blogs, but below is a link to reference possible operations that can be performed.
  • So that we do not block the UI thread we have wrapped this in an async/await call.

Dependency Injection

Now that the repository has been defined, it can be made available through Prism’s dependency injection. This can be configured in the App.xaml.cs file in the RegisterTypes method.

App.xaml.cs
        ...
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<NavigationPage>();
            containerRegistry.RegisterForNavigation<MainPage>();
            containerRegistry.RegisterForNavigation<Blog>();
            containerRegistry.RegisterSingleton<SimpleBlogRepository>();
        }

Reading Blogs

Now that the repository is available through DI, we can access through our constructors. SimpleBlog has been hard-coded a list of blogs in the MainPageViewModel.cs. This can easily be transitioned to using the new SimpleBlogRepository.

MainPageViewModel.cs
	private _simpleBlogRepository; 
public MainPageViewModel(INavigationService navigationService, SimpleBlogRepository simpleBlogRepository)
            : base(navigationService)
{
            …
_simpleBlogRepository = simpleBlogRepository;      //store a reference to our repository    
}

        	public override async void OnNavigatingTo(NavigationParameters parameters)
        {
            Blogs = await _simpleBlogRepository.GetBlogsAsync();

            base.OnNavigatingTo(parameters);
        }

Some points of interest:

  • The Blogs are being updated in the OnNavigatingTo so that we can take advantage of async/await. This way we do not block the UI thread.
  • A reference to the repository needs to be added in order to call the repository outside of the constructor while still using Prism’s DI.

Now when we run our application again, voilà . . . we see absolutely nothing.

Oh yeah, the Azure Blog table has not yet been populated with any records. Sadly, while you can view and delete records through the Easy tables interface, there are not any direct means of adding or editing records.

But, there are several options available to us. We could delete the table and import a csv file with a heading row for our three columns. Which honestly could be used as a viable option for some use cases, such as providing a daily MLS listing. Another option for our POC would be to create some records in our SimpleBlogRepository if none currently exist. I have added that bit of logic into the SimpleBlogRepository.cs in the repository.

Wrapping It Up

There are many directions that could be explored to improve the SimpleBlog application. We have only scratched the surface of potential available to use.

We could switch to IMobileServiceSyncTable< Blog >, which would provide for offline synchronization of these articles. Or we could provide a means for our users to create new blogs from within the application. We could even create a web application for our editors to create, modify, and manage content that can be pushed down to our users.

We also definitely need to consider security. This quick example REST API has left our table open for anybody to write and update records. Thinking about it, I’ll close that hole for now by just disabling the permissions on those methods. At a later point we could easily add authentication / authorization to only allow access to authenticated users.

Hopefully, this article has demonstrated how easy it is to add a server back-end to your mobile application and has piqued your interest in learning more about what is available using Xamarin.Forms, Prism, and Azure Mobile Services. These are just a few of the resources that have been helpful in my research for this article.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments