Xamarin Certified Once More

I first passed my Xamarin Mobile Certification back in June 2014 but when it came to taking the recertification exam the following year I never quite got around to it. Ultimately it lapsed and I while I was no longer certified I did keep my University subscription running so that I could keep my skills up to date.

During the next year I have to say that I was quite disappointed as there didn’t really seem to be any new content, i.e. no new courses were added as far as I could tell. At the end of that year I was considering not renewing my University subscription, at $1500 it was not exactly a no-brainer.

Then Xamarin was bought by Microsoft and it was included in the MSDN subscription, effectively saving me $2000. With the promise of new content I decided to renew my University subscription – I was $500 up anyway so why not I thought.

Well, as promised, new content is being added, a handful of Azure courses and one on Xamarin.Forms custom renderers so far. That and the fact that I’m currently engaged as a Xamarin developer I thought it would be prudent to refresh my certification. That, coupled with the fact that the Certification and Recertification exams are to change on 15th October this year meant I had a definite timeframe.

Xamarin list 10 courses as being required knowledge for the recertification exam so I spent a couple of weeks reviewing these – making notes and doing the exercises – before embarking on the exam.

The exam itself is 100 multiple choice questions which must be completed within three hours. The pass mark is 80% so not a lot of wiggle room here.

During the exam itself there were a few, shall we say, curve balls – questions which, to me, seemed quite ambiguous. One mentioned an image which was not present resulting in me having to guess the correct answer based on the text – which proved unsuccessful as it turned out – it was in the list of incorrect answers. If I’d missed the 80% by a single mark I don’t think I would have been too happy. As it was I passed with a score of 87% which I’m pretty happy with.

Creating a Simple Modal Dialog Form for Xamarin.Forms

I’ve finally managed to get some time to look at the Smite Scoreboard application that I’m using as a vehicle to dive into Xamarin.Forms (XF) and it’s been a fraught time (see bottom of post).

Between incompatible nuget packages, mismatched Windows and iOS configurations and finding that XF didn’t actually support what I wanted to do I was pretty close to saying, “you know what, to hell with it – I’ll just use the native Xamarin approach instead”.

However, I recalled a video by John Sonmez titled ‘Why does Programming Suck?’ and rolled my sleeves up and dug in again.

Anyway – getting back to the Smite Scoreboard app and what is basically the first User Story.

As a user I want to be able to create a list of players, adding, editing and removing as appropriate.

Now, I know what I wanted to do to implement this story – a simple ListView with an ‘Add Player’ button which would open a modal dialog . The dialog would contain a ‘Player Name’ field with OK and Cancel buttons. Entering a name and tapping OK would add a new row to the ListView. Simple huh.

Well no, not really. While XF does support modal pages, which take up the whole screen, it does not support modal dialogs.

I tried a couple of approaches including the creation of a layout with an Entry field above the ListView which would replace the field I was going to put in the dialog. I had this partly implemented but really didn’t like how it was working and decided to bite the bullet and find a way or make a way!

And this is what I came up with (iPhone on the left, Android on the Right):

Yes – it’s not pretty but it shows me that I can do what I want to be able to do. Making it look nice is a job for later, lets get it working first ?

So, on to the code. I decided to address the initial problem – how do I create a modal dialog (or the impression of a modal dialog) which will allow data entry? I didn’t worry about the ListView integration as I’m happy enough that I can make this work.

I found the key in Charles Petzolds book (which is free) and simply extended his solution to my needs.

Basically he uses an AbsoluteLayout which will hold the ‘normal’ page elements as well as a ContentView which will form an overlay that the user can see through but crucially not tap through. The ContentView is initially loaded with it’s IsVisible property set to false.

The skeleton xaml file looks like this:

<AbsoluteLayout>
  <!-- Normal Page Content -->
  <StackLayout AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
               AbsoluteLayout.LayoutFlags="All">
      <!-- Normal Page Content -->
  </StackLayout>
  <ContentView x:Name="overlay"
               AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
               AbsoluteLayout.LayoutFlags="All"
               IsVisible="False"
               BackgroundColor="#C0808080"
               Padding="10, 0">
      <!-- Overlay -->
  </ContentView>
</AbsoluteLayout>

With this in place I added a button to the StackLayout and bound the Click event to a handler in the code behind which flipped the IsVisible property of the ContentView to True, thus displaying the overlay.

All I had to do now was to create a layout within the ContentView which looked something like a dialog. I came up with this:

<StackLayout Orientation="Vertical"
             BackgroundColor="White"
             HeightRequest="175"
             WidthRequest="300"
             HorizontalOptions="Center"
             VerticalOptions="Start"
             Margin="0,20,0,0" >
 
  <Label BackgroundColor="Black"
         FontSize="18"
         TextColor="White"
         HorizontalOptions="Fill"
         Text="Add a Player" />
 
  <Entry x:Name="EnteredName"
         Placeholder="Player Name"
         TextColor="Black"
         VerticalOptions="CenterAndExpand"
         HorizontalOptions="Center"
         WidthRequest="250" />
 
  <StackLayout Orientation="Horizontal"
               HorizontalOptions="Center">
 
    <Button Text="Cancel" FontSize="Large"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="Center"
                Clicked="OnCancelButtonClicked"/>
 
    <Button Text="OK" FontSize="Large"
                  VerticalOptions="CenterAndExpand"
                  HorizontalOptions="Center"
                  Clicked="OnOKButtonClicked" />
  </StackLayout>
 
</StackLayout>

Wiring the buttons up to flip the IsVisible property of the overlay back to false and, in the case of the OK button, access the entered value was straightforward enough.

using System;
using Xamarin.Forms;
 
namespace SimpleOverlayForm
{
    public partial class Home : ContentPage
    {        
        public Home()
        {
            InitializeComponent();
        }
         
        void OnButtonClicked(object sender, EventArgs args)
        {
            EnteredName.Text = string.Empty;
            overlay.IsVisible = true;
            EnteredName.Focus();
        }
 
        void OnOKButtonClicked(object sender, EventArgs args)
        {
            overlay.IsVisible = false;
            DisplayAlert("Result", 
                          string.Format("You entered {0}", EnteredName.Text), "OK");
        }
 
        void OnCancelButtonClicked(object sender, EventArgs args)
        {
            overlay.IsVisible = false;
        }
    }
}

The result may not be pretty right now but I think it will suffice for the time being until I can get to grips with theming etc.

The full source code can be downloaded from GitHub

It should be noted that I had issues when I attempted to update to the latest version of Xamarin.Forms via Nuget. The version installed with the ‘File > New Project’ did not seem to like the Overlay configuration and while the semi-transparent background was visible the ‘dialog’ controls were not. Only by updating from 2.0.0.6482 (installed by default) to 2.3.1.114 (latest at time of writing) was I able to get this working. But it was not that simple (of course). Version 2.3.1.114 has dependencies on specific version of the Xamarin.Android.Support packages, 23.3.0, but I’d already updated those packages to their latest versions (23.4.0.1). This meant that I had to revert those updates and install 23.3.0 instead.

Unable to deploy Xamarin Android app to GenyMotion emulator

We all know that when you are developing mobile apps there is nothing better than running on an actual device. This is especially useful when wanting to access the device sensors such as GPS and the accelerometer. But we also all know that we have to test against a wider variety of devices than we have in our drawer. That’s where emulators come in – and where the trouble starts in some cases, but I won’t go into Hyper-V here!

Well I’ve been using GenyMotion for a little while and am very happy with it – to the point that I was about to put my hand in my pocket to buy a licence (which I may well still do). However, today I ran into a problem where Visual Studio would refuse to deploy to the emulator.

With the emulator running I selected it as the deployment target in Visual Studio and pressed F5, the build completed successfully and then, just before deployment the emulator disappeared from the list of targets and the deployment failed. I made sure I had the latest version of Genymotion installed (which I did) and that everything else was up to date (which it was).

While I was badgering Xamarin in the forums and via the support email I thought to fire up the Android Debug Bridge (adb) command prompt from within Visual Studio to check what devices the Debug Bridge was actually connected to:

Well, there you have it – it’s a problem with the adb versions ….. wait a minute, how many do I have?

My understanding was that I should only have one – the one that Visual Studio connects to so that it can access the Android devices & emulators. And (I think) I was right on that score – I should only have on running. So what’s with the version clash?

As it happens, Genymotion also ships with a version of the Android Debug Bridge and as it turns out, right now that one and the one shipped with the Xamarin toolset are not the same version.

Comparing versions of adb.exe (from Genymotion and the Android SDK) I found that Genymotion was currently at version 1.0.32 while the Android SDK has 1.0.36.

So what to do?

I suppose I could copy the adb files from the Android SDK into the Genymotion installation – but that frankly smells a bit to me and as it turns out it’s unnecessary.

It is possible, within Genymotion, to set which ADB instance to use for each individual emulator. Simply select the emulator instance and click Settings. Select the ADB tab, click ‘Use Custom Android SDK Tools’ and browse to the SDK location on your system.

Note that the SDK will be in a folder called ‘Android’ within C:Program Files (x86) or C:Users<user>AppDataLocal

Setting this resolved my issues and I am once again enjoying the flexibility of Genymotion and will be buying a licence very shortly.

Insights is dead, long live Insights

In my previous post I sang the praises of Xamarin Insights and explained how it enabled me to locate a bug with the FillLPG for Android application.

At that time Insights as in Preview Release and all Xamarin subscribers has free access to the service, many like myself building it into production applications. We all knew that the time would come when Xamarin would decide that the product was mature enough and take it out of preview and start charging for it. At the recent Evolve conference (which I was not fortunate enough to attend) it was confirmed that existing users would still have access to the service but that plans were still being worked out.

Well, the plans have been worked out and the pricing released – and the news is not great for users like myself. It was hoped that existing users would retain free access, albeit limited, to all aspects of the service – but this is not the case.

The free tier is ‘limited’ to the real-time issue/crash reporting area (as used in my previous post) with all other areas, what I will refer to as Analytics, only available to paid subscribers.

Now, here’s the crux of the issue – the entry level subscription is $199/month. When I received the email I actually had to read it a few times to make sure I was not mistaken – surely they meant $199/year didn’t they?

Well, no – they didn’t. Xamarin have put a price tag on this service is just shy of $2400/year. Now I, and others, see that as a bit of a slap in the face from Xamarin – after all, my usage during the Preview phase has surely been helping with their development of the service. That said, I do still have access to the Issue/Crash reporting part of the service and while there are some limitations being placed on that (log retention etc) this is the area I was making the most use of anyway – so frankly I’ve not really lost much, especially seeing as the Analytics have been offline for sometime now.

Now, FillLPG for Android was using some of the Analytics aspects of the service – I was able to tell how many users had actually logged in and how many had used certain functions such as updating or confirming a station price. That was interesting and has now been lost – in Insights anyway.

In the midst of this maelstrom a number of fellow Xamarin developers have mentioned the Mobile Analytics offerings from Google and Amazon and how they can be incorporated into Xamarin applications. These services are essentially free so I will be investigating them both shortly and intend to post the results in the coming weeks.

Xamarin Insights to the Rescue

So, calling webservices from mobile applications is a solved problem yes? Well, not quite. I’ve been developing desktop and web-based applications for many years now and when it comes to accessing the Internet there are normally only a couple of scenarios to consider, you either have access or you don’t – simple.

However, in the world of mobile it’s not that simple. Mobile devices are just that, mobile, and can move in and out of coverage and between data connections numerous times during an application lifecycle. As mobile developers we know that this happens and we guard against it but checking that we have a valid connection and maybe even that we can ‘ping’ the target resource somewhere out there in the cloud.

Well, I thought I’d done all that within the FillLPG application. I knew, absolutely knew, the format of the content that the webservice would return, which is currently XML, and had suitable methods in place to parse that data. So imagine my confusion when I start receiving error reports like this:

The above is from the Xamarin Insights dashboard which provides me with near real-time crash and issue reporting. There was dozens of records like this in the logs and it was really confusing because I know that the webservice should be returning the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<colours>
  <green>53.9</green>
  <yellow>59</yellow>
</colours>

So, why on earth was the app complaining about a DTD reference?

Well, with a quick configuration tweak I was able to find out. I added the response to the exception data before sending the report to Insights so that I could see what the method was actually returning:

catch (Exception ex)
{
    ex.Data.Add("Thresholds XML", xmlResponse);
    Insights.Report(ex);
    throw;
}

And this was the result…..

This was not the XML is was expecting and explains why the parsing method were choking. But where was this HTML page coming from? I was sure it was nothing to do with the FillLPG website.

Reading through the markup it was clear that this was a login page for a Wifi Hotspot! The device had connected to it but it was not authenticated so the calls to the FillLPG webservice were just being redirected to the login page.

I was able to replicate this scenario by configuring my router to block all traffic to the FillLPG site and then hitting refresh (or any operation that invoked a webservice call). The router then redirected to the ‘This Site Is Blocked’ page and the app crashed!

The fix for this was fairly straightforward and I’ll put another post together for that, but I was already checking the Status Code of the Response and assumed, wrongly as it happens, the a value of 200 indicated a successful operation.

I was also using the ConnectivityPlugin and checking for an active connection AND that the site was reachable – but for some reason these tests were passing even though the router was actively blocking connection to the webservice.

So Xamarin Insights has saved the day for me again. There is no way I would have located this issue without it and while it is still ‘In Preview’ it is proving to be an invaluable tool for tracking down even the most elusive of bugs.

Xamain.iOS – Mapping & My Location

So, you’ve created your MKMapView in your view controller and instantiated a CLLocationManager which you’ve called RequestWhenInUseAuthorization() on. Everything tells you that this should be enough so that when the Map loads and requests the current location iOS will prompt the user whether they want to allow the device to share it’s location – but the prompt is never displayed and neither is the location.

I watched a Xamarin University course on iOS Mapping (IOS 230) and when I followed along with the exercise using a new project (not the one provided in the course materials) the location was still not displayed. But, when I ran the Completed project in the course materials I was prompted to allow location sharing and when I clicked ‘Allow’ the location was displayed. Looking at the code it did not seem to be any different from mine (but of course it had to be).

I finally found the missing element – it was a missing property in the Info.plist file. The Xamarin course materials had it but it was not mentioned during the course itself.

The good news is that it is super simple to fix this:

  • Open Xamarin Studio
  • Open Info.plist
  • Using the tabs at the bottom of the window – select ‘Source’
  • Click the ‘Add new entry’ text at the bottom of the table and add a new String property as follows:
    • Property: NSLocationWhenInUseUsageDescription
    • Value: Show map location
  • Save the file

That’s it – run the app again and (as if my magic) you will be prompted to allow access to your location and (if you click Allow) your location will be displayed.

You can download the (very basic) solution used above by clicking here.

Note that the solution was created using Xamarin Studio 5.9.5 (build 9) and Xamarin.iOS 8.10.3.2 (Business Edition)

Fixing Xamarin COMPILETODALVIK build error in VS2013

After clearing the decks of some other freelancing projects I’ve had on the go recently I’ve been able to get back to looking at my FillLPG application that I’ve decided to rewrite from scratch using Xamarin.

It was time to start working on the UI and with the new Xamarin.Forms library promising cross platform UI development I thought I’d create a quick project to compare the old approach with the new (and maybe write blog post or two about it). However, I ran into problems very quickly and thought I’d pass on my experience.

I decided to create a Solution with Android, iOS and Portable Class library projects. The application would open with a Map (Google Maps on Android and Apple Maps on iOS) and would have a menu to open a standard login page. Now, in order to display a map on Android you need to reference the Google Play Services library and make some changes to the AndroidManifest.xml file to configure the required permissions etc – and this is where the problems started.

I’d created the Solution, added the Android and PCL projects and used the Component Store to include the Google Play Services component. When I attempted to build the solution I was greeted with a rather unhelpful error message.

At this point I’ve not written a line a code – but the solution won’t build!

The issue appeared to be caused by the presence of the Google Play Services component and it’s worth bearing in mind that this comes in the form of a Java .jar file (why wouldn’t it – that’s the native language of Android after all). Well, as part of the compilation a Java process is spun up and the .jar is loaded and (presumably) compiled. During this process the Java process has an amount of memory allocated to it but the default size (whatever that happens to be) appears to be too small and an OutOfMemoryException is thrown.

After quite a lot of Googling I found two solutions that worked for me;

The first approach involved simply adding a new Environment Variable to increase the Java heap size on a machine-wide basis, i.e. for all Java processes that run on your system.

Variable: _JAVA_OPTIONS (the leading _ is deliberate)

Value: -Xmx1g

This may be what you want but if, like me, you split your development between multiple systems are are working in a team of developers then this may not be the optimal solution.

The second solution requires opening up the .csproj file for the Android project and making a small adjustment. This has the benefit of being part of the project so, if checked into source control is will be set for all development systems that it is checked out on.

Open up the .csproj file into an XML editor (if you’re doing this in Visual Studio then you’ll need to unload the project first) and locate the JavaMaximumHeapSize element. Then update it as follows:

<JavaMaximumHeapSize>1G</JavaMaximumHeapSize>

Both of these options increase the heap size to 1GB which should be more than enough.

With that fixed I can get back to the Xamarin.Forms sample project and get back to work.

iOS Limitations and Xamarin Mobile Certification

In my previous post I mentioned that I was looking at developing a cross platform, mobile application to schedule SMS messages.

Well I’m afraid that took a bit of a backseat for a couple of reasons.

Firstly I became aware that the action of sending a text message with no input from the user was not possible using iOS. While I have not investigated this fully it did make me pause for thought – what was the point of starting this cross-platform project if it was not going to work on the iPhone? Well, if the information I have is correct, there is no point …… unless I just demonstrate that writing apps for Android does not necessarily mean Java! So, this project is still on the cards – just not at the top of the deck.

The second reason for me not starting the development was that I have been studying via the Xamarin University and am happy to say that I am now Xamarin Mobile Certified :-).

The training took the form of a number of live web session presented by experienced Xamarin developers. Over the course of a couple of months I ‘attended’ many required sessions to allow me to sit the certification. This consisted of 150 questions which must be answered in under three hours. The pass mark was 80%. With my knowledge of iOS a little on the shaky side (being an Android user at heart) I was a bit hesitant about taking the full exam (I could have just taken the Android flavour) but I thought ‘what the hell’.

The exam did highlight to me that I need to do some more work on iOS but a pass is a pass and now that I have my evenings back I will be moving forward with the migration of the FillLPG application to Xamarin. Initially targeting Android but developed using all I have learnt to ensure that the maximum amount of code can be reused for an iOS version.

The code for FillLPG will unfortunately not be made available but I’m sure that there will be more than a blog post or three coming out of the development so stay tuned.

Getting Started with Xamarin – a Pet Project

In previous posts I have mentioned that 2014 will be my ‘Year of the Mobile‘ and that Xamarin (which will allow me to develop for Android, iOS and Windows Phone using C#) will be my weapon of choice.

As with all undertakings such as this I needed a few pet projects to work on, something that more closely resembles a real world application than some contrived examples that you find in some books and web tutorials (that’s not to say that all book and web tutorials are created equally).

I already have my FillLPG application, written in Java, which I am moving to C# via Xamarin but I wanted something that integrated with the standard phone functionality, e.g. phone calls, SMS. I also wanted it to be something that I could make use of myself – scratching my own itch if you will.

I’ve had a number of ideas but you need to walk before you can run so I’ve opted for an SMS Scheduler app. Yes, I know that this has already been done both as an integrated feature in full blown messaging applications and standalone utility apps (which is what mine will be) but that’s no reason not to use it as an learning exercise. The requirements are such that it will provide a number of opportunities for investigation into operations such as:

  • Contact Selection (taking into account some contacts may have multiple phone numbers)
  • Date/Time Pickers
  • Data storage (probably file based – SQLite is a bit heavy weight for this in my opinion)
  • Scheduling of the SMS ‘jobs’
  • Sending of the SMS itself
  • Logging and Notifications

As with previous ‘tutorials’ I’ll provide full source code at each step and the final project will also be on GitHub.

As I am predominantly an Android user I will be developing for that platform first but with a mind to sharing as much code as is practical.

2014 – The Year of the Mobile?

I’ve always said that when it comes to software development, you have to “pick your fights” – it’s just not possible to keep up with the ever-changing technologies. We only have so much time to spend learning new technologies and techniques so it is important to carefully consider what to focus on and what to let pass us by.

When it comes to Mobile development I have released a simple, native, Android app which was written using my somewhat rusty Java skills. At the time of writing the app is installed on around 5000 devices (if Google Play is to be believed). Since it’s original release I have addressed bugs and added a few requested features but I found it to be a bit of a struggle due to Java not being my main development language – but I simply don’t have time to bring my Java skills up to the required level. As for iPhone/iPad development I have joked that “I don’t have enough time left in my life to learn Objective C “.

So when I heard about a product which will allow developers to create native applications for Android & iOS (and Windows Phone) using C# (my language of choice) I was naturally intrigued.

The Xamarin ‘framework’ provides a set of bindings which sit above the Android and iOS APIs  allowing C# code to be compiled into native applications for the target platform. Moreover, it is possible to share large chunks of code between platforms thus reducing maintenance and duplication.

I’m currently in the process of completely rewriting the FillLPG application using Xamarin and C# with a view to reusing as much code as possible in order to ease the process of developing a version for iOS. It’s not been an easy process by any means – every new technology has it’s learning curve and fair share of bugs and issues, but because I’m using C# – indeed I’m also using Visual Studio 2013 – at least I’m not starting from zero.

The process of rewriting the FillLPG application has taught me a lot but as the old adage goes ‘you don’t know what you don’t know’ so I’ve also enrolled onto the Xamarin University course at the end of February and all things being equal I should be certified by the end of March.

So I declare 2014 to be my year of the mobile. I will still keep as current as I can with web development but the mobile market cannot be ignored and with a tool such as Xamarin I’m now in a position to take it on.