.NET Geographic Searches

I recently had to implement a localised search mechanism on an API.  Maths and Trigonometry aren’t my strengths it has to be said.  So I started looking online for pointers and background info.

Initially it might seem like you have to do some complicated maths to work out things like the size of the circle you’re dealing with etc.  But really the solution is very simple.  You know the starting points latitude and longitude and you also have a radius in a known unit, such as miles, meters or kilometers.  You’ll also have a dataset of potential target locations complete with their latitude and longitude points.

The only measurement you need is the distance from your starting point to a potential target location.  If that distance is less than or equal to the target location it’s within the circle designated by the radius.

The most accurate and popular algorithm for working this out is the Haversine algorithum.  The .NET framework has this built in.  The GeoCoordinate class inside the System.Device.Location namespace.

To use this:

var startingPoint = new GeoCoordinate(51.212213,-2.122312);
var targetPoint = new GeoCoordinate(52.212213,-1.122312);
var distanceInMeters = startingPoint.GetDistanceTo(targetPoint);

You can then convert the number of meters into whatever unit you would like to work with. Pretty simple really. The Haversine algorithm accounts for the curvature of the planet as well and has a very small margin of error.

You can find lots of implementations of this online, such as this one:

public static class Haversine {
  public static double calculate(double lat1, double lon1, double lat2, double lon2) {
    var R = 6372.8; // In kilometers
    var dLat = toRadians(lat2 - lat1);
    var dLon = toRadians(lon2 - lon1);
    lat1 = toRadians(lat1);
    lat2 = toRadians(lat2);
 
    var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
    var c = 2 * Math.Asin(Math.Sqrt(a));
    return R * 2 * Math.Asin(Math.Sqrt(a));
  }
 
  public static double toRadians(double angle) {
    return Math.PI * angle / 180.0;
  }
}
 
void Main() {
  Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40)));
}
 
// Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711

I would definitely recommend using the .NET version though as this will be thoroughly battle tested.

Share

SQLite Extensions for .NetStandard NuGet

I just created a couple of NuGet packages for helping to consume SQLite in .NetStandard1.5 applications.  Includes all the nice Async stuff you’d need as well.

It’s based on the twin coders Extensions that provide entity relationships within the database so makes your data tasks easier and wotnot.  All the code is on GitHub here:

https://github.com/jamsoft/SQLiteExtensionsCore

And you can get the NuGet packages like this:

Install-Package SQLiteNetExtensionsCore(link)

Install-Package SQLiteNetExtensionsCore.Async
(link)

Let me know if you encounter any issues or open a support/bug report on GitHub

Share

Windows 10 UWP – Emulator- The Revenge

I’ll tell you why UWP is suffering.  The UWP flavour of XAML is a mere shadow of WPF and the emulator is shockingly hard to get working or working reliably.  For all the warts and problems Xamarin has at least the emulators work.  At this point I’m approaching 10 straight days over the course of three months doing nothing but attempting to debug a UWP application in an emulator running on my development machine.  That’s an inordinate waste of my own life and valuable development time.

Imagine that, a Windows machine with a Windows IDE and a Windows VM engine fails to just work, WTF??  Microsoft, there is no excuse for this.   From all my hours of reading it seems droves of developers are failing to make meaningful use of their own freakin emulator.  I’ve been plugging away at trying to get this to work, on and off for over three months.  I find myself with regained enthusiasm for the problem to start trying again.  Go through the same pain and exasperation and give up again in complete and utter frustration.

Utterly ridiculous.

I’ve tried every solution I’ve found online and nothing has fixed the problem.  You can see long posts on StackOverflow discussing a shit-ton plethora of potential solutions.  The very fact there are such a vast array of potential solutions points to this entire feature of UWP and Windows Phone development needing a lot of TLC from Microsoft.

Why can I debug an iOS application crossing not just the network for compilation but also across operating systems with ease yet I cannot do the same internally to my development machine?  This is a seriously stupid situation.  Some of these discussions span years and multiple Windows OS versions and emulator versions.  Threads starting in 2012 and running through to today, with developer after developer failing to get a proper solution.  Or finding a solution that works until you reboot the machine and have to perform a load of random steps to get it working again.  I’ve wasted a day here and a day there trying to get this to work and it looks like I’m very close to just throwing in the towel – permanently.

In fact this is making me completely reconsider continuing any work with UWP at all.

You can see from threads like this one and this one and this one and this one (you can see a pattern here?!) that lots of people either had (the lucky ones) or are still having issues.  This post in particular was originally written in September of 2012, it has comments up to January 2016 and here I am looking at it March 2017 trying to solve the same problems.  5 years later people are still struggling with Hyper-V and emulating a Windows Phone.  This smacks of a stupid and a hugely counter-productive situation to put your developers in.

It also shows that it is a severe and very real point of pain for many and far from an isolated obscure networking issue.  At least give us some better useful exceptions, or things to Goolge Bing.  At this point I’m seriously underwhelmed with UWP development to the point where I really don’t care about it being a success or not.  Is that really where Microsoft wants me or other developers to be?

I can emulate ALL THE OTHER PLATFORMS with nothing more than a press of a button, but using a completely Microsoft owned tool-chain fails miserably.  It’s no wonder the Windows Store shelves are threadbare and the UWP platform is thus-far an utter flop.

I guess you can tell from the tone in this post that I’m far from happy with this situation, it’s an insanely frustrating situation all round.  I don’t give up on problems easily but this one has me utterly beaten.  I would list all the solutions and voodoo that I’ve tried in order to get this working but frankly I’m struggling to even keep the enthusiasm to finish this blog post explaining my own personal failure.

I guess I’m going to leave this rant alone now unless I find more energy or enthusiasm for the task, this maybe my first and last ever post on UWP.  Frankly, I’ve got better things to do with my time and lets face it, even if I could be arsed to dive into this again and finish my UWP application it’s not going to make me a millionaire anytime soon …

Share

ReSharper 10 Speed Woes

I love ReSharper, I really do feel slightly lost when using Visual Studio and hitting Alt+Enter doesn’t offer the same code sugar rush I’ve come to expect.  But I’ve gotta say that VS2015 Update 2 with ReSharper 10.0.2 is just starting to get to a point where the marriage seems to be stagnating.

For the first time since I started using ReSharper all those years ago I’m reaching for the suspend button.  I’m regularly seeing it use such a vast amount of my CPU cycles that I just cannot justify leaving ReSharper active all the time.  There are certain problems I know work on where the syntax can structure can see the instance of of Visual Studio running ReSharper start using 80+% of my i7.

That’s a LOT of CPU grunt.  I should really also say that as far as I can tell so far Visual Studio 2015 seems to be the buggiest RTM version I have used.  I have multiple issues at the moment with no solid workaround or even much help/input from Microsoft.

The versions of tools I have here are:

  • Visual Studio 2015 (14.0.25029.00 Update 2 RC)
  • .NET 4.6.01038
  • ReSharper 10.0.2 (104.0.20151218.120627)

There is a guide provided by JetBrains for speeding up ReSharper.  You could argue that having a guide like this acknowledges there is an issue, which I think is both fair and slightly unfair.  Either way I’m a die-hard fan and even I’ve had to resort to looking over this guide and trying to arrive at a feature/usefulness balance that I can life with day-to-day.  Seeing delays of 2 seconds between key presses is the makings of pure frustration but it is what I have been seeing on occasions, at times like that ReSharper is anything but a productivity tool.

I was working on a solution the other day and was having some serious issues with the performance I was seeing, I switched from using ReSharper intellisense to using the built in Visual Studio intellisense and was genuinely shocked to see the immediate difference.  The difference in speed was actually shocking.

This is actually the first thing I would suggest people try in order to speed up their system.  It appears ReSharper is doing an awful lot of text chugging in order to arrive at some of the suggestions and naming options.  Whilst useful, in the particular section of code I was writing (View constraints in a Xamarin iOS solution) the processing was just killing my machine.

Will keep this up-to-date with anything useful I find along the way.

Share

MvvmCross iOS Support and Samples

A while ago Martijn van Dijk and I had a very brief chat about creating an MvvmCross iOS Support library for use with MvvmCross.  Just to add in some general usage bits and bobs to make iOS development with MvvmCross a little bit easier.  I had been creating some useful bits for my own projects and could definitely see the value in them for other people to use in their projects.  But … as ever, my time is stupidly short.

Turns out it’s not as short as I thought and to be honest it didn’t take much effort to pull some things out and wrap them up in a self-contained fashion.  So today I spent a bit of time doing just that.  The results are now available in the MvvmCross iOS Support GitHub repository along with a newly minted MvvmCross iOS Support sample application.

MvvmCross iOS Support

The library really only contains one “helper” element at the moment in the shape of a pretty nifty presenter called – MvxSidePanelsPresenter.  Mvx Presenters are a kind of “glue class” that orchestrates what happens in between a view model navigation request and the presentation of it’s view in the application UI.  So any calls like ShowViewModel<TViewModel>(); will eventually end up being processed by a presenter, which decides what to do with it.

The presenter provides 3 panels as view “targets”, a main central panel, a right panel and a left panel.  Where a view is placed is controlled by a class level attribute.

Panel Presentation

[Register("CenterPanelView")]
[MvxPanelPresentation(MvxPanelEnum.Center, MvxPanelHintType.ActivePanel, true)]
public class CenterPanelView : BaseViewController&lt;CenterPanelViewModel&gt;
{
}

So to explain this example it’s telling the presenter that I want to be displayed in the center panel as the active panel and I also want to be shown immediately.  If this was requesting MvxPanelEnum.Left for instance this would show the view in the left hand panel and would also immediately slide the left panel into view.  Pretty neat.

Combining A UISplitViewController for Master / Detail Views

Another neat feature of the presenter is that it can present views in a split view if the presentation attribute includes the a specific request to do so (by specifying MvxSplitViewBehaviour) and the application is also running on an iPad.  In the case where there are split view behaviours added to the attribute and the application is running in an iPhone these behaviours will be ignored. The views are in that case presented in whichever panel has been specified. So there is a graceful fallback to default behaviour when needed.  You can specify this split view behaviour like this:

[Register("MasterView")]
[MvxPanelPresentation(MvxPanelEnum.Center, MvxPanelHintType.ActivePanel, true, MvxSplitViewBehaviour.Master)]
public class MasterView : BaseViewController<MasterViewModel>
{
}

[Register("DetailView")]
[MvxPanelPresentation(MvxPanelEnum.Center, MvxPanelHintType.ActivePanel, true, MvxSplitViewBehaviour.Detail)]
public class DetailView : BaseViewController<DetailViewModel>
{

The master view with be shown in the left hand portion of the split view and any detail views will be automatically shown in the right hand portion of the same split view.

Let me know if you find this stuff useful and obviously open any pull requests or open issues for any bugs.

You can see the code here on GitHub.  And you can read the more official documentation for this library on the MvvmCross documentation pages here.

Share

Abstracting APIs – Abstract Potentially Insane?

There’s no doubt about it, things that help are good.  This topic of abstraction came up in a chatroom the other day and I found myself advocating not abstracting in the client.  Having had more time to think about it I finally realised my own thoughts about it.  Just crept up from my subconscious.

At the moment I’m writing my own mobile apps, consuming an API that I’ve also written and maintain for use by mobile apps and web sites.  So naturally looking at anything to help is always worth considering.  The basic premise of my thinking is that in my particular situation, where I’m developing the API, dogfooding is the way to go.

Having to manually integrate with the API could be beneficial in a number of ways.  Having to deal with its security, data and inevitable idiosyncrasies can all potentially reveal design improvements.  If you immediately abstract your API behind someone else’s logic and expectations you’ll miss these opportunities during development.  You could argue the reverse is also true.  If Refit has troubles integrating with your API that could also reveal other problems or design improvements.

The particular client abstraction we were discussing is Refit.  It’s really very cool and if you aren’t in control of the API you’re interacting with it’s ideal, I’ll definitely be using it.  But I’m sure the authors of that API are at least testing that API if not also manually integrating with it at some point for some of the reasons outlines above.

Share

View Model Value Change Tracking in MvvmCross & Xamarin

Change tracking object contents at first might seem like an easy or straightforward task but there are lots of pitfalls and potential issues with many solutions.  What works in your situation might not work in other situations due to implementation details.

The most obvious use of change tracking is at the heart of many ORM frameworks.  These frameworks manage data, often through proxy classes, in order to track what needs to be written to the data store when inserts or updates are applied.  These are often very granular and can be significant performance drains if misused or used in situations when not really required.

Most solutions you’ll find simply add an IsDirty property on a base class or interface and then just set that to true in any property setters in order to mark the class as dirty.  Other solutions maybe a little smarter and have a SetProperty() method that compares the new value to the current value and only executes the set if the value is new or unequal.  Whilst this isn’t change tracking it is at least efficient in view models when bound to interfaces.  An example method might look like this:

protected void SetProperty&lt;T&gt;(ref T backingfield, T value, Expression&lt;Func&lt;T&gt;&gt; property)
{
    if (Equals(backingfield, value))
    {
        return;
    }

    var mem = property.Body as MemberExpression;
    if (mem != null)
    {
        var prop = mem.Member as PropertyInfo;
        if (prop != null &amp;&amp; prop.CanWrite)
        {
            // take advantage of any setter logic
            prop.SetValue(this, value);
        }
        else
        {
            // update backing store
            backingfield = value;
        }
    }

    RaisePropertyChanged(property);
}

If you’re trying to compare to original values you could start tracking each change to each property and working out if the current value has been used at any point in past.  This could very easily become a very bloated object graph.  You’re also still left in a situation where developers have to remember to call the SetProperty() method and not just set a property either directly or miss the public class API altogether and set the private backing field and negating any setter logic anyway.  If you don’t want to have property changed code in all your setters this can be a good approach if a little more expensive.

Negating all of these issues in one solution is extremely hard but minimising them is a must.

My Solution

I wanted a fairly simple IsDirty semantics at the class level.  I wanted my solution to just take care of itself and I didn’t want to have to do too much work in order to get this reliably functioning.  I also want it to be efficient and smart enough to accurately report that the class data really had changed and also wasn’t the same as the original values. My requirements where:

  • Entirely PCL (Portable Class Library) based implementation
  • Behaves in data binding situations
  • Attribute-driven Opt-In
  • Complex reference & value types included in object graph
  • Public only tracking (this is a view model after all!)
  • Filtering properties on Type or Name (string fuzzy matched)
  • iOS, Android, WP & MvvmCross friendly
  • As performance & memory efficient as possible
  • Class level monitoring only
  • Minimal extra library dependencies

So given these change tracking requirements I have coded my solution and I’m going to include all the code in a GitHub GIST below.

Usage

I wanted this to be as simple as possible pollute the code as little as possible.  I think it’s OK at the moment but will no doubt change and hopefully get better.

Property Attribute Example

If you use the attribute only those properties will be monitored, all other properties will be ignored.

public class PersonViewModel : MvxViewModel
{
    // ignored
    public string Name { get; set; }
    
    [IsDirtyMonitoring]
    public string DisplayName { get; set; }
}

IsMonitoring Example

To start the monitoring, at some point after you can guarantee that all the values you regard as “clean” available in the object set Ismonitoring to true.  This forces a the calculation of an MD5 value for all the properties, now any subsequent calls to the IsDirty getter will compare this hash value to a newly created one with the current data.

You can reset the clean hash at any point by simply setting IsMonitoring to true again.

public sync void Init(int id)
{
    var data = await _myapiClient.GetPersonAsync(id);
    Mapper.Map(data, this);
    IsMonitoring = true;
}

Dependencies & PCL

The basic design has two dependencies.  Since I already had Newtonsoft.Json used in my project I have made use of parts of this and in order to implement the MD5 object hashing I have had to add a library – the xBrainLab.Security.Cryptography library available on codeplex.  Weighing in at 9,728 bytes this isn’t really much of a concern.

Basic Change Tracking Design

The basic design is that when IsMonitoring is set to true an object immediately generates an MD5 hash of all the relevant properties (default minus filters or explicitly opted in).  Then each subsequent call to IsDirty will first generate a new MD5 hash of the current values and compares that to the stored “clean hash”.

Hash Values (MD5)

Hashing in PCLs isn’t the norm so we have to use a library.  When generating the hash the object is first serialised to a memory stream using a JSON.NET serialiser.  This is then MD5 hashed and either stored or compared in order to calculate if an object has changes since monitoring began.

You can also set a newly minted clean hash by simply setting IsMonitoring to true on live objects.

Class Serialisation

The serialisation is all handled my JSON.NET and it’s built in serialiser.  I did try using the BSON serialiser as this may have a performance gain but it seemed to be erroring too often so I may have to revisit this.  There is a custom contract resolver that controls what is or isn’t to be tracked.  If a class has any properties marked with the IsDirtMonitoringAttribute then only these marked properties will be tracked.  If none of the properties are marked with the attribute then all public properties will be included in the change tracking minus any properties of the same type as the filter types or property name masks in the name filter.

Performance

It’s not particularly scientific or probably that accurate but I have added a unit test that monitors it’s execution time.  The test performs 100,000 IsDirty calls in a loop and will fail if it takes more than a second to complete based on the built in StopWatch class in System.Diagnostics it’s about as accurate as I’m needing.  Considering this will be called pretty infrequently and usually on a background thread this performance doesn’t concern me.  I have now implemented this on a few classes in an iOS application and I haven’t noticed any runtime issue (as yet!).

Anyway, enough wibbling as I should be out Christmas shopping … here’s the code … any comments or improvements really welcome.

Share

Whitelist SSL Certificates in .NET for Xamarin / MvvmCross Apps

I have a fairly complex development environment for my current project and needed to allow some self-signed certificates to pass through the SSL certificate chaining process when calling from mobile platforms.  Obviously, this is potentially breaking a major security feature and need to be done safely.

In a ‘normal’ MvvmCross or Xamarin.Forms application you want to include as much in the core PCL project as possible for portability and code-sharing.  Unfortunately there is no PCL implementation of the ServicePointManager class, but this is defined in both Xamarin.iOS and Xamarin.Android.  Strangely, another instance where Windows Phone is problematic as this isn’t defined at all in WP.

Given that I have another shared library that hosts my API client that is compiled into a platform specific version I can do this here and have that shared.  Otherwise your best options are including this code in the platform specific projects somewhere in the Setup.cs class for instance.

Bypass Certificate Checking

#if DEBUG
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
    (sender, certificate, chain, policyErrors) =>
    {
        if (policyErrors == SslPolicyErrors.None)
        {
            return true;
        }

        var certThumprint = string.Join("", certificate.GetCertHash().Select(h => h.ToString("X2")));
        var thumbprint = "<YOUR CERT THUMBPRINT>";
        if (certThumprint == thumbprint)
        {
            return true;
        }

        return false;
    });
#endif
Share

iOS Keyboard Handling in MvvmCross View Controller

I’ve just had to handle the situation where a user taps on a text editor control in an iOS view and the keyboard auto appears.

Whilst this is obviously great for the user it leaves a lot to be desired in the full editing life-cycle in terms of UX.  Also In some situations there isn’t a dedicated keyboard dismiss button available to the user to remove the keyboard from the UI.  Nor will a view automatically handle the fact that they keyboard will obscure the very control the user tapped on meaning they cannot even see the text they are adding or editing.

Personally I find it quite amazing that in an OS at major revision 9 this is entirely left to the individual developer to handle properly.  I’m sure Apple have their reasons but this should be default behaviour on the platform in my opinion.  This is in fact a number of things I find missing in iOS.  Whilst it’s true that this arguably leaves things flexible in terms of not dictating how things should be done it does mean that there ends up being a plethora of potential solutions out there, also possibly of varying quality and reliability.

Anyway, I have found a fantastic solution to this and have a GitHub GIST available in the shape of extension methods and an MvvmCross base view controller implementation.

GitHub GIST


Original credits go to GuillermoGutierrez

Share

Enable ASP.NET 4.5 On Windows 10 or Windows 8/8.1

By default IIS and ASP.NET aren’t configured as part of a Windows setup (for obvious reasons) so developers are used to having to register IIS manually before being able to run and develop ASP.NET web sites on their desktops.  Prior to Windows 8 it was a simple command like this:

aspnet_regiis -r

This no longer works and requires a different command. Depending on what you already have enabled this may work:

dism /online /enable-feature /featurename:IIS-ASPNET45

If you haven’t enabled anything related to IIS yet you can do that at the same time with:

dism /online /enable-feature /all /featurename:IIS-ASPNET45

However!  That might not appear to solve the problem even when it has!  A post from Microsoft makes a bug apparent:

After the installation of the Microsoft .NET Framework 4.6, users may experience the following dialog box displayed in Microsoft Visual Studio when either creating new Web Site or Windows Azure project or when opening existing projects.

Configuring Web http://localhost:64886/ for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.

NOTE: Microsoft .NET Framework 4.6 may also be referred to as Microsoft .NET Framework 4.5.3

This issue may impact the following Microsoft Visual Studio versions: Visual Studio 2013, Visual Studio 2012, Visual Studio 2010 SP1

Workaround:

Select “OK” when the dialog is presented. This dialog box is benign and there will be no impact to the project once the dialog box is cleared. This dialog will continue to be displayed when Web Site Project or Windows Azure Projects are created or opened until the fix has been installed on the machine.

Resolution:

Microsoft has published a fix for all impacted versions of Microsoft Visual Studio.

Visual Studio 2013 –

Visual Studio 2012

  • An update to address this issue for Microsoft Visual Studio 2012 has been published: KB3002339
  • To install this update directly from the Microsoft Download Center, here

Visual Studio 2010 SP1

  • An update to address this issue for Microsoft Visual Studio 2010 SP1 has been published: KB3002340
  • This update is available from Windows Update
    • To install this update directly from the Microsoft Download Center, here
Share

Xamarin Android Player in Windows 10

After having upgraded to Windows 10 I found that I had some networking issues running the Xamarin Android Player.  When trying to start the emulator it would attempt to create a new Host-Only adapter and would constantly fail.  I ended up with 6 adapters configured.  It was constantly asking me to reboot the computer as well.  None of this worked.

The Xamarin Android Player is also expecting a very specific network configuration.  What I ended up doing to fix this issue is:

Launch VirtualBox

  1. Go to File -> Preferences -> Network then the “Host-Only Networks” tab
  2. Delete all the spurious adapters named “VirtualBox Host-Only Ethernet Adapter <somenumber>#” leaving just one
  3. Double-click the remaining adapter and enter all these details:

Adapter;
IPv4 Address: 10.71.34.1
IPv4 Network Mask: 255.255.255.0

DHCP Server;
Enabled
Server Address: 10.71.34.2
Server Mask: 255.255.255.0
Lower Address Bound: 10.71.34.101
Upper Address Bound: 10.71.34.199

Now when starting a Xamarin Android Player instance you should see it boot as expected but with full network access and without attempting to create new Host-Only adapters.

Share

Package Dependencies & Deploying .NET

I recently had a requirement to completely package up a .NET application so that it was extremely portable beyond it’s initial installation. By bundling all the dependencies into the main executable package you can move the application around with minimal fuss once installed.  The goal was to keep the application as independent as possible.

The application is actually fairly simple with only a handful of required library files to package.  Once all the dependencies had been packaged the entire application executable is still under 600k.  This process detailed below also enables the package to contain non .NET assemblies, like C++ components and other files.  What’s really good is by default the dependencies are never extracted onto the file system which is ideal.

Initially this might sound like a complicated process. However … all you need is one NuGet package Fody/Costura (Source).  That’s it!  Just install the package and you’re done!

The NuGet Package Solution

make sure that you have your start up project selected in the package manager console and execute this command:

Install-Package Costura.Fody

You don’t even have to configure anything.  Just build …

The only thing that might need doing in order to make sure your package only contains exactly what’s needed you can add a new set of targets to your *.csproj file.

When you install the package it will automatically add a new import:

<Import Project="packages\Fody.1.26.1\build\Fody.targets" Condition="Exists('packages\Fody.1.26.1\build\Fody.targets')" />

Then to make sure you get the package your really want you can add:

<Target AfterTargets="AfterBuild;NonWinFodyTarget" Name="CleanReferenceCopyLocalPaths">
  <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
</Target>

Done. Very nice and a must know trick.  The only thing I want to now tackle is bundling in the base configuration file.

Share

WPF ListBoxItem Selected Background Highlight in Windows 8

When targeting the way a ListBoxItems are styled on pre Windows 8 platforms you could easily change with style syntax like:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>

This would essentially override the OS level WPF style brushes and remove the highlighting (at least in this case since the color property is set to transparent). This has all been changed in WPF post Windows 8 and requires a lot more code to achieve the same effect.

In the style below, I use the above code in the ControlTemplate to achieve this:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type ListBoxItem}">
            <Border x:Name="Bd"
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Padding="{TemplateBinding Padding}"
                    SnapsToDevicePixels="True">
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    Content="{TemplateBinding Content}"
                                    ContentStringFormat="{TemplateBinding ContentStringFormat}"
                                    ContentTemplate="{TemplateBinding ContentTemplate}"
                                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
            </Border>
            <ControlTemplate.Triggers>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsMouseOver" Value="True" />
                    </MultiTrigger.Conditions>
                    <Setter TargetName="Bd" Property="Background" Value="Transparent" />
                    <Setter TargetName="Bd" Property="BorderBrush" Value="Transparent" />
                </MultiTrigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="Selector.IsSelectionActive" Value="False" />
                        <Condition Property="IsSelected" Value="True" />
                    </MultiTrigger.Conditions>
                    <Setter TargetName="Bd" Property="Background" Value="Transparent" />
                    <Setter TargetName="Bd" Property="BorderBrush" Value="Transparent" />
                </MultiTrigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="Selector.IsSelectionActive" Value="True" />
                        <Condition Property="IsSelected" Value="True" />
                    </MultiTrigger.Conditions>
                    <Setter TargetName="Bd" Property="Background" Value="Transparent" />
                    <Setter TargetName="Bd" Property="BorderBrush" Value="Transparent" />
                </MultiTrigger>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter TargetName="Bd" Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Phew … thanks Microsoft!

Share

Xamarin Android Automated CI Publishing Using MSBuild & JetBrains TeamCity

I love automating processes and making things consistently repeatable.  Continuous integration is your friend, yes it can take time to setup but if you take that effort hit upfront it will pay off in an immeasurable way through your development process and during the entire lifetime of the your development.

For my continuous integration I use JetBrains TeamCity.  I love this CI system, granted I’ve not used them all but comparing them to TFS and Jenkins it is like an oasis of calm in comparison and without doubt the cleanest UX design by a very long margin.  Anyway … I digress.  If you want to automate the process of producing your ready to distribute Xamarin .apk Android application packages, this is the basic process you need to follow:

Creating Your Keystore

The first step is to create your own personal keystore that will contain the information used to digitally sign your Android package files.  You can do this with the following command:

"C:\Program Files (x86)\Java\jre1.8.0_45\bin\keytool.exe" -genkey -v -keystore myandroid.keystore" -alias myaliasdroidpub -keyalg RSA -keysize 2048 -validity 30000

Before you run this command make a note a few parameters first.  I did all of this in a batch file so I can refer to it later, this does include some sensitive data so beware what you do with this file.  The 30000 at the end of the command denote the length of validity of the certificates and Google require this to be past 2033.  You’ll need the following info:

REM — Password – <yourpassword>
REM — name —– <yourname>
REM — OU ——- <organisationunit> eg: JamSoft
REM — Orgname — <organisationame> eg: JamSoft
REM — Local —- <locality> eg: Frome
REM — State —- <state> eg: Somerset
REM — Country — <2lettercountrycode> eg: UK

Visual Studio Android Project

Now that we have our Java keystore ready and prepped for use we can look at the Visual Studio project.  In order to make this automated in the build system we need to configure the project to use our keystore credentials.  This is spreading sensitive information around but since our keystore is probably going to be checked into our repository it’s most likely going to spend it’s life being treated in a sensitive fashion anyway, so no real concerns.  I personally make lots of backups of things in large .RAR files and store these in various places but these are also password protected and treated as confidential.

In Visual Studio edit the Android application .csproj file and add another PropertyGroup element as per the code below:

  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <AndroidKeyStore>True</AndroidKeyStore>
    <AndroidSigningKeyStore>myandroid.keystore</AndroidSigningKeyStore>
    <AndroidSigningStorePass>yourpassword</AndroidSigningStorePass>
    <AndroidSigningKeyAlias>myaliasdroidpub</AndroidSigningKeyAlias>
    <AndroidSigningKeyPass>yourpassword</AndroidSigningKeyPass>
  </PropertyGroup>

Now our .csproj file knows how to use our keystore unattended. We can tie into the Xamarin build process from within our automated builds and produce the base Android package.

You can test that this is working using the following command:

msbuild.exe HelloWorld.csproj /p:Configuration=Release /t:PackageForAndroid

This will execute MSBuild against your Android project file and you’ll now find your .apk file in your bin\Release directory.

Signing The Package

Now that we have our packaged application we can apply the signing processes.  To sign the package created in the previous step we need to execute the following command:

"C:\Program Files (x86)\Java\jdk1.7.0_71\bin\jarsigner.exe" -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore myandroid.keystore -storepass yourpassword -keypass yourpassword -signedjar \bin\Release\packagename-signed.apk \bin\Release\packagename.apk myaliasdroidpub

This package is now digitally signed using your certificate from the keystore we made earlier. Personally I still have a couple of questions around why this needs to be done again considering that the details for this keystore are in the csproj file but I’m still waiting on a response from Xamarin on this.

ZipAligning the Signed Android Package

Now that we have a signed package we can zip align this package and then publish this as an artifact of our TeamCity build process.  This command makes use of the Android SDK zipalign.exe program.  You’ll have to find where this is on your machine as there are many potential locations.  The command you need will look something like this:

“C:\Users\<name>\AppData\Local\Android\android-sdk\build-tools\<version>\zipalign.exe” -f -v 4 packagename-signed.apk packagename-zipaligned.apk

You don’t need to follow this naming convention used here this is just for illustration purposes.

You can now set this as a published artifact of your TeamCity build configuration.  Yay!

MSBuild Project

To kick off the process in your MSBuild project you can add TeamCity Step that executes an additional Target in your build script like this:

  <Target Name="PackageAndroidApk">
    <MSBuild Projects="$(MSBuildProjectDirectory)\..\src\path\MyProject.Droid.csproj" Targets="PackageForAndroid" Properties="Configuration=Release">
    </MSBuild>
  </Target>

This target will create the base APK package that you can sign and zipalign.

Once you have all these commands working you can add all the required build steps.

Capture

And voila!  Automated.  Nice 🙂

Share

Learning MvvmCross

Learning a new technology can sometimes be a very time consuming and error prone process.  The more complex the technology the longer this process can go on for.  When I was first getting my head wrapped around WPF and using the MVVM pattern this was a long process.  WPF is massive and very complex.  MvvmCross whilst not nearly as large is a very complex framework in itself.

Having said that I’m literally amazed at just how much Stuart Lodge manages to produce in terms of tutorials, write-ups, videos and code.  For that reason alone it’s worth your time to investigate.  Below I’m starting to compile a list of resources that I find useful along my own journey of using this framework.

Code

MvvmCross Source

NPlug1DaysofMvvmCross

Videos

This is a series of really good videos produced that demos how to achieve a very large number of basic and advanced scenarios using Xamarin and the MvvmCross libraries.  Stuart has put a lot of time and effort into producing this and it’s well worth your time to dive in from time to time to learn about the various features and options available on how to structure your code and applications.

MvvmCross NPlus1DaysofMvvmCross Tutorial Videos

Blog Posts

This is a partner to the code and videos and contains a lot of very good examples and tutorials.

NPlug1 Blogs Table of Contents

Share

View IISEXpress Hosted Sites On Your Local Network

This is a useful little tidbit of knowledge to have.  Suppose you can browse to your new spanky site using IISExpress at http://localhost:54275/ … now you want to look at it on your phone?  Or your laptop? Or your … you get the picture …

Pre Visual Studio 2015

  1. Open up C:\Users\<yourname>\Documents\IISExpress\config\applicationhost.config
  2. Find your site definition and add in a new binding <binding protocol=”http” bindingInformation=”*:54275:<your-ip-address>” />
  3. Open Command Prompt (as admin) netsh http add urlacl url=http://<your-ip-address>:54275/ user=everyone
  4. Then execute netsh advfirewall firewall add rule name=”IISExpressWeb” dir=in protocol=tcp localport=54275 profile=private remoteip=localsubnet action=allow
  5. Then point your remote machines to http://<your-ip-address>:54275
  6. Voila!

That wasn’t so hard eh!

Visual Studio 2015

You need to complete steps 2 to 5 above, but Visual Studio 2015 by default doesn’t use the global configuration file for these IISExpress bindings.  In order to configure this you know have a couple of options.

The first option is to configure your project to use the global configuration files by added this to your *.csproj file:

<UseGlobalApplicationHostFile>True</UseGlobalApplicationHostFile>

Or you can add your addition bindings to the solution specific configuration file Visual Studio 2015 generates here:

<solution_dir>\.vs\config\applicationhost.config

Now running your solution under Visual Studio 2015 will behave as required.

Potential Errors

There are obviously too many potential errors to keep track of on a single blog post but I thought I’d detail a few fixes to issues I’ve personally experienced.

Access Denied

sometimes you may see this message when trying to launch your solution in Visual Studio.  To get around this close everything down and re-launch Visual Studio “as admin”.  This should fix the issue and then subsequent launches should work without running Visual Studio as an admin.

Failed to register URL "http://192.168.0.8:51258/" for site "<name>" application "/"
Error Description: The Network location cannot be reached.

This was a particularly annoying issue and took quite some time to track down.  It seems that the Threshold 2 update to Windows 10 removed all my listening IP address entries!  You can check that by executing this command in a Command Window:

netsh http show iplisten

If your own IP address isn’t listed here you need to add it.  You can do that by using this command (use your own IP address obviously):

netsh http add iplisten 192.168.0.8

You can see more information about netsh here.

Share

Upgrading MVC4 to MVC5 and WebAPI1 to WebAPI2 – MEF – DotNetOpenAuth

Originally Written 20 June 2014

So, if you have found this blog post as you are going through this process and have hit numerous brick walls I’m afraid I’ve got no answers.

I wasted 3 days on this process and by 3pm on the 3rd day I simply gave up and reverted my working copy back to MVC4.

it seems there are a number of breaking changes between MVC4 and MVC5 that just simply are not being talked about much and since I have a workload of 10 people at the moment I simply do not have spare capacity to sit down for days on end poking the framework to get it to work for me.

The security model in MVC5 is different meaning that DotNetOpenAuth is no longer working, which means Andrew Arrnott who WAS the lead (yes you read that right – WAS) had to issue a quick fix to DNOA so that it worked – DotNetOpenAuth MVC 5 extensions.

On top of all that faffing around with DNOA I found that I had yet more issues with the Microsoft.Bcl.Build stuff which is frankly a joke. Also the Attribute routing implementation that is now built in to WebAPI isn’t a patch on AttributeRouting. Crap.

Then for some reason which I could never get to the bottom of (hence the rolling back to MVC4) all my MEF code in my WebAPI solution simply stopped working. I have absolutely no idea why but all of a sudden my custom controller factory was simply bypassed by the whole pipeline meaning that anything marked as an import was left null. There is nothing talking about this online and I tried all mannor of code changes to try and figure out the problem and get it working but nothing fixed it. I have two open StackOverflow questions which I will keep an eye on:

http://stackoverflow.com/questions/24324228/updating-mvc4-webapi-to-mvc5-webapi-2-broken-mef-implementation

http://stackoverflow.com/questions/24326270/webapi-custom-controllerbuilder-not-being-called

So basically, upgrade at your peril, it may just eat through your time like a bastard, I gave up … for now.

UPDATE 30 June 2015

Amazingly this is almost a year to the date of the original post.  Again I have tried to migrate my MVC WebAPI and MVC Site over to the newer versions and again I have utterly failed and rolled it all back.  So many breaking changes and libraries that I’m dependent on that still just won’t play nicely.  I’ve wasted so much time and effort on getting this done that I have simply not got the time to carry on trying to push forwards with it all.

I have absolutely fallen out of love with DotNetOpenAuth.  It is a hugely over complicated library and I cannot wait to ditch it for something better.  It works for now and will have to do but I am not happy about how this library is put together.  It is hugely brittle and even the build process in the source code is horribly complex.

When will package authors realise that the more trickery you put into something the harder and harder it gets to support and for others to pick up and run with.  Not impressed.  Version 5 of this library has been in development since 2013 and is still only in an alpha state.  I’m going to move away from using this package at the first available opportunity I get.

I’ve also come to the conclusion that I’m not going to migrate to a newer version of MVC I’m going to build the MVC6 or maybe even MVC7 version from the ground up to make the most of the new features of the chosen replacement platform.  It seems the changes in 6 are profoundly deep, ASP.NET 5 doesn’t even support Web Forms for instance.  THAT is a huge development on its own.

Anyway, for anyone reading this and planning on doing the migration, good luck!

Share

Xamarin – The Baptism of Fire – Windows 7

So as I blogged a few days ago about the issues I was having with getting to grips with all the issues I was having (which you can read here) it appears I’m getting to grips with all the added complexities of working on cross platform .NET based solutions.  There have been some incredibly late nights involved, surviving on 5 hours sleep a night for nearly a week has taken it’s toll I can assure you.

If you look at the other posting on the site of late, chiefly the Windows 8 post, you’ll see that despite all the Profile hacking I did I still wasn’t happy (neither was ReSharper but that’s another story).  I did end up migrating away from Windows 7 onto the Windows 8.1 Pro platform.

I’m a simple developer at heart.  Although I love all the neat tricks of .NET and using advanced interface based abstractions and Mvvm I still like to stick to first principles – simple is always better.  I didn’t like the fact that when I was dealing with lots of other peoples code and libraries my basic setup around Windows 7 wasn’t dealing with it properly or reliably.  Most of the things you’ll find yourself looking at deal in some way with a profile that the Windows 7 OS isn’t compatible with.  Profiles that target Windows 8 or Windows Phone 8.1 just don’t like it.  You can’t even installed the required SDKs  Windows 7.

So, I have moved on.  I loved Windows 7, it served me very, very well.  Was rock solid for me and I had a complex machine with an even more complex Windows configuration and until the last couple of weeks it motored on and munched through all my work.

Anyway, if you’re thinking of getting started with mobile development and Xamarin and you’re on Windows 7, upgrade.  It’s as simple as that.  You’ll save yourself lots of hacking around, late nights and stress when things go odd, and from what I can tell they almost certainly will.

Share