App Store App Submission – Continual Failure and Obfuscation

The App Store has to be one of the flakiest “services” I’ve ever had the displeasure of having forced on me.  App submissions seem to fail constantly, more often than not, with little or no real error information.  I am genuinely in shock about how bad the entire iOS software distribution process it.  It is thoroughly, thoroughly broken.

The first submission I did failed 3 times even to just get the build up onto the Apple servers.  When it finally made it onto their server to took an overnight wait to get out of the “Processing” status and into a state where I could push it to our testers.  This second time I’ve wanted to push a new build it’s uploaded all 4 times I’ve tried but failed “Processing” 4 times as well.  Two days and 5 builds (from the same source code) and I’m nowhere nearer getting this build out to testers.

Local validations pass, then an upload fails, try again, upload works … processing fails … ad nauseam.

Episode IV – A New Build

I uploaded a new version of that same app to the app store last night for instance.  Waited nearly an hour watching the “(Processing)” text again,  got thoroughly bored waiting and went to bed.  Woke up this morning to the incredibly helpful message:

There was an error importing this build

No error information, no reasoning, nothing to work from, nada, zilch …

And now since Apple refuse to accept another upload with the same build number I have to push EXACTLY the same code-base through my build pipeline just to artificially up the version number to suit Apple.  Shambolic.

According to this thread I am not alone.  This seems to be quite an issue in fact.  And it’s not related to Xamarin since it’s happening to Obj-C and Swift app developers alike.

Now that I have made a new build with a new version number, I cannot even get this build to upload through XCode.  I now get:

This action could not be completed.  Try Again. (-22421)

I’m PAYING Apple for this service … real cash money … I expect more, a LOT more.  You can see from this SO thread that the problem happens often.  If you get an error from a system like this and the “fix” is to just repeat the same steps until it does work is absolutely 100% proof of a piss poor architecture behind the scenes.

No wonder Apple use Microsoft Azure as the real back-end powering iCloud, they simple couldn’t build Azure.

Fixes like “as with everything XCode a reboot fixed the problem” is hilarious.  Just proves to me all these people that make out that Apple stuff “just works” really aren’t using their systems for anything other than looking at cat videos.

Shambolic.

Another error I get when validating the archive before submission is:

iTunes Store operation failed

Seriously Apple, you need to clear up this embarrassing mess of a process.  This is XCode 7.2.1 not XCode 0.5.

Application Loader vs XCode

Confusingly, there are two methods to get (I say get generously as neither are working reliably) apps into the App Store.  XCode only deals with xcarchive files via the organiser in XCode.  Whereas Application Loader only deals with .ipa files.  Confused?  Yes well, confusion is name of the Apple game.  Application loader always fails on the API analysis stage, but don’t worry the message is only an advisory note that something else in your distribution tool chain is frankly shit.

The fact that these two methods seem to behave so differently and support completely different workflows suggests to my developer mind that they aren’t even using the same code to perform what should be a standardised process.  It’s not like the App Store is new …

XCode has told me every time that my binary is valid but it so far has always failed once it hits the Apple servers and the LONG 4+ hour wait while they are “Processing” it.  Jeez, people moaning about Microsoft should have a look at Apple if you wanna see a mess at work.

This from the richest company in the world, literally inexcusable.  I wouldn’t mind so much if it actually gave any hint at all as to what the issue might be.  “It Failed” is literally useless.

Error Message At Last

So on my third attempt to get my app up to Apple, I only had to wait 4 hours to be told that processing had failed again.  However, this time I actually got an error message, hidden under the little red exclamation mark:

itc.apps.prereleasebuild.errors.processingfailed.

However, what that actually means is anyone’s guess, I cannot find much about it online which leads me to believe this isn’t an error that should ever make it to the UI.  Half an hour later and that little error message has disappeared anyway.  It’s now back to the useless “It Failed” crap.  I haven’t received any other info from Apple.  Nothing, no emails, no explanation and no advice and obviously, nothing in my TestFlight dashboard.

I literally give up, I’m waiting for a few days until I even bother trying again.

Seriously, Apple this is a shambles.

Apple System Status

Due to all these App Store frustrations I found a useful link on my journey of failure.  Apple System Status link.  You can see from here that iTunes Connect is experiencing issues.

Share

Xamarin iOS TeamCity Build

So this turned into a complete nightmare for a while.

TeamCity Mac Agent Push Installation

I started by trying to get TeamCity to do a push install of a new agent on my MacBook Pro and very quickly things got very, very ugly.  First off it couldn’t find a JDK (which was installed) so I was using bash to update my ~/.bash_profile with the JAVA_HOME variable, but nothing seemed to work.  I fixed that by simply downloading the latest JDK release package and installing it.

Once the JDK errors and my /.bash_profile were fixed I then got the error (this is it in its entirety) “su: Sorry” … at that point I threw in the towel.  I’ve got better things to do that battle with this crap.  I abandoned the plan to push install the agent as I simply couldn’t figure out what was wrong with no information, the error text above was all that appeared in the agents log file as well so its  anyones guess as to what the problem really was.

NOTE: Make sure you can browse to the TeamCity site on your network using the agent machine

So I dialed into my TeamCity server, grabbed the zip installer and did it all manually.  This worked first time (after amending the buildAgent properties file) so what ever the issues were with the push installation I don’t know and frankly I don’t care, JetBrains have some tiding up to do both on this.

Build Steps

Since the build for the iOS application is now happening using Xamarin Studio installed on the Mac the build process is much simpler.  At the moment my unit tests are all run during debug builds only and these occur on a PC running another build agent.  I will revisit this to start executing test runs on the Mac agent to make for a more holistic testing process.

Updating Plist Files

There are a number of ways you can update the plist data on OSX.  Some people seem to suggest using the termainal DEFAULTS command but I found that didn’t work when presented with an iOS style Info.plist.  Chiefly it seemed to be confused by the internal layouts having arrays and a dict element.

By far the simplest way I found was making use of the standard OSX tool PlistBuddy which can deal with our iOS plist data.  So I added a new build step (executed before the compile step) and have configured it to allow me to update it’s internal version numbers and bundle identifiers based on the build configuration.

I normally use a 4 element version number for .NET (major).(minor).(build).(revision) which gives full traceability back to the source control for an individual release.  But if you use this in all cases you’ll have problems as iOS uses the semantic version number format (major).(minor).(build) for the “CFBundleShortVersionString” version number.

But you can also use arbitrary values in the “CFBundleVersion”.  Lots of people seem to ignore the AssemblyInformationalVersionAttribute in .NET but this is a great feature as you can use arbitrary strings as well as the more formal version format when using it in .NET assemblies.

$ /usr/libexec/PlistBuddy -c "Set :CFBundleIndentifier (yourbundleid)" Info.plist
$ /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString %build.number%" Info.plist
$ /usr/libexec/PlistBuddy -c "Set :CFBundleVersion %build.number%.%build.vcs.number%" Info.plist

Compile – Obsolete

The build step for compiling the iOS configuration is executed using a CommandLine build runner with a simple command like this:

/Applications/Xamarin\ Studio.app/Contents/MacOS/mdtool build "--configuration:Debug|iPhone" /path/to/solution.sln

Archiving Builds – Obsolete

Once the build is complete you’ll want to automatically create your archive. When you come to distribute your application to the App Store or to TestFlight via the XCode you’ll want to use xcarchive. You can use IPA files from the Build step with the Application Loader but as far as I can tell there is no way to upload dSYM files for any symbolicate processes which is a bit crazy (unless I’ve missed something)

Create another build step and use:

/Applications/Xamarin\ Studio.app/Contents/MacOS/mdtool -v archive "--configuration:Debug|iPhone" /path/to/solution.sln

This will place an xcarchive file into ~/Library/Developer/XCode/Archives/.  You can then validate this archive via XCode -> Window -> Organizer on the Archives panel.

Bye Bye MDTOOL Hello XBUILD

So, it seems the recent versions of Xamarin Studio and the MDTOOL method of compiling and archiving have become problematic.  I started to see builds failing with some odd errors relating to my Droid project inside the build logs of the iOS builds.  Hugely confusing.  I never got to the bottom of why this was occurring and decided to review the whole process.  Both the compile and archive steps are now combined into one step and one command.  The command I’m now using is:

/Library/Frameworks/Mono.framework/Commands/xbuild /p:Configuration=AppStore /p:Platform=iPhone /p:BuildIpa=true /p:ArchiveOnBuild=true /target:Build /path/to/solution.sln

Obviously you can change any of the configuration or platform parameters to suit your requirements / project setup.

As I work through the next steps of this process I’ll keep this blog post updated – you can read the Android version here.

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

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

MvvmCross Beta5 & SidePanel Navigation Sample

There is a new release of MvvmCross yesterday that takes the platform to v4 beta 5 that was released yesterday.  I’ve also contributed a new v4 sample project which provides cross platform side panel navigation to iOS and Android application.  You can check out the new version here and the sample is here.

You can see some screen shots of the sample applications below:

droid_menu_closed droid_menu_open ios_menu_closed ios_menu_open

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

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

Xamarin iOS Build Server is Too Old

This is silly message really.

If you’re getting this error (or something similar) but you also know that you’re running the latest version of the iOS build host:

Build server with address 192.168.0.5 is too old to be used with this version of Xamarin.iOS extension. Double click here to select a new server.    Xamarin.iOS Extension

It’s most likely that you have a manual proxy configured in your Windows development machine

The Solution

Go to your Manual Proxy configuration settings and turn off your manual proxy.  Once you’ve done this just double click on the message in Visual Studio and it should connect to your iOS build machine and run fine.

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

Xamarin Android Player in VirtualBox with Fiddler as Proxy to IISExpress API

So today was another learning experience indeed.  I decided to try Xamarins own Android Emulator today.  I’ve had so many odd problems with the Google Android Emulator that I was getting a bit fed up with using it to be honest.  It seems to have a lot of small issues that make it a pain to use and it has some major issues that under certain circumstances means it won’t work at all.

Anyway, the installation went without a hitch, needed to reboot to get the Host-Only network driver working.  Then I hit a road-block.

I was trying to configure the emulator to use Fiddler as a proxy on the development machine.  In the Google emulators you can configure a proxy using the APN settings for the cellular provider but this isn;t present in the Xamarin emulator so I’ve spent far longer than I should have trying to figure this one out.

By default all the emulators sit behind a virtual router, meaning if you have several emulators running they won’t be able to see your development box nor each other.  They are running in a kind of virtual network environment and each instance is completely isolated on the network.  Add into that the additional abstraction of VirtualBox and you have a pretty complex environment to deal with.

Anyway, I have added in additional bindings to make my IISExpress web sites available over the network and I could contact the API using the IP address but this makes Fiddler ignore the traffic.

The Solution

So, in the Xamarin Emulator you need to setup the proxy settings in the WiFi configuration.

If you’re having lots of issues getting this to work it’s worth checking that VirtualBox has been configured properly during the installation.  For instance when I first installed it, it was configured to use a SubNet mask of 255.0.0.0 so there was no hope of ever getting it to work properly on my development box.  Unless you have a custom setup (which is highly unlikely) this should in fact be 255.255.255.0.

Check VirtualBox Network Settings

Open the VirtualBox application and check the network settings for VirtualBox (not your VM) go to File -> Preferences:

vbsettings

This will show you the adapters created for VirtualBox during the installation.  My particular system needs to be available on #2 so double click the adapter to check/change:

adaptersettings

When my system was initially set-up the IPv4 Network Mask was set to 255.0.0.0 meaning it couldn’t see my development box.  It very likely that if you are trying to connect things to your host development box you may need to check what your configuration is (most likely 255.255.255.0) and then set VirtualBox to use the same mask (ipconfig is your friend).

Configuring the Xamarin Android Player

  1. Swipe down from the top of the screen and tap the Settings icon.
  2. Tap Wi-Fi.
  3. Tap and hold your current Wi-Fi network. Select Modify Network.ModifyNetwork
  4. Tap the Show advanced options box.ShowAdvancedOptions
  5. Tap the Proxy settings dropdown and select Manual.IPAddress
  6. Type the IP address and port (usually 8888) of the Fiddler server.IP Address
  7. Tap Save.

To verify this configuration, go to http://ipv4.fiddler:8888/. You should see the Fiddler Echo Service webpage, and the traffic should appear in Fiddler.

This is all tested and working as expected now.

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

The Apple Developer Clique

I’m genuinely gobsmacked by this.

I applied for the Apple Developer program a couple of weeks ago on behalf of the company I co-founded.  I was amazed to find out that I had to provide them with details about myself, details about my company including things like our DUNS number.

In addition to this I had to wait for them to call me … yes, CALL me.  Just so that I can get a set of digital keys to sign anything I build.  So I waited for the call which took a little over a week.  The checks they did in this call were frankly pathetic:

Them: “Hi Apple here, you applied for the developer program on behalf of <company>?”

Me: “Hi, yes I did”

Them: “Can you confirm you are <name> and can you sign things for your company?”

Me: “Yes I can”

Them: “OK, thanks.  I’ll update your application now, bye.”

I mean seriously Apple what is the FUCKING use of “check” like that??  I could have been bloody anyone on the end of that phone connection.

So, I then had to wait for that to filter through the system.  I got distracted as busy business types generally do and got on with other things to make better use of my time.  An email arrived on the 10th June saying that I could now finish the application.  So today (20th June) I’m in a position to get it paid for (I’ve got to PAY Apple to make their eco-system more attractive??? WTF??  I won’t go into how offensive I find that here).

BOOM!!  Because I didn’t cough up my cash quick enough (within 7 days) I now have to go through this laughable application/wait/phone call process again.  I have to apply again, giving all the same details AGAIN, wait for another impossibly stupid phone call and another email.

Just so that I can hand over the stirling equivilent of £110 (not $99) so that I can spend my time making an app for my company.

Seriously, Go fuck yourselves Apple.  Take about a little clique!

“Ohhh, you didn’t respond quick enough, oooh, oooh … you need to be faster than that … Oooh, join our little club you want do you?  It’ll cost ya.”

Yeah, well I’ve already paid a massive premium for the bloody laptop I’m using.

Share

PCL Profile 259 in Visual Studio 2012 on Windows 7, Xamarin, MvvmCross & ReSharper 7.1

Well, today was a lot of fun.  You can tell just how much fun from the ridiculous title of this blog post.

I’ve lost most of a productive day to this set of issues.  I was seeing some errors being reported by ReSharper 7.1 in my PCL and Xamarin Android solutions and couldn’t work out what the issues were.   They compiled without any compiler issues being returned and ran on the various emulators as expected, again without any issues or exceptions.  Consdering the error reported by ReSharper was Module ‘System, Version=4.0.0.0, culture-neutral’ should be referenced.  An error of that sort, if “real” should mean an application would have trouble even starting up let alone running.

resharper_errors

I’ve basically been round the houses trying to sort this out.

Considering the problem centered about MvvmCross I decided to have a look at the source for that so cloned the repository and started having a poke around.  Now the first problem you’re going to encounter given the VS2012 and Windows 7 constraints is that Windows Phone requires Windows 8 for development.  The WP8 SDKs won’t even install onto Windows 7 so those projects are dead in the water.  This target .NETPortable Profile259 which cannot be installed on Windows 7.

So when I opened the MvvmCross solutions on my machine I was seeing some very odd behaviours.  You can see some of the weirdness in the following screenshots:

mvvmcross

The Cirrious.CrossCore solution targets Profile 259 (the new Profile78 basically with Windows Phone 8.1 support thrown in – unavailable on Windows 7).  So what has been happening is any of my own projects that link to this library are trying to resolve system.dll v4.0.0.0 through Profile259.  Since I don’t have this profile ReSharper was correctly informing me of an issue but incorrectly informing that I’ll get a compiler error as a result.

In order to arrive at this solution I had upgraded ReShaper from 7.1 to 9.1 only to still see the issue.  Reinstalled all of Xamarin and even contemplated a fresh Windows install (not a small task).

The Solution

The solution turned out to be fairly simple.  Kid the system into thinking that my operating system DOES have Profile259 by copying the XML files from:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile78\SupportedFrameworks

Into:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile259\SupportedFrameworks

This doesn’t fix the issues I see when opening the MvvmCross solutions, they still compain about not finding system.dll but it has meant that my solutions that reference Cirrious.CrossCore do not throw up the problem of highlighting “non-issues” in my own projects.

So that was a hell of a learning experience.  And I did pull the trigger on an update to ReSharper 9.1 after complaining to JetBrains that 7.1 cost £110 and an upgrade to 9.1 cost £122!  So they gave me a 25% discount!  Yay!

Thanks JetBrains.

Share

Code Reviewing – Xamarin Components and MvvmCross Plugins

At the moment I’m working through the implementation of a mobile application build on top of the Xamarin platform targeting Android, iOS and eventually Windows Phone as well.

I’ve done a lot of Mvvm in the past with various personal and commerical WPF applications so not a lot of this is new.  The paradigms are very familiar but some of the approaches are new.  I’ve not done a whole lot with Portable Class Libraries for instance.  I’m also new to the device platforms I’m working on as well but viewing through the familiar C#/Java code makes things a lot more comfortable even if the underlying implementations are slightly different.

I’m reviewing a lot of security code at the moment, plugins and approaches and frankly I’m slightly concerned by what I’m seeing.  Before I say anything else I’m finding the development flow with Xamarin and MvvmCross to be really great.  Both of these platforms and frameworks are really great.

Lots of hardcoded strings used for encryption.  OK, not so bad considering the inevitable trade off between reliability, ease of use and the areas where one is comfortable to accept some risks given the contexts.

With all that said I’m seeing some very poor coding practices employed in some areas.

  • Lots of badly formatted code(not following established coding standards)
  • Code littered with magic strings even within the same class file.
  • Numerous instances of “” rather than string.Empty.  (pedantic? maybe but mobile apps need to be effecient and this simply isn’t)
  • Swathes of methods and properties with no documentation or comments.
  • Lots of hardcoded values not stored in constants

That is just lazy coding, nothing else.  A quick run of any of the code analysis in Visual Studio will highlight all of this.  It seems that none of the component authors I’ve seen thus far have ReSharper for instance.  Some of this I’m seeing even in released components available through the Xamarin Component Store.  Really not good.

I’m also seeing some components named in such a way that if you didn’t review the source code you could easily assume they are doing something when in fact they are not.

The long and short of it is I would suggest that you review the code for any component you plan to use before shoving it all in your solutions and forgetting about it.  You really shouldn’t be doing that btw, not when the source code is available to see online via a simple left click!!

Anyway, I’m finding lots of good examples of how to do things but relatively poorly implemented in many instances.  So far I have basically backed out from using any components in favour of implementing them myself.  In the small number of cases when I have used a component I’ve made notes in the classes, added tickets to YouTrack and added TODOs in the code that will be reviewed and ported into my own codebase prior to product release.

DO YOUR REVIEWS PEOPLE!!!

Example – IHS.MvvmCross.Plugins.Keychain

I’ve been building my own proprietary solution to interact with the various keystores on the mobile platforms.  I have to say that I’m loving the architectures.  Having come from years of WPF/Prism/Mvvm this all feels like second nature to me these days.  But along the way I’m finding some real horrors, it has to be said.  Take this as an example:

public string GetPassword(string serviceName, string account)
{
    var storedAccount = FindAccountsForService(serviceName).FirstOrDefault(ac => ac.Username == account);
    return storedAccount != null ? storedAccount.Password : null;
}

private IEnumerable<LoginDetails> FindAccountsForService(string serviceId)
{
    var r = new List<LoginDetails>();

    var postfix = "-" + serviceId;

    var aliases = _keyStore.Aliases();
    while (aliases.HasMoreElements)
    {
        var alias = aliases.NextElement().ToString();
        if (alias.EndsWith(postfix))
        {
            var e = _keyStore.GetEntry(alias, _passwordProtection) as KeyStore.SecretKeyEntry;
            if (e != null)
            {
                var bytes = e.SecretKey.GetEncoded();
                var serialized = Encoding.UTF8.GetString(bytes);
                var acct = LoginDetails.Deserialize(serialized);
                r.Add(acct);
            }
        }
    }

    r.Sort((a, b) => a.Username.CompareTo(b.Username));

    return r;
}

I literally do not know where to start to point out the problem and inefficiencies with the code I’ve shown above. What’s wrong with doing this instead?

var alias = MakeAlias(username, serviceId);
_keyStore.GetEntry(alias, _passwordProtection);

Why iterate over every single possibly stored value in the key file, then deserialise each entry in the store, build a list containing many entries and then pull out the specific one you are actually looking for? What a complete waste of valuable resources!!!

Share

Xamarin Pairing Visual Studio 2012 to Mac for iOS Builds

Well, this was a bit of a pain in the arse.

When I initially paired Visual Studio 2012 to my Mac it all seemed to pair and be happy.  No problems with the pairing, the two found each other on the network and all was well.  Then it came to actually doing something.  FAIL.

Visual Studio was moaning about not being about to actually connect to it to perform a build.  I stupidly hit the Unpair button and then couldn’t work out how to “re-pair” the two.  The steps I performed to get this working:

  1. Run regedit and remove the Xamarin entries for you Mac under KnownServers
  2. Turn off the Mac Firewall (this seem insane and I’m looking for a better solution)
  3. Restart your Mac
  4. Go through the standard Pairing process
  5. Should be good to go!

Once I clear up the Firewall advice insanity I’ll update this post with anything I find out.

Share