Saturday, March 5, 2016

Easy App Theming with Xamarin.Forms

Beautiful user interfaces sell mobile apps, and designing a successful user experience for your app is a great first step for success. But what about all of the little details that combine to create a fantastic design, such as colors and fonts? Even if you create what you believe to be the perfect design, users will often find something to dislike about it.

Why not let the user decide exactly how they would like their app to look? Many popular apps have taken this approach. Tweetbot has light and dark modes and the ability to change fonts to find the one that works best on the eyes during late-night Twitter sessions. Slack takes user customization to the next level by allowing users to customize the entire theme of the app through hexadecimal color values. Properly supporting theming also brings some tangible benefits to code, such as minimizing duplicated hardcoded values throughout apps to increase code maintainability.

Xamarin.Forms allows you to take advantage of styling to build beautiful, customizable UIs for iOS, Android, and Windows. In this blog post, we’re going to take a look at how to add theming to MonkeyTweet, a minimalistic (we mean it!) Twitter client, by replicating Tweetbot’s light and dark mode as well as Slack’s customizable theming.
Introduction to Resources

Resources allow you to share common definitions throughout an app to help you reduce hardcoded values in your code, resulting in massively increased code maintainability. Instead of having to alter every value in your app when a theme changes, you only have to change one: the resource.

In the code below, you can see several duplicated values that could be extremely tedious to replace and are ideal candidates for using resources:
1
2
   
<Label Text="First Name" BackgroundColor="White" TextColor="Blue" FontSize="24" />         <Label Text="First Name" BackgroundColor="White" TextColor="Blue" FontSize="24" />
<Entry BackgroundColor="White" TextColor="Blue" />

Resources are grouped together and stored in a ResourceDictionary, a key-value store that is optimized for use with a user interface. Because a ResourceDictionary is a key-value store, you must supply the XAML keyword x:Key for each resource defined:
1
2
3
   
<Color x:Key="backgroundColor">#33302E</Color>
<Color x:Key="textColor">White</Color>
<x:Double x:Key="fontSize">24</x:Double>

You can define a ResourceDictionary at both the page and app-level, depending on the particular scope needed for the resource at hand. If a particular resource will be shared among multiple pages, it’s best to define it at the app-level in App.xaml to avoid duplication, as we do below with the MonkeyTweet app:

1
2
3
4
5
6
7
8
9
10
11
   
<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MonkeyTweet.App">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="backgroundColor">#33302E</Color>
            <Color x:Key="textColor">White</Color>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Now that we have defined reusable resources in our application ResourceDictionary, how do we reference these values in XAML? Let’s take a look at the two main types of resources, StaticResource and DynamicResource, and how we can utilize them to add a light and dark mode to MonkeyTweet.
Static Resources

The StaticResource markup extension allows us to reference predefined resources, but have one key limitation: resources from the dictionary are only fetched one time during control instantiation and cannot be altered at runtime. The syntax is very similar to that for bindings; just set the property’s value to “{StaticResource Resource_Name}”. Let’s update our ViewCell to use the resources we defined:
1
2
   
<Label Text="{Binding Name}" FontSize="Medium" FontAttributes = "Bold" TextColor = "{StaticResource textColor}" LineBreakMode="NoWrap"/>
<Label Text="{Binding Text}" FontSize="Small" LineBreakMode="WordWrap" TextColor = "{StaticResource textColor}"/>

Dynamic Resources

StaticResources are a great way to reduce duplicated values, but what we need is the ability to alter the resource dictionary at runtime (and have those resource updates reflected where referenced). DynamicResource should be used for dictionary keys associated with values that might change during runtime. Additionally, unlike static resources, dynamic resources don’t generate a runtime exception if the resource is invalid and will simply use the default property value.

We want MonkeyTweet’s user interface to be able to switch between light and dark modes at runtime, so DynamicResource is perfect for this situation. All we need to do is change StaticResources to DynamicResources. Updating our resources on-the-fly is super easy as well:
1
2
   
App.Current.Resources ["backgroundColor"] = Color.White;
App.Current.Resources ["textColor"] = Color.Black;

Users can now switch between a light and dark theme with the click of a button:
Monkey Tweet with a dark and light theme applied via dynamic resources.
Introduction to Styles

When building a user interface and theming an app, you may find yourself repeatedly configuring controls in a similar way. For example, all controls that display text may use the same font, font attributes, and size. Styles are a collection of property-value pairs called Setters. Rather than having to repeatedly set each of these properties to a particular resource, you can create a style, and then simply set the Style property to handle the theming for you.
Building Custom Styles

To define a style, we can take advantage of the application-wide resource dictionary to make this style available to all controls. Just like resources, each style must contain a unique key and target class name for the style. A style is made up of one or more Setters, where a property name and value for that property must be supplied. The TargetType property defines which controls the theme can apply to; you can even set this to VisualElement to have the style apply to all subclasses of VisualElement. Setters can even take advantage of resources to further increase maintainability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   
<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MonkeyTweet.App">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="backgroundColor">#33302E</Color>
            <Color x:Key="textColor">White</Color>

            <Style x:Key="labelStyle" TargetType="Label">
                <Setter Property="TextColor" Value="{DynamicResource textColor}" />
            </Style>
            <Style x:Key="backgroundStyle" TargetType="VisualElement">
                   <Setter Property="BackgroundColor" Value="{DynamicResource backgroundColor}" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

We can apply this style by setting the Style property of a control to the name of the style’s unique key. All properties from the style will be applied to the control. If a property is explicitly defined on the control that is also part of a referenced style, the property set explicitly will override the value in the style.

1
   
<Label Text="{Binding Name}" Style="{DynamicResource labelStyle}" FontSize="Medium" FontAttributes = "Bold" LineBreakMode="NoWrap"/>

Our style is a dynamic resource behind the scenes, so they can be altered at runtime. I’ve created a custom page that allows users to enter their own hexadecimal colors to theme MonkeyTweet thanks to Xamarin.Forms resources and styles:

Feb 03, 2016 15:34
Conclusion

In this blog post, we took a look at theming applications with the Xamarin.Forms’ styles by theming our MonkeyTweet application to have a customizable, user-defined theme. We only just scratched the surface of styling; there are lots of other cool things you can do with styling, including style inheritance, implicit styling, platform-specific styling, and prebuilt styles. Be sure to download the MonkeyTweet application to apply your own theme and see just how easy it is to build beautiful, themed UIs with Xamarin.Forms!

Getting Started with Azure Mobile Apps’ Easy Tables

Every front end needs a great backend. This is true now more than ever in today’s connected world, where it’s extremely important to have your data with you at all times, even if you are disconnected from the internet. There are tons of great solutions available for Xamarin developers including Couchbase, Parse, Amazon, Oracle, and, of course, Microsoft Azure. Microsoft Azure Logo
In the past, we looked at the brand new Azure Mobile Apps, which gives you a full .NET backend providing complete control over how data is stored and retrieved for your mobile apps. What if you need a backend right now with minimal setup? That is where Azure Mobile Apps’ brand new Easy Tables come in. How easy are Easy Tables? So easy that you can add backend data storage to your app in as little as 15 minutes! The best part is that if you’ve used any Azure Mobile Services or Azure Mobile Apps, you’ll feel right at home.

Keeping Track of Coffee Consumption

If you follow me on social media or have seen me present, then you know I love coffee; I’m drinking one as I type this! That’s why I thought that for this post I would build a cross-platform app to help me keep track of just how many coffees I’m consuming each day. I call it “Coffee Cups”, and we’ll be building it throughout this post. Here’s the final version in action:

Creating a New Azure Mobile App

Inside of the Azure portal, simply select New -> Web + Mobile -> Mobile App, which is the starting point to configure your Azure Mobile App backend.
Creating a new Mobile app in the Microsoft Azure portal.
When selecting Mobile App in Azure, you will need to configure the service name (this is the URL where your backend web app/ASP.NET website will live), configure your subscription, and set your resource group and plan. I call Seattle home, so I’ve selected the default West US locations:
Blade configuration for a new mobile app.
Give Azure a few minutes to deploy your mobile app, and once deployed, the Azure portal will bring you directly to the configuration screen with the settings tab open. All of the settings we’ll adjust can be found under the Mobile section:
Easy tables section within Settings blade.

Add Data Connection

We can’t have a backend for our mobile apps without a database. Under the Data Connections section, select Add, and then configure a new SQL database as I’ve done below:
Adding a new database to our mobile app with Easy Tables.
Make sure that you keep Allow azure services to access server checked for your mobile app to allow services to properly connect to the database server. Also, be sure to keep your password in a secure place as you may need it in the future.
Click OK on all open blades and Azure will begin to create the database for us on the fly. To see the progress of database creation live, click on the notifications button in the upper-righthand corner:
Creating data connection.
When the data connection is created, it will appear in the Mobile Apps data connections blade, which means it’s time to set up the data that will go in the new database.
Available data connections for our mobile app

Adding a New Table

Under Mobile settings is a new section called Easy Tables, which enable us to easily set up and control the data coming to and from the iOS and Android apps. Select the Easy Tables section, and we’ll be prompted with a big blue warning asking us to configure Easy Tables/Easy APIs:
Add a new table.
Since we already setup the database, the only thing left to do is Initialize the app.
Instructions for adding a new table by connecting database and configuring App Service to use Easy Tables.
After a few moments, the app will be fully initialized so we can add our first table of the database named CupOfCoffee. If you are adding Azure Mobile Apps to an existing application, this table name should match the class name of the data you with to store. The beautiful part of Easy Tables is that it will automatically update and add the columns in the table dynamically based on the data we pass in. For this example, I’ll simply allow full anonymous access to the table, however it is possible to add authentication with Facebook, Twitter, Google, Microsoft, and other OAuth login providers.
Add a table dialog.

Adding Sync to Mobile Apps

With our backend fully set up on Azure, it’s now time to integrate the Azure Mobile SDK into your mobile apps. The first step is to add the Azure Mobile Apps NuGet package that’s named Azure Mobile SQLiteStore. This package sits on top and includes the Mobile Services Client SDK to connect to our backend and adds full online/offline synchronization and should be added to all application projects. For example CoffeeCups is written using Xamarin.Forms, so I added the NuGet to my PCL, iOS, Android, and Windows projects:
Azure Mobile SQLiteStore in NuGet.

Initialize the Azure Mobile Client

Add the Azure Mobile Client SDK initialization code in the platform projects. For iOS, the following code must be added to the FinishedLaunching method of the AppDelegate class:

For Android, add the following to the OnCreate method of your MainActivity:


The Data Model

It’s now time to create the data model that we’ll use locally to display information, but also save in our Azure Mobile App backend. It should have the same name as the table that we created earlier. There are two string properties required to ensure the Mobile Apps SDK can assign a unique identifier and version in case any modifications are made to the data. Here is what the CupOfCoffee model looks like:

Notice the model has a UTC DateTime that will be stored in the backend, but also has two helper properties for a display date and time. They are marked with a JsonIgnore property and will not be persisted in the database.

Accessing Mobile App Data

It’s now time to use the Mobile App SDK to create a MobileServiceClient that will enable us to perform create, read, update, and delete (CRUD) operations that will be stored locally and synchronized with our backend. All of this logic will be housed in a single class, which for this app is called “AzureDataService” and has a MobileServiceClient and a single IMobileServiceSyncTable. Additionally, it has four methods to Initialize the service, get all coffees, add a coffee, and synchronize the data with the backend:


Creating the Service and Table

Before we can get or add any of the data we must create the MobileServiceClient and the SyncTable. This is done by passing in the URL of the Azure Mobile App and specifying the file in which to store the local database:


Synchronize Data

Mobile devices often lose connectivity, so it’s vital that our app continue to function properly even in low or no connectivity environments. Azure makes this extremely easy; with just a few lines of code, Azure automatically syncs our local database and the backend when connectivity is reestablished:


Retrieving Data

The IMobileServiceSyncTable offers a very nice asynchronous and LINQ queryable API to get data from our backend. This can be done to grab all of the data or filter it down by a property, such as an Id. In this instance, we’ll simply synchronize our local data with the backend before fetching all cups of coffee, sorted by the date:


Inserting Data

In addition to getting all of the latest data, we can insert, update, and even delete data that will be kept in sync between devices.

Now from my mobile app I can simply create my AzureDataService and start querying and adding coffees through the day, all in under 70 lines of code.
Completed Coffee Consumption app built with Xamarin and Azure Easy Tables.

Learn More

In this post we’ve covered setting up the basic Azure Mobile App’s Easy Tables to perform CRUD and sync operations from our mobiles apps. In addition to this, you have full access to the service code and can customize it right from the portal (using the edit script option in Easy Tables and even custom scripts with Easy APIs). Be sure to check out all of the additional services provided by Azure Mobile App Services such as authentication and push notifications on the Azure portal. You can try out Azure Mobile Apps by downloading this Coffee Cups sample from my GitHub or by testing pre-built samples\ apps on the Try App Services page.

Source: https://blog.xamarin.com/getting-started-azure-mobile-apps-easy-tables/?utm_source=newsletter&utm_medium=email&utm_content=easy-tables&utm_campaign=march2016&mkt_tok=3RkMMJWWfF9wsRolu6%2FAZKXonjHpfsX56eUrX6G%2Bi4kz2EFye%2BLIHETpodcMT8tmN6%2BTFAwTG5toziV8R7nCKc1q1c0QXBfr