Simple Alternative to AutoMapper

Recently we had some troubles with AutoMapper after upgrading our core libraries (Xamling-Core) to Xamarin Unified. Our unit tests started failing.

There is more detail on that issue here: http://blog.xamling.net/2015/01/26/strange-sigsegv-after-upgrading-to-xamarin-unified/.

In the meantime it left us scrambling for a replacement. Our entity cache and management system relies on mapping to ensure entity instances are the same no matter how you get it… a job for a mapper. Keep original entity in memory, any updates come in you copy the new data on to the in memory instance… all references are happy.

So we had a look around, and turns our – we don’t really use many of AutoMappers features. Great lib to be sure – but we are doing the most basic of mappings.

The solution was found on StackOverflow (naturally) posted by user Azerothian here.

We made a few little mods and made it available as part of the Xamling-Core library.

SimpleMapper.cs

Jordan.

EDIT – it was pointed out by @JakeGinnivan that this would be slower than AutoMapper… keep that in mind for high usage scenarios. Shouldn’t be a problem in a mobile app, but worth keeping in mind – thanks Jake!

Strange SIGSEGV after upgrading to Xamarin Unified

So we upgraded to Xamarin Unified so our app – Project Tripod – would be accepted in to the store. It wasn’t a horrible process. Few refactors here and there. Of course, that meant we had to update Xamling-Core too. There were a few headaches there unfortunately.

We kept getting this strange crash when writing strings to the file system. It showed in a lot of our tests – ending with a crash something like this:

2015-01-24 12:35:23.660 AutomapperProblemReplicate[601:149248] critical: Stacktrace:
2015-01-24 12:35:23.661 AutomapperProblemReplicate[601:149248] critical:   at  
2015-01-24 12:35:23.661 AutomapperProblemReplicate[601:149248] critical:   at (wrapper managed-to-native) object.__icall_wrapper_mono_array_new_specific (intptr,int) 
2015-01-24 12:35:23.662 AutomapperProblemReplicate[601:149248] critical:   at System.IO.StreamWriter.Initialize (System.Text.Encoding,int) [0x00017] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.IO/StreamWriter.cs:77
2015-01-24 12:35:23.662 AutomapperProblemReplicate[601:149248] critical:   at System.IO.StreamWriter..ctor (string,bool,System.Text.Encoding,int) [0x00076] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.IO/StreamWriter.cs:146

We spent quite some time debugging this… only to discover much later the culprit was something else entirely.

It was AutoMapper. Very strange indeed… remove all Mapper.CreateMap calls and Mapper.Map etc – and voila, problem gone.

We’ve raised an issue on the AutoMapper GitHub. It’s not been accepted or reviewed yet, so it’s not officially recognised, but maybe this post will help you anyway.

https://github.com/AutoMapper/AutoMapper/issues/669

File read problems on Xamarin + iOS

The repro code for this post can be found here: https://github.com/jakkaj/Repro.

Note: The solution to the problem is not in that repro, it’s below. The repro helped us figure out what was happening.

I was having some quite severe issues when reading content in my Xamarin.iOS app. Data would either come back corrupted (out of order) or the file read operation would return the entirely wrong data (old data!).

The corruptions were what tipped it off first. We were saving serialised entities to the filesystem but when reading them back again the JSON parser started throwing errors. The text would be out of order, parts replicated, and double end braces and other strange bits and bobs.

The problem was using IsolatedStorageFile! Don’t use it! It sort of works sometimes… seems the problems occur after a while. I didn’t get to the bottom of exactly what was causing the problem or why, but essentially don’t use it!

Instead use File.WriteAllText and the other related methods as outlined in the Xamarin documentation here: http://developer.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/.

For a working example see https://github.com/jakkaj/Xamling-Core/blob/master/XamlingCore/XamlingCore.iOS/Implementations/LocalStorage.cs.

 


        public async Task<bool> SaveString(string fileName, string data)
        {           
           var path = _getPath(fileName);
            _createDirForFile(path);

            File.WriteAllText(path, data);
            return true;
        }

        void _createDirForFile(string fileName)
        {
            var dir = Path.GetDirectoryName(fileName);

            //Debug.WriteLine("Creating Directory: {0}", fileName);

            if (dir == null)
            {
                return;
            }

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }

        // <summary>
        /// iOS 8 Specific get path
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string _getPath(string fileName)
        {
            var documents = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User)[0];
            var str = documents.Path;
            var result = Path.Combine(str, fileName);
            return result;
        }

Jordan.

Developer User Experience – It’s your Job!

This is an excerpt from my up coming TechEd Melbourne Talk entitled Xamarin with a View.

As a senior developer, software architect or just all round gun developer – your duty is to set up your projects for your end users…

And by that I mean other devs. You are responsible to choosing patterns and practices to keep them in the game, to reduce work, complexity and improve quality.

That is squarely your job – you facilitate them. They are your end user.

So often devs go in and set up projects the “correct” way with out any regards for the devs that actually have to sit there and use it. I see this a lot especially with consultancies. They give you best break neck up to date stuff on the latest nugets -> then leave with no regard for developer user experience – there is no elegance to it. Just smashing things in there and leaving them is just not good enough. It’s easy – you need to finish the job.

Your framework set up needs to be the sheep dog, the guardian angel and their roadblock all at once.

It must be super easy for devs to introduce new code using your conventions and patterns – it should be so hard to get wrong it’s embarrassing.

Your developers will be forced in to using the best patterns and practices without even knowing it half the time.

I want you to consider these things when you’re next setting up a project or when you’re asked to make framework choices.

I want you to join me in improving the Developer User Experience (DEVUX).

Developer UX – something that I think we don’t consider enough.

Of course I’ll be showing some techniques on how to do this!

Jordan.

Time Period Library for .NET

Extensive time period calculations and individual calendar periods.

A while ago we had to write an EPG for a WP8 TV app that we’re building for a client. As part of this we had the need to do some pretty difficult DateTime calculations.

Finding out if a C# DateTime is within a time range is hard. Finding out if two time ranges intersect is even harder!

Install this little Nuget package and you can do stuff like:

var cellTimeRange = new TimeRange(nowTime.AddHours(-2), nowTime.AddHours(3));
var timeCellsInRange = cell.TimeCells.Where(_ => new TimeRange(_.StartTime, _.EndTime).IntersectsWith(cellTimeRange)).ToList();

https://www.nuget.org/packages/TimePeriodLibrary.NET

How cool is that!

Did you know you’re a consumer?

I’ve been talking to a lot of people lately about how they are replacing their PC with tablet and slate devices and they’re trying to convince me that the “post PC era” is upon us. Apparently you can do all your work on one of these devices and the PC is no longer needed. People are starting to buy an iPad rather than have a family PC and apparently they are just as effective at “work” and hence there is no need for the household PC.

I couldn’t disagree more.

I think we have a differing definition of “work”. Sure you can send emails, and create presentations and all that, but is it really work? I mean, to me – an email is just a long drawn out text based meeting. Presentations, well – lucky for you some people out there still need to have slides smashed in their face before a meeting is called a success. You can even buy a $30 adaptor for your iPad to plug directly in to the projector! Sure you may be able to use your tablet to help perform your duty at work – but mostly you’ll be just reading things that other people have created. If you use your tablet as a work aid, then you are most likely a consumer. 

“But we have wordprocessing, spreadsheets you name it!” they scream at me. Yes, yes and yes. First off, you should get a Surface as it has big boy Office programs on it (okay, that’s a rant in a rant). Secondly, is it enough that you *can* do this on your device? Is it enough to convert you from CONSUMER to CREATOR?

I’ve been thinking about this for a while now. I’ve been very worried that by people leaving the PC platform in favour of tablet we’re reducing the world’s digital creativity – we’re creating a bunch of consumers. Sure, one market segment that is way up is photo creations I’ll give you that. All the technological advancements of the human race have culminated in PHOTOS and SOCIAL. Currently people seem to be more interested in taking shitty photos of their shitty food and sending it to their shitty friends. I remind you – your “power” on a tablet with a locked down app store is limited to the functionality that the application designers allow you. You are at the whim of some other people who’s main goal is to make money (from YOU) – to lock you in, to get you to sign up, to share your shitty photos.

So, my analysis of the downward trend in the PC industry: we’re sorting the men out from the boys. People who would have once purchased a full PC are now buying a tablet (okay iPad) – but that’s okay as a large segment of that market we’re never going to be contribute anyway. They merely consume. They purchased the PC and didn’t use 99% of it’s capability. Maybe some browsing. Maybe some shitty game their friend gave them. Some viruses, a browser history full of porn. Cracked version of Office perhaps. These are the consumers and tablets are helping us filter them out in to light. The sales figures alone demonstrate just how much of the world consumes versus creates. There was an interesting talk at TEDxSydney about how people do not label them selves what they really are and one of the examples was consumers – people rarely label themselves so. Hmph.

And you know what? That’s just fine by me. Just don’t pretend you are not a consumer. It just turns out that there are a lot more consumers out there than I realised. It’s not a negative thing – it’s just a realisation. 

I’ll finish you by challenging you – if you really think these new devices are as good for work as a PC, buy your kid one to use for high school and university. Didn’t think so. Becasue that’s real work.

Code from my TechEd Australia 2012 Sessions

This year at TechEd on the Gold Coast I delivered two sessions:

DEV324: Windows 8 with a view

A session where I took MVVM as a base to launch your applications to the next level. 

WPH222: Windows Phone SDK – Be productive straight out of the blocks

Think of this one as you’ve started your first serious application, what are some of the common issues you’ll run in to, and what are the common techniques you’ll need.

https://webjak.blob.core.windows.net/posts/Teched12/Teched.zip

 

 

DataStateBehavior for Windows 8 XAML Applications

Note: Knowledge of MVVM and Binding etc is assumed.

You can download the source from here

At Xamling we work very hard to maintain strict standards and practices during development – one reason we do this is to maintain the best parallel workflows between design and development as we can.

Something that we’ve used extensively in the past with Silverlight is the ability to create DataStateBehaviors, which allow us to bind values from our view model to our visual states. When those values change a VisualState is automatically selected, meaning that we can separate our XAML and code very nicely.

An example might be a view that has two states: UserLoggedIn and UserNotLoggedIn. Depending on the value the VM supplies we want to switch these states.

You could imagine in the past with Silverlight and Expression Blend interactivity stuff, you could do the below:

<Behaviors:DataStateBehavior TrueState="UserLoggedIn" FalseState="UserNotLoggedIn" Value="True" Binding="{Binding IsLoggedIn}"/>

Well after much mucking around tying to keep some semblance of parallel workflows and code that is *not* aware of the view, I decided to bite the bullet and see if the DataStateBehavior could be implemented.

I went on the hunt, and found a number of sites that allow us to replicate behaviors, and using some code pinched from the Expression Blend samples site ages ago, I managed to get it working.

First, the excellent post by Joos van Schaik was a great start, and he even has a nice little library that we’ll use here: http://winrtbehaviors.codeplex.com/.

Grab that, and add it to your project. (there is a copy in the sample, but please see attribution above).

Next, Miguel Fernandes had a great idea to use the BindingListener from the WP7 Prism Phone project on codeplex.

With these two bits, now all I had to do is dig out a class from years ago that was pinched from the Express Blend Samples site, and modify it to work on XAML WINRT.

Once you’ve done that, add a propery to your view model – in the sample the propery is IsLoggedIn. It starts as false, then after 5 seconds moves to true. The sample view model is in ViewModel/SomeViewModel.cs.

I’ve also added a couple of grids to the MainPage.xaml, one for logged in and one for not logged in.

There are two states, once again for the login status.

Finally, I’ve added in the DataStateBehavior itself:

<Behaviors:DataStateBehavior TrueState="UserLoggedIn" FalseState="UserNotLoggedIn" Value="True" BindingName="IsLoggedIn"/>

NOTE: We use BindingName, which is a string unlike the original binding in the Blend stuff, this is because WinRT seems to pass through the bound value, not the actual binding class itself.

NOTE: This only works when the behavior is attached to a control (will not work on FrameworkElements etc like Grid). So bang it on your UserControls.

NOTE: This wont be “Blendable” – i.e. no UI to manage the behavior like in the past 😦

NOTE: Sample is built on VS2012 RTM.

You can download the source from here