Blog

Another Xamarin Forms app about to hit the App/Play Stores

Smite is a wooden garden game based on a Northern European game and played around the world.

If you think of a combination of skittles and boules you’ll be pretty much there – but not quite, there are a few twists.

Each player will take turns to throw a wooden ‘smitter’ at 10 numbered wooden pins, arranged in a similar manner to those in 10 pin bowling.

  • Knock over a single pin and you score the number on that pin.
  • Knock over two or more pins and you score the number of pins that fall; knock over four pins and you score four points.
  • Before the next players turn the pins are stood back up but remain where they fell, they are not returned to their original location.
  • Miss all the pins three turns in a row and you are ‘smitten’ and out of the game.
  • If any players score exceeds 50 points they are returned to 25..!
  • When a player scores exactly 50 points the game will end when the round completes – all remaining players will complete the round. There can be more than one winner!

It sounds simple but when the pins start to spread out the game becomes much harder – I can personally attest to this, as can many members of my family..!

Keeping score is not difficult but games can go on longer than expected and you soon find yourself scrabbling around for scraps of paper to continue the scoring.

Having run out of paper on many occasions I decided to create a simple app to keep score and apply the simple rules above. The ability to take player photos to use as avatars and ensuring that game state is saved when the app is backgrounded (lunch and dinner frequently interrupt a ‘a few quick games of Smite’) add some nice functionality and coding challenges.

Written using Xamarin.Forms there are Android and iOS versions of the app with around 95% of the code being shared – only a couple of small platform specific classes were required.

I currently have a few testers looking at the release candidate version – with a few more being recruited at the upcoming Smite World Championships.

It’s a pretty straightforward app and nowhere near as complicated as the likes of my other apps,ย FillLPG or Motorhome Stopover, but I fully expect to have a few bugs to fix and features to add.

Online Tool of the Month – ExtensionMethod.Net

OK – not really a tool, more of a resource but I hope you will like it.

As you may know my language of choice is C# and since version 3.0 developers have been able to add functionality to existing types without actually modifying the type itself by using Extension Methods.

We are all used to the String methods such as ToUpper() and ToLower() – but what if you wanted to truncate a string to a specified length and apply a ‘…’ suffix?

Well, you could of course write a private method in the class you want to perform this operation or create a static class with static methods to do the job for you. Both perfectly valid ways of achieving the same result but extension methods are somewhat cleaner in my opinion (if you ignore the ‘they are’t object oriented’ argument).

Now you can read all about Extension Methods using the above link but as with things like RegEx, there is not always a need to reinvent the wheel and the ExtensionMethod.Net website is basically a collection of user submitted methods which address common needs (or even the not so-common ones).

The site isn’t limited to just C# methods either – there are submissions for VB, F#, Swift, Kotlin and Javascript.

You can search or filter the methods by language, target object (e.g. System.String) and author.

Once you have found something you like you can view the code and, most of the time, see usage examples.

From there it is just a quick copy/paste to bring the code into your project – where you will more than likely want to tweak it slightly (because that’s what we do right?) and you’re good to go.

N.B. If you like the sound of the ‘Truncate’ method I mentioned above, you can find it here.

Online Tool of the Month – MakeAppIcon

I’ve been developing a couple of Xamarin applications recently and while the default application icons are better than nothing you will of course need to replace these with custom graphics before going live.

Now I’m no designer so I’ve used Fiverrย to find suitable resources for a number of previous projects (websites, logos and menu icons) and have done so for these mobile apps. In return for about ยฃ10 I received nice, clean icon designs which I’d never have been able to put together myself – ยฃ10 well spent in my opinion as I can spend the time coding instead ๐Ÿ™‚

Anyway, having the design is one thing – creating the required assets for each platform is another. Android and iOS both require numerous versions of the image with specific dimensions. Android requires these to be placed in a specific folder structure while iOS requires specific file name formats for the assets to be used correctly.

Creating these manually is a bit of a pain and time consuming – surely there must be an easier way!

Enter MakeAppIcon which makes creating these assets a breeze. Assuming you have a suitable source file, I use a 1024×1024 png file, this handy tool will create all the possible permutations required for Android and iOS – many of these you may not need but at least you have them if you need them.

When you goto the site it’s not that easy to see what you need to do – there are ads for their paid products and the free service does not jump out at you. Currently you need to turn your attention to the panel with the toaster.

Select your source image and it will start to process it – which can take a few minutes (this is a free service remember). When it has finished you will be asked for your email address so that it can send you your icons.

Now, I normally don’t like doing this but on this occasion I decided to go ahead – and I can confirm that I’ve not received any SPAM etc as a result (not even to push their paid products!).

After a few minutes an email will arrive containing icons from ldpi to xxxhdpi for Android and every size for iOS from 20×20 to 83.5×83.5 (@1x, @2x and @3x as appropriate). There’s even Play Store and iTunes artwork.

All you have to do now is import them into your project and your are good to go ๐Ÿ™‚

Xamarin Gotcha – Care needed when taking a photo with the Xam.Plugin.Media plugin

I’m currently writing a Xamarin.Forms scoreboard application which, as part of the functionality, allowed each player to take a photo which would be displayed within their ‘player tile’. I made use of the Xam.Plugin.Media plugin developed by James Montemagno to implement this feature and everything was working like a charm. I then parked the project for a couple of months while I attended to some paying development and training.

When I returned to the project I looked at the outstanding items on my backlog and decided to implement the saving of game state when the app is backgrounded. This was pretty straightforward and I had it nailed in a few hours by adding code to the OnStart, OnSleep and OnResume handlers in the shared class library (in this case, a PCL). After testing the functionality I then ran through a manual ‘smoke test’ to make sure everything was working as expected – and that’s when the trouble started ๐Ÿ™

I was initially working on the Android version and I quickly discovered that the photo taking functionality appeared to be broken. When I took a photo and then accepted it using the Android camera app I was taken back to a blank player list!

This didn’t used to happen – this was working code and I was certain I hadn’t change anything to do with the player photo code.

Nuget?

I then decided to create a quick and dirty app to pull in just the packages I needed to take a photo and display it within a view – and that worked just fine using the same versions that I had in my project, so the “problem” was in my code.

Returning to my code, the first thing I tried was to update all the Nuget packages. Some time had passed since I’d last opened the project and there were a number of updates pending. I was testing on my Pixel 2 XL running Android P (I’m in the beta program) and maybe, just maybe there was a mismatch here. As it was, this made no difference but it was a good job done – I’d have needed to do this anyway so no time like the present.

PCL v .NET Standard?

One major difference was that my app was using a Portable Class Library (PCL) while the sample app used .NET Standard (as you can’t create a PCL version now). Maybe that was my problem – maybe I needed to upgrade to please the plugin and/or Xamarin.Forms 3.0. Deciding it was another useful exercise anyway I decided to do just that – I created a new shared class library using .NET Standard and pulled my code over (a very simple process considering).

No joy – the problem persisted!

Then, in a moment of clarity, I wondered whether this was a problem was present in the iOS version of the app and to my surprise I found that it wasn’t. Running the smoke test on an iPhone 6s demonstrated the expected behaviour.

Going back to Android and diving into logcat I didn’t find anything obvious in terms of errors but then I saw a debug output message that I had added to the OnResume handler while developing the Save Game functionality. Why was that being called?

Eureka!

Then the penny dropped and it’s a fundamental part of the way that Android works.

When I called into the plugin to take the photo it opened up the Android Camera app – temporarily backgrounding my app in the process. When the user takes and accepts the photo, the Camera app will return control to my app, passing it the image data, and thus bring it into the foreground.

Of course, when the app is backgrounded the OnSleep handler is called and when it is brought into the foreground OnResume is called. In my case the OnSleep handler wasn’t a problem, but the OnResume hander was a different matter.

When resuming the app will now attempt to locate any saved state and if found it will deserialise the data and initialise the state to continue the saved game. But, if no saved state was found it will assume that the app is being opened with no saved state so it would just create a new game – and this is what it was doing, creating a new game with an empty player list!

A quick update to handle this unexpected backgrounding/foregrounding behaviour and I was back to a fully working app on iOS and Android.

The fact that the camera app was temporarily backgrounding my app didn’t dawn on me at the time but when I thought about it it was obvious.

A frustrating few hours to be sure but at the end of the day the app is now working the way it was intended to work and it’s now running with .NET Standard with all Nuget packages updated.

Online Tool of the Month – MockUPhone.com

While preparing my previous post I needed to generate some mobile device mockups showing my Xamarin.Forms app running in Android and iOS.

In the past I have normally cobbled these together using Paint.Net, a device bezel image and overlaying the screenshot onto it. Not pretty but it worked and looked fine.

However, the bezel images I had were rather old and I wanted to freshen things up a bit so went off in search of some new ones – only to come across MockUPhone.com.

MockUPhone is a free online service which will take your screenshots (I generate mine using Android and iOS simulators) and apply a variety of device bezels, e.g. Pixel 2, HTC One, iPhone 8 & iPhone X.

If I had a gripe then it would be that the images were not the same size for each platform which meant that I had to resize one of them to match the other but as I was going to be merge matched screenshots for Android and iOS into a single image this was hardly a hardship.

It is also worth noting that they offer another service called ‘ShotBot‘ which is an App Store screenshot designer for Android and iOS. It requires a login and I’ve not tried it myself (yet) as I already had my App Store listings ready to so – but when I need another one, I’ll be sure to take a run at this.

First Xamarin.Forms app goes live in both App Stores

A while ago I eluded to the fact that I was revisiting Xamarin.Forms for cross platform mobile development – previous projects had used the ‘native’ Xamarin.Android and Xamarin.IOS toolkit.

I was interested to see how far Xamarin.Forms had come since my last encounter where I found it lacking in some critical functionality that was required for the project at hand – primarily when dealing with Maps.

When I was approached by a user of my FillLPG application to write something along a very similar line, i.e. a number of points of interest displayed on a map with clickable markers to display more details, for both Android and iOS I wondered whether Xamarin.Forms had matured enough to do the job.

The application is a companion to the Motorhome Stopover website which provides it’s members with access to over 600 locations around the UK where they can park overnight for free. While these are not campsites, facilities vary from location to location, they do provide a useful service when drivers are travelling across the country to their ultimate location (not everyone wants to drive from Edinburgh to Penzance in one day and being able to break the journey is a godsend).

The app requirements were very simple, for the minimum viable product (MVP) anyway.

Authenticated Motorhome Stopover members should be able to view all currently active locations on a map, view contact details of any location and the facilities it provides and, using the device’s built-in navigation capability, navigate a route from the users current location.

Essentially, with the addition of an FAQ and About page, the app boiled down to a map showing stopover locations and a page listing contact and facility details for a location when the user tapped on its marker. If Xamarin.Forms couldn’t deal with this then I was going to be surprised.

The client was an Android user so much of the initial development was undertaken with that in mind and I focused on getting that version to a level where it was functional and he was happy – then I would take a run at the iOS version.

Initial development was undertaken prior to the release of Xamarin.Forms 3.0 but later upgraded without any problems – nothing appeared to be broken and everything just worked.

Looking back at my previous forays into Xamarin.Forms I think that the biggest hurdle was Custom Renderers. The problem being that documentation was very sparse and with the base toolkit not providing the level of customisation I wanted I didn’t have the confidence to plough on and develop Map Renderers only to have to revert to native development.

This time around the documentation was there in abundance, along with GitHub samples and a Xamarin University course. How times have changed ๐Ÿ˜‰

That said, it wasn’t plain sailing and there were still a few speedbumps along the way – although many of these can be attributed to climbing the learning curve of Xamarin.Forms rather than problems with the toolkit itself.

The best thing was, when I turned my attention to the iOS version of the app there was very little to do once the Custom Renderer for the map was completed and wired up. Everything else pretty much worked as expected with the only additional development being that of addressing minor styling and layout differences as can be seen in the screenshots below.

Not withstanding the need for additional features such as searching and filtering there is still some work to do. This mainly centres around testing and everything that facilitates it, e.g. dependency injection in Xamarin.Forms and how to do this within a Unit Test.

The ease with which I was able to develop these applications and the level of code reuse has certainly confirmed to me that Xamarin.Forms is more than just a tool to create very simple applications, quick mock-ups or proof of concept apps.

Overall I’m pretty happy with the initial release of the applications. Yes they are a bit feature-light at the moment and need a bit of polish here and there, but I’ve learned the hard way that at some point you just you need to ship something otherwise it will never see the light of day!

By defining a clear Minimum Viable Product I was able to focus on the core functionality and not get bogged down in the minutiae.

Get it on Google Play

 

Online Tool of the Month – webhook.site

If you’ve ever worked with a third party API that uses Webhooks you will appreciate the power and flexibility that they provide. Instead of having to poll for updates yourself you can rely on the API to call you instead.

I first came across webhooks when developing a web application that implemented Stripe as it’s payment gateway for monthly/annual subscription payments.

In this instance the webhooks would fire when specific events occurred; e.g.

  • Payment was successful
  • Payment failed (and will be retried)
  • Subscription Cancelled (manually or after repeated, automated attempts for payment have failed)

Long polling for this information would be a nightmare and having the webhook contact an endpoint on your API removes this headache – but does introduce another.

When I was developing the webhook callback endpoints it was difficult to see what data was being passed in the request. Stripe’s API documentation was good but there is nothing like actually seeing the data for yourself.

Attempting to route calls from a remote webhook to my development environment was somewhat problematic and I never quite managed to get it working. In the end I created a simple WebAPI service that I deployed to a virtual private server which would receive the webhook request (as JSON) and simply email it to me. Simple effective but a bit of a pain.

Recently I was looking at integrating an existing product with JIRA for another client and low and behold, it’s API provided webhooks – but before dusting off my WebAPI project I took a look to see if there were any alternatives out there – and, not surprisingly there was.

Enter webhook.site – a simple but powerful web application that basically adds a lot of polish to the quick and dirty solution I had previously developed.

When you navigate to the site it will generate a unique url that you can use to configure the webhook.

Then you can either wait for something to hit it (if you are debugging something live) or fire up your development environment and go through the process that will trigger the webhook to fire. Some services, like Stripe, provide a function to allow you to simply trigger the webhook with dummy data.

Once the webhook.site endpoint receives the request it will display the request and it’s payload.

This will prove invaluable if you are trying to debug inconsistent data operations and webhook failures.

Maybe it was a typo in a property name, maybe a data type mis-match, but without being able to actually see the data being sent it is impossible to determine what is going wrong.

 

Online Tool of the Month – realfavicongenerator.net

Following the migration of this website to WordPress I installed the ‘redirection’ pluginย in an effort to handle the difference in the url structure used by Squarespace (my previous host/platform). This plugin allows me to redirect users using the old Url to the correct content and also see any 404 errors for resources I may have missed.

While reviewing this 404 log I noticed a few rather odd entries, such as

  • apple-touch-icon-precomposed.png and
  • apple-touch-icon.png.

Knowing that I never had such content on the site before I did a bit of Googling and found that these are favicons (the little square logos that reside on your browser tabs) that Apple’s Safari browser will attempt to load along with your page.

Now that I knew what the problem was, how do i fix it? I mean, I had a favicon on the site – why couldn’t Safari just use that one?

After a bit more searching I found the Real Favicon Generator site where I was able to enter the Url of my site and it would generate a report on what it found (or didn’t find as the case maybe).

This is actually for another site I manage but the result is similar to when I ran it on this site

Now, that’s a lot of red but fear not – help is at hand. As the sites name eludes, it is also able to generate the appropriate icons as well. But how will I get these into WordPress – it only has the facility to allow me to specify a single favicon file.

Well – as well as the testing of the site and generation of the icons, there is also a WordPress plugin which makes things super easy.

With the plugin installed, navigate to the Appearance menu and select ‘Favicon’.

Select your desired image, they recommend 260x260px but mine was 150x150px and it looks fine for my purposes.

Click Generate and you will be taken to an editor page which allows you to tweak a few colours and settings – I didn’t bother with this, I just clicked the ‘Generate your Favicons and HTML code’ button at the bottom of the page.

And that’s it – I re-scanned the site and (unsurprisingly enough) everything was now green – and the 404 errors are no longer appearing in the redirection logs.

A New Freelance Project – and a Chance to Use .Net Core on Linux

I was recently approached by a website owner, who had seen the FillLPG for Android application and wanted a similar mobile application, i.e. an app which displayed a number of points of interest on a map and allowed it’s users to select a location and have further details displayed.

With my experience with FillLPG I was happy enough that I would be able to create applications to render the map with the points displayed in the appropriate location. The big question is – where is the data coming from?

The current situation

The website in question is fairly dated, in the order of 10 years old, written from scratch in PHP (not something like Drupal or Joomla) and backed up by a MySQL database.

The existing database is somewhat badly structured (in terms of todays programming practices) with no foreign keys, endless bit fields for HasThis and HasThat properties and a disjointed table structure (properties which you would think would reside in one table are in fact in another – manually linked by an id value).

There is no API that I can access from the mobile application – it’s just not there and there is no resource to create one.

The way forward

So, how do I access the data return it in a sensible format?

After a bit of thought I decided that the best option would be for me to create a WebApi project for the mobile apps to access. This project will access a separate MySQL database (with a structure more in line with what I need) which will be populated & updated by a utility program that I will also develop and execute on a regular basis (this is not highly volatile information that changes frequently).

So why .NET Core? You don’t need that to develop a WebApi project!

Glad you asked and my initial reply would probably be – ‘Why not?’. As a contractor I feel it is vital to keep your axe sharp and your skills up to date. I’m starting to see a few contracts now for .NET Core so it makes sense to keep my skills relevant.

After come careful analysis I decided that the most cost effective hosting for this solution was on a Linux based server. Yes, I know I can do that on Microsoft Azure but there are far cheaper services out there offering Linux hosting, so I’m going to use one of those.

Now, the only reason I can even consider using a Linux host is because of .NET Core. This allows me to develop using .NET technologies and C# – my development stack of choice.

But would it allow me to do what I intended to do? Could I create a WebAPI application to allow the mobile applications to access the data? What about the ‘Data Shuttle’ utility that will populate and maintain the data between the website database and the new WebAPI one?

Well, I’m happy to say that the answer to that question is yes, it will – and it did.

I’m writing this post after developing the initial, server side components, i.e. the Data Shuttle and WebAPI, and everything it working well – you would not know from the outside that the endpoints are not hanging off an Azure instance.

There were some pain points along the way and I’ve not answered all of my questions quite yet, things like logging and error notification, but everything I need for a Minimum Viable Project (MVP) are now in place from a server side perspective.

I have a handful of posts drafted at the moment which will dive deeper into the development for this project but here are a handful of links that you may find helpful in getting started:

 

Online Tool(s) of the Month – For Finding Lat/Lng

I’ve recently been engaged by a client to write the mobile applications for his website (more on that in later posts) which plots ‘points of interest’ on a map. That probably sounds a little familiar as I have already developed the FillLPG for Android application which displays the location of LPG stations around the UK – and increasingly into Europe.

Working with mapping applications is always a challenge, but an enjoyable one for me as I find maps such an engaging medium. One recurring challenge for me is that I don’t speak ‘Latitude and Longitude’ so when I need to test my code, e.g. load the map for a certain location and perform a ‘nearby’ search, I have to determine some suitable coordinates.

There are a few online tools out there but I always use one of a couple that I’ve found to be useful

Of the two LatLong.net looks the more modern interface with simple but powerful search capabilities. Enter a place name or Postcode (that’s a ZIP code for you US readers) and the map is displayed and a pin in the appropriate location with it’s coordinates clearly displayed (Lat/Lng and GPS).

If you want to find the coordinates of a specific location then you just need to pan & zoom the map until the location is in view and then simply click it with the mouse.

Couldn’t be easier really and this is all I need most of the time.

Sometimes though, I need a little more and while FindLatitudeAndLongitude.com may look a bit dated there is a lot of power there. For instance, while you can do everything that the previous site can do, if you can find the Menu panel (highlighted in the screenshot) you will see that you can perform all manner of searches and reverse look-ups.

Using the ‘Lat/Lng to Address’ search it is possible to zoom into a map, select a location (probably a house or business) and resolve the full address by clicking the ‘Load’ button. I’ve found this feature to be very powerful – for development and personal use (sometimes you just need a postcode for your SatNav).