xamarin

Happy Halloween with #MonoMac

As a part of this year’s Halloween celebration, I was asked by my lovely family to whip together something interesting to show on the TV – a whole lot of nothing followed by a scary image and a accompanying scary sound, maintaining the mood during the party.

Our TV is connected to a Mac Mini, acting as our media center, so what better thing than writing some MonoMac code to usher the holiday along!

I started out by creating a new Mac (open source) – MonoMac Project in Xamarin Studio, then configuring the main window to have a black background and to cover the entire screen:

Then, I had my wife gather a bunch of scary images and sounds, which I put in the Resources folder of my solution. Having an idea, graphics and sounds, it was now time to add a BackgroundWorker to the MainWindowController, showing a random image and playing a random sound at a random interval. Lots of randoms!

So, how do we actually show an image and play a sound, you ask? It’s easy as pumpkin pie!

We have 20ish images in the scary app, so I defined a constant (100 (percent)) that indicated that we should hide the currently showing image and stop the currently playing sound. The soundPlayer is an instance of NSSound, supporting all sorts of audio file formats, including .aiff, .wav and .mp3.

The last bit – the actual image display, is simply an Image Well (NSImageView) for which I created an outlet in XCode. I set its contents like so:

That’s it! With Xamarin, coding for the Mac is a breeze! Check out the full source code at Github and adjust it to your needs. Happy Halloween!

Announcing v1.2 of AxCrypt for iOS!

The fresh from the oven – and still open-sourced – version 1.2 of AxCrypt for iOS feature separate listings of Received and Transferred documents and better utilization of the larger screens of iPhone 5 and iPads. It also invites the user to send feedback straight from the app and provides additional online resources through its main interface. Being more protective of the user’s information, AxCrypt for iOS now closes its document if you leave the app for whatever reason (say, you get a phone call). Last, but not least, the app should be more stable than ever, having both its file management and resource management looked at a little extra.

Click to go to the source file

v1.2 MainWindowController on an iPhone 5

Click to go to the source file

v1.2 FileListingViewController on an iPhone 5

Click to go to source

v1.2 MainViewController on an iPad

 

In this version of AxCrypt, I replaced my home made progress indicator with the excellent BTProgressHUD from Nic Wise. The Xamarin Component Store made it really easy to browse and locate the component, and putting it into my solution, was a breeze:

I also added the progress HUD to my new WebViewController, complementing the iOS’ Network Activity Indicator. As an extra bonus, if something were to go wrong, the HUD provides a nice ShowErrorWithStatus method, letting the user know what’s going on.

Separation of Concerns

Attempting to make the solution easier to manage, I broke out a lot of functionality from the AppViewController, creating the Theme class (more on that below) and the FileListingViewController, moving the flow control from the view controller to the AppDelegate, where it belongs. The result of this refactoring, was that the AppDelegate now gives you a very nice overview of what the app does, delegating control to various controllers through its application flow. I also broke out the decryption logic out of the PassphraseViewController and into its own DecryptionViewController, reducing the PassphraseViewController to, simply, PassphraseController.

Theming

As I touched on above, I broke out the shared appearance logic in this version out of the MainViewController and into a separate Theme class, coupled with two new MonoTouch.Dialog Elements – ThemedFileElement and ThemedStringElement, both delegating their cell rendering to methods in Theme. This allowed me to get an overview of all theming related code, and helped me decouple the various ViewControllers further (since their Views should match the main view without being dependent on it).

For the full set of commits, see this listing.

I hope you enjoy the new version and that you find it helpful!

 

Building cross-platform mobile applications in Visual Studio, using Xamarin and Azure Mobile Services

For a recent presentation, I developed a ninja locator app, where I demonstrated how to achieve code-reuse and write cross-platform applications in Visual Studio, using Xamarin’s offerings and Microsoft’s Azure Mobile Services. The demo features two applications – one iOS app and one app for Windows Phone 8.

As the user starts either of the apps, they are presented with an option to log into their favourite login provider, whereafter they’re able to share their geographical position with a selected group of friends, thus enabling them to keep track of each other when travelling together, or – in our scenario – keeping track of your fellow consultant colleagues as they roam the streets:

Screenshot_3_24_13_7_52_PM Screenshot_3_24_13_7_53_PM Screenshot_3_24_13_7_54_PM

Screenshot_3_24_13_8_06_PM Screenshot_3_24_13_8_45_PM Screenshot_3_24_13_9_01_PM

When building cross-platform applications, one’s dependency graph is of paramount importance. Luckily, this gets easier all the time, with Portable Class Libraries (PCL) getting a wide-spread adoption. In a cross-platform application, you’ll want as much code as possible in one or several PCLs, creating suitable abstractions for native calls as needed.

In our particular scenario, I achieve code reuse in two ways: First, I’m relying on Azure Mobile Services and am using their client libraries to access their services. The client libraries are available both for Windows Phone and – through Xamarin’s Component Store – for iOS and Android. Secondly, I’ve created a Portable Class Library that contains all interaction with said client library, thus having the Business Logic of this application in one spot. Let’s take a look at the solution explorer in Visual Studio:

Screenshot_3_30_13_9_43_AM-4

 

The solution features five projects – a core project with the shared business logic, a library each for the native implementations (I’ll get back to that later), and a native binary per platform. For the core library, I chose to create a PCL to ensure that I didn’t take dependencies on libraries that were not supported across the board. I configured the PCL like so:

Screenshot_3_30_13_10_02_AM-2

 

… basically picking the top-tier targets, but excluding Xbox (since that severely limits your available APIs as outlined here).

<< Secret dev. challenge!! Writing this blog entry, I identified a number of logical errors/inconsistencies. But instead of fixing them, I thought I’d make a competition out of it! See if you can find them and point them out in the comments! >>

In the core library, I have a set of classes, containing shared logic:
- Configuration: Contains static application settings, such as the Mobile Services Url, its Application Key, shared color settings etc.
- UIDefinitions: Abstract class that utilizes the Configuration to relay native color objects: 
- Ninja: The single model class in this project defining a trackable resource.
- IMobileServiceTable: An abstraction over the MobileServiceTable class provided by the Azure Mobile Services Client API:
- ServiceClient: Our Azure Mobile Services interface. This client contains the shared logic we want to execute on each platform, but is kept abstract so that each platform can provide its own implementation of the Azure Mobile Services client API:

Looking at the Service Client, we see that it offers four extension points: Initialize, two versions of LoginAsync (one for the initial login, and one for repeated logins (“keep me logged in”-scenarios)) and a GetTable method that returns an IMobileServiceTable<T>. Using these extension points, the Service Client can successfully orchestrate its business logic and provide one asynchronous method that:
1) Initializes the native client API
2) Log into the Mobile Service through a selected provider
3) Perform a read operation (more on that later)
4) Perform a write operation (again, more in a bit)
5) Perform a callback, passing the list of fetched records.

Using these abstractions, I ensure that the core library is not dependent on anything else than what the core .NET libraries provide me. It’s worth pointing out that – at the time of writing this demo – a PCL version of AMS was not available. It is now, however that doesn’t help this particular scenario much, since we still need to compile our code with separate compilers.

So, why do we just read the entire ninja table from the service and then insert an arbitrary Ninja entity? Well, let me start off by saying that there’s more going on than meets the eye. An Azure Mobile Service is a service endpoint which act as an intermediary to the data we have chosen to store in the cloud. As such, we can intercept calls to its operations to make it act more like a service. Starting with the read operation, it is defined as such:

As can be seen above, the read operation only selects the entities whose group correspond to the requesting ninja’s group, thus enforcing the business rule that a ninja only are able to see ninjas in its own group.

Similarly, the write operation does more than just inserting an entry: .

The insert operation first adds a LastSeen field to the entry being inserted, that could be used for later housekeeping (removing all ninjas that haven’t been seen for a month or what-not). Then, it modifies the given group name, ensuring it’s always stored in upper-case (to make things easier for the select operation). Finally, if a ninja entry with the given user id already exists in the table, it is updated, rather than inserted anew.

OK, back to the world of C#!

How do we implement the ServiceClient and the UIDefinitions? I have chosen to implement the shared code into platform-specific libraries so that my native clients doesn’t have to worry about any details, but instead can focus on their user interface and interaction logic. Also, I have chosen to create links between the core library’s source file and the native libraries instead of binary references. This is because – although I have no external dependencies – the iOS-library (and app) still needs to be built using the MonoTouch/Xamarin.iOS toolchain. However, creating these links is easy and provides you with the same value, as far as code reuse is concerned, as a binary reference. You, simply, create a folder in your project (calling it “Core” in this case), right-click on it and choose to Add – Existing item and then create a link to your source file:

Screenshot_3_30_13_10_44_AM

Screenshot_3_30_13_10_42_AM-2

 

Adding a link means that there is only one source file in your project, but you have two entry points for them. In our case, it means that we can refer to pre-written code in our libraries. If you prefer, you can also ALT-drag files from one project to another, which creates the same links.

Back to the native implementations:

Starting off with the Windows Phone implementation of UIDefinitions, we can see, that all it does, is to simply convert its’ base class RGB-values to a Color instance:

Unsurprisingly, the iOS counter part does the same, but for Cocoa Touch:

Not much code in either of these, but that is also the main idea – the bulk of the code should reside in the core library, so that you – in essence – have one code base that you are able to test with one set of unit tests.

Moving on to the service client implementations, we see that they – too – are kept thin; basically being a wrapper around the Azure Mobile Services native client API:  

Although the mostly consist of similar code, note that how we in the iOS library need to pass a View Controller whose View is currently visible to the client API when we are calling the Login methods, so that the client library can properly display the required UI to the user.

The GetTable methods of the ServiceClient returns an IMobileServiceTable<T>. It is defined as such for Windows Phone:

… and as such for iOS: .

That’s it! Now, all we have to do, is to consume our respective libraries in our apps. Both the native libraries (NinjaLocator.WindowsPhone.Core and NinjaLocator.iOS.Core) and the apps themselves (NinjaLocator.WindowsPhone and NinjaLocator.iOS) both reference the Azure Mobile Services client library. In the case of Windows Phone, it was added using Nuget:

Screenshot_3_30_13_7_49_PM

 

And in the case of iOS, it was added using Xamarin’s new Component Store:

Screenshot_3_30_13_7_54_PM

Using the libraries we’ve written is as easy as setting the login provider, passing a constructed Ninja entity and then acting on the result set. In the Windows Phone case, we choose to utilize our library as a response to the user navigating to the Page featuring our map control: . We also bind the the foreground color of our Title styles to NinjaLocator.Core.UIDefinitions.ForegroundColor: 

Similarly, in the iOS case, we call on our library to retrieve graphics directives and to invoke the service client:

I hope this gives you an idea of how to think when writing cross-platform applications!

 Scroll to top