While this results in files that are difficult for humans to read, browsers are still able to load and parse the data (unless the minification process has been a bit heavy-handed).
These files are normally used in preference over the unminified versions because of the reduced file size – making for quicker page load times.
Now, I’ve already reviewed an online ‘Unminifier’ but that doesn’t mean it’s your only choice – as we know, the Internet is full of choices.
Enter unminifycode.com – a simple website which will take your minified file contents and present it in a more readable format, adding the whitespace and formatting back in. It obviously won’t try to rename any variables or functions that were shortened during the minification process.
Simply copy the file contents and paste it into the large text box and click ‘Unminify’ – I’ve used moment.min.js here for demo purposes (I know that the unminified version is easily downloaded)
After a short delay the nicely formatted code will be presented and you can just copy it and paste it as you see fit.
Comparing the output of each tool the only differences appears to be a bit of whitespace – nothing that would affect the validity of the content itself.
So there you have it, you wait for an unminification tool and then two come along 😉
As we enter week six of the Covid-19 lockdown here in the UK I am still ‘between contracts’. I’ve had a handful of video interviews but these haven’t led anywhere yet – but I’m not sitting around idle.
Notwithstanding the decorating, gardening and spring-cleaning (of office and summerhouse – I’m not trusted to attack the house itself) I have been hitting Pluralsight online tech training hard for the past few weeks.
Taking the time to get up to speed with the most recent changes in .NET Core, Blazor and Xamarin were an initial target for my attention but I’ve subsequently moved on to those courses that I had bookmarked thinking – “that would be interesting/useful to look into if I ever get time”. Well now I have the time.
I’ve been digging into the world of NoSQL, PostgreSQL and Django with a view to porting an existing pet project using the latter two.
On top of all the training I’ve been performing some housekeeping on my servers (actually Digital Ocean Droplets), installing updates, running SSL Lab and Security Headers scans and even deleting a couple that weren’t really needed anymore.
I’ve even been able to do some aggressive housekeeping on my Synology NAS; removing obsolete VirtualBox images and duplicated files while refining the folder structures and configuring a decent backup to Amazon S3.
This week, in addition to hitting the job boards I will be looking at updating the NuGet packages on my deployed website projects and mobile apps and hopefully getting my Secure SMS project pushed to Github – even if it is in a ‘Proof of Concept’ form (read that as functional but ugly).
The police chief was forced to u-turn in his threat while the forces involved with the other two incidents say that the officers were ‘well intentioned but over zealous’ – but to my mind, that’s not the point.
The point is that there will always be people in a position of authority or power who overstep their remit – and when it come to our privacy that’s not a good thing.
The UK Government, along with many others, are trying to force technology companies such as WhatsApp to provide backdoor access to encrypted, private conversations of their customers.
Now, the Government will say that this is for the safety of us all and that they are only targeting bad people – you know terrorists and pedophiles – and access to the private data will be strictly controlled.
But as I’ve previously posted, if the likes of WhatsApp were to provide such access then the bad people will just use something else, leaving us with a hobbled and insecure messaging platform.
We would not only be at the mercy of hackers but also the sort of ‘over-zealous’ agencies who would now be able to trawl over our private conversations. Bearing in mind that most (if not all) of the bad people will have moved away and that the Government will be keen to show some justification for having applied pressure for access to the data, I think it will be inevitable that innocent people will come under unwarranted scrutiny.
I also proposed the development of a Secure Chat application, “SecureXamChat”, to prove the point that it was trivial for any competent developer to write such a thing.
The one sticking point that I kept thinking about was the transport layer – the mechanism of actually sending and receiving messages (the actual encryption/decryption etc is pretty straightforward).
I didn’t want to use the systems provided by the big tech companies as this would place a barrier in front of users with a non-technical background. I wanted something that didn’t need any advanced configuration.
One day it just came to me – why don’t I just use the transport mechanism built into just about every phone out there, that is the Short Message Service – or SMS as we all know it.
Well, the Covid-19 lockdown has given me a lot of time and I’m currently finishing off an early proof of concept (that means functional but ugly) Android application which will allow users to send and receive encrypted SMS messages.
The application, written in Xamarin, will;
Generate a Key Pair based on a password/passphrase
Allow users to share their PUBLIC keys via QRCode scanning
Encrypt text messages and send them via SMS
Decrypt received secure messages
I should reiterate, that the aim of this development is NOT to help the bad guys. It’s to prove to the UK Government that;
Forcing companies to weaken the encryption of their products will not achieve their goal (unless the goal is the ability to snoop on the public at large of course)
Encryption is out there – it’s just Maths. You cannot but the genie back in the bottle.
I should finish the development of the application in the next few days, maybe a week as I’m not solely working on this. Once I have it in a workable state I’ll Open Source it by pushing the code to Github.
I may well polish the code and the User Interface but this is not intended to be a production ready application. I’m not intending to release this to the Play Store and I’m certainly not looking to make any money from this.
I’ll post again once development of the Proof of Concept is ‘complete’. In the meantime remember;
When privacy is criminalized, only the criminals will have it
In my previous post I stated that ‘As Directors we are not able to furlough ourselves and therefore would not be eligible for the Governments Covid-19 Job Retention Scheme‘.
I also said ‘the details of these measures are still coming out and there is a great deal of confusion so what I’m about to write may well change going forward‘ – and it has (although a bit quicker than I expected).
If you don’t know who Martin Lewis is then check out the Money Saving Expert website. Basically, when this guy says something, especially it’s all in CAPS then he’s checked and double-checked the facts. He wouldn’t make this kind of statement without being absolutely sure.
If he says that Limited Company Directors CAN furlough themselves – even if they are the sole employee of the company, then that’s good enough for me.
So, what does that change?
Well, for me it doesn’t change anything at all. I am in a position where I can operate as normal, i.e. I have a dedicated, fully equipped home office. All I am missing right now is a client but, as I don’t intent to furlough myself, I can continue to search and engage as before. I can still work for the company – it’s business (almost) as usual in that respect.
Obviously, this may not be the case for everyone and if 80% of their salary would make a difference to their ability to see this thing out then they should take it.
But that’s the sting here isn’t it – most contractors pay themselves a minimal salary, topping them up with regular dividends. So 80% of £750 is £600 a month – in most cases this is far short of their normal income and maybe not enough to keep them afloat and that’s a major concern.
But contractors who are shouting about being ‘forgotten’ and ‘left out’ really don’t understand the slippery slope they are treading – especially with IR35 set to raise it’s ugly head once more.
Huh? What’s IR35 got to do with this?
This is what Andy Chamberlain from IPSE had to say about contractor complaining about being ‘left out’ of the Self Employee Income Support Scheme:
I urge you to click the above tweet and then read the rest of his thread.
If we want to be treated as regular businesses and not caught up in ill informed Employment Status determinations and blanket contractor bans then we have to accept the fact that we have done this to ourselves.
Help is being offered to us but as we decided to pay ourselves in the way we do and now it has come back to bite us.
Not a popular opinion I’m sure – but that’s where we are.
Covid-19 Self-Employment Income Support Scheme (link)
Now, the first of these aims to prevent companies from having to make their staff redundant by paying 80% of their salary up to a maximum of £2500. The employees must be ‘furloughed’ which basically means that aside from training they are not allowed to do any work for the company.
While this is pretty generous for employed staff, the self-employed were up in arms that they had been left out. While there were other avenues opened up, e.g. Statutory Sick Pay which the self-employed are not normally entitled to, these provided much less in the way of financial support.
It took a week for the Chancellor to present the second scheme aimed at the self-employed which offered the same 80% but this time over the average monthly profit as submitted in the previous three years tax returns.
The fly in the ointment is that these payments won’t be available until the beginning of June 2020 but the Chancellor insisted that other sources of funds were available from banks etc and combined with the other measures, e.g. mortgage holidays, this was the best that could be done.
All sounds ‘good’ what’s the problem?
Now, all that is unprecedented – the government stepping in to pay employee salaries and the lost income of the self-employed, but where does it leave the UK’s contracted workforce? In particular what about those who, like myself, operate through a Limited Company.
Well, many contractors consider themselves to be self-employed; after all the company is theirs and they employ themselves so they presumed that they would be covered by yesterdays announcment.
Reading the details of the Self-Employed Income Support Scheme it was quickly found that this would not apply to us;
Those who pay themselves a salary and dividends through their own company are not covered by the scheme but will be covered for their salary by the Coronavirus Job Retention Scheme if they are operating PAYE schemes.
Most contractors operate in this manner, i.e. we pay ourselves a minimal salary and then withdraw dividends from the company profits.
For the avoidance of doubt, yes we do this because it is more tax efficient than taking a ‘proper’ salary. This does not mean that we pay no tax at all – far from it. My company pays Corporation Tax and Employers National Insurance while I pay my Personal Income Tax via self assessment.
With that out of the way let’s look at the Coronavirus Job Retention Scheme as directed above.
Well, it will pay 80% of the our salary up to a maximum of £2500 a month. But as contractors normally pay themselves a minimal salary, circa £700-800 a month, this won’t add up to much at all.
It should also be remembered that the payment is dependent on the employee being ‘furloughed’ and essentially forbidden from performing any duties. But as Directors of the company, how can we do that? Monitoring the bank balance, paying invoices, marketing, chasing new contracts – this is all work and would mean that we would not be eligible for this scheme anyway.
[This is at least the current advise from my accountant and from many other sources out there. It is however a point of contention so as I said at the start, it may be subject to clarification]
So why are contractors being “left out”?
Well, step back for a minute. Is it just us that can’t claim from these schemes? Have we being singled out because we’ve been kicking off about IR35?
No, we haven’t.
All company directors will be in the same boat – none are self-employed and none can be furloughed (if the current understanding is correct).
I was a director of another Limited Company some years ago – nothing to do with contracting, just a “regular” business. From what I understand if I was still there I would be as ineligible as I am now.
Think about the directors of the last clients you worked for (assuming it was a Limited Company and not another Contractor) – what’s their position?
If we want to keep the argument against IR35 alive we need to realise that we are no different from those other companies.
Yes, it sucks that everyone else seems to be getting bailed out while we aren’t – but that’s just how it is.
We’ve all had periods ‘between contracts’ and while I don’t look forward to them I do try to plan for them. I know that I can survive a few months with nothing coming in. It’s uncomfortable to watch the bank balance draining but at the end of the day but that buffer is there for a reason.
And here’s the kicker – and it won’t be popular
If we raise Mary Hell about this then we are eroding our argument about IR35.
If we demand to be treated differently to all the other Limited Company Directors out there – then we are essentially saying “we are not like those regular companies”.
When we get through Covid-19, and we will get through it, will we then start saying – “we are just regular companies so IR35 shouldn’t apply to us”?
My standpoint (for what it’s worth)
I don’t see myself as ‘self-employed’. I am a Director of and employed by a Limited Company – a legal entity in it’s own right.
That company provides services to others (end-clients) but I remain an employee of the company and not of those clients.
Even if I was able to furlough myself from my company, which current advice says I cannot, then it really would not be worth it from a financial standpoint.
I would much rather make the effort to keep my company afloat, to dig in and work through this – or at least ride it out.
Yesterday (17th March 2020) the Government announced that they would be postponing the rollout of IR35 changes into the private sector due to the Coronavirus outbreak.
Despite the Minister referring to ‘off roll payroll working rules‘ (maybe indicating that he has no real idea what they are) he confirms that the changes will be tabled again ready for implementation in April 2021.
This comes far too late for many genuine contractors and associated services such as accountants who have had to close their businesses down as clients imposed blanket bans or ‘Inside’ determinations requiring the engagement of Umbrella companies and significant reductions in income.
It also comes the day after HMRC provided evidence to the House of Lords and were found seriously wanting in their response to scrutiny. While the House of Lords cannot force Government to defer the bill we have to hope that this contributed to the decision to pause the rollout (regardless of what they say).
The #StopTheOffPayrollTax campaign has been very active on Twitter and in organising a march on Parliament – but it appears that it took the Global Coronavirus Pandemic for the Government to realise that the proposed implementation and it’s consequences were out of step with the rescue packages it had announced for ‘regular businesses’, i.e. not the self-employed.
Many people think that it’s just IT Contractors that were going to be affected but it soon became clear that the flexible workforce is woven throughout our society. From the hospitality sector to veterinary surgeries, from the NHS and pharmacies to driving instructors. As the extent of the impact became more widely understood the noise started to grow.
But when Dr Iain Campbell started to highlight the strain that the draconian changes to the IR35 legislation would bring to the front-line NHS staff treating those infected with the Coronavirus did things become very real indeed.
So What Now?
Well we are not out of the woods yet – not by a long shot.
In the above video clip the Government confirm that this is a delay and not a cancellation of the changes being rolled out into the private sector.
So, despite all the evidence the Governments standpoint is remains that;
‘People doing the same job should be taxed the same way’
The UK Government and HMRC
Apparently this is regardless of the fact that they will not receive the additional benefits that the tax contributions buy their employed counterparts, e.g. statutory sick pay.
The last few months has been a stark warning that unless the legislation is changed or proper guidance is provided to end-clients then we will be in the same position twelve months from now. Teetering on the edge of a flexible workforce implosion.
I think it’s far more likely that nothing will change from the Government apart from a renewed desire to get the changes implemented – so it’s down to the end-clients to get up to speed with the ins and outs of IR35, unless they want to see contractors walking off site in their droves (and they will – that’s been shown!).
Working Outside IR35 is not (in my opinion) that hard and by making very few changes to working conditions most (but not all) of the roles determined to be Inside can easily be moved Outside IR35- and in a manner which can be defended if need be.
The problem is that end-clients don’t understand IR35 enough to be able to say with confidence that the legislation does not apply to a role. This is further compounded by the fear that HMRC will come after them for tax which is deemed to be unpaid should they disagree with the employment status determination.
It is this fear that has left the flexible workforce facing extinction – being forced to make a choice between contract termination or being ’employed for tax purposes’, but not for employment rights!
But the onus doesn’t lay solely with the end-clients – we, the flexible workforce, need to take these twelve months to help them understand what Outside IR35 means and why we are so important to them.
And it’s not only the end-client that needs to be brought up to speed.
We all know that there are contractors out there who are operating contrary to the legislation (knowingly or otherwise). They need to be educated as to how to operate in a compliant manner or called out as a disguised employee.
People are on Twitter claiming victory but we are a long, long way from winning!
The Government seem to accept that the changes were going to have a massive negative impact on a large number of businesses, otherwise the suspension of rollout due to the ‘ongoing spread of Covid-19 to help buinesses and individuals‘ would make little sense.
If they are set on this course of action then the flexible workforce and the end-clients we offer services to need to be ready for the changes which seem inevitable.
I’m currently working on a new privacy application for Android and in a previous post I guided you from the Xamarin.Android Drawer Navigation project template to something that actually worked (as in you could actually use the pretty navigation provided by the template).
Now I wanted to change the menu items to something more relevant with some appropriate icons – I mean, how hard can that be right?
Well, as with everything in development these days – things are not always as easy as they seem to be.
The source code from the previous post can be found on Github and if you take a look you will find the menu defined within an XML file at ..\Resources\menu\activity_main_drawer.xml. A number of items are defined here with the same basic attributes:
So, all I need to do is to change the android:icon attribute to point to the drawable I want ….. and that’s where the “fun” started.
If you’ve worked with drawables in Android you will know that you need multiple versions of the same graphic at different resolutions. This will allow different devices, with different screen resolutions to display the appropriate graphic. You can find more information here: https://developer.android.com/training/multiscreen/screendensities.
If you look at the above article you will see that five different resolutions (screen densities) listed – that means you need five versions of each of your graphics for your app (although there are instances where you can get away without all of them).
There are online tools to perform the generation for you but the resulting assets still need to be extracted and copied into the project.
Then comes the small matter of what icons to use – and where to get them from.
Android comes with built-in icons, like the ic_menu_camera asset in the above menu item. But finding a list of these isn’t, as I’ve found, that easy and Google recommend copying the icons you need (at all require screen densities) into your project and not to rely on them being present on any particular users device.
So, is there a better way?
Well, as the title of this post eludes, we can use fonts instead – yes, you read correctly … Fonts!
After a little bit of searching I found a blog post by James Montemagno in which he describes using the FontAwesome font in Xamarin.Forms projects.
Well, I’m not using Xamarin.Forms, I’m using Xamarin.Android but if one can do it then surely the other can too.
Checking out the Readme on Github it certainly looked like this was the answer to my problems, there was just one wrinkle – it was written in Java.
No problem you say – just man up, roll up your sleeves and create a Library Binding project. Yes, I could do that – or I could see if someone else had already ported it over to Xamarin – which of course they had.
If you head over to https://github.com/PragmaticIT/xiconify you will find the source and can dig through it at your leisure – but the Readme points to a nuget package which can be easily installed into your project, so that’s what I did and as you can see from the image below, I selected to ‘Material Design’ package.
Once the package is installed it needs to be initialised in the applications Main Activity:
When I checked Twitter this morning my heart sank – I was watching the new Chancellor (Rishi Sunak) regurgitate the HMRC view of IR35 and the changes to be rolled out into the private sector in April.
He was essentially announcing the Death Knell of Flexible Working as we know it – the contract market will shortly implode even further than it already has.
We, the contracting community had hoped that the fresh faced minister would pause the roll-out and call for the review that was promised ahead of Decembers election.
Instead he stated “it’s not fair to all the people who is employed that someone else who is doing the same job is paying less tax” – the cornerstone of the HMRC argument for making the changes.
On the face of it that may be a reasonable stance to take – but they are not comparing apples with apples here (and they damn well know it).
While we make be doing the same job we are engaged on a very different basis.
We have structured ourselves to operate as service companies to offer clients a flexible resource as and when they need it for as long as they need it (and no longer).
Notwithstanding the fact that contractors are not entitled to sick pay, holiday pay, pension contributions and other benefits such as professional development (training), gym membership and health insurance. Sure, not all of these are covered by the tax & National Insurance they pay but the overall package makes them an employee.
Add to that the notice period that they benefit from, normally a month but can be more, and the fact that even if there is no real work for them to do their employer is still obliged to pay them for turning up. Even if they ‘let them go’ they would have to pay them for their notice period (and any untaken holiday pay!)
Contractors normally have very short notice periods, if they have one at all, and their contract can be terminated at anytime for just about any reason – there is no guarantee of work (and no expectation of it – that’s the life of a contractor).
So, what’s changed?
IR35 itself – the legislation (as complex and unfit for purpose as it may be) – will not change. Determinations on employment status will still need to be made with reference to this legislation.
What’s changed is who makes that determination after April 6th 2020.
Since it’s introduction around twenty years ago, it was the contractors responsibility to determine their employment status. If that determination indicated that the role was Inside IR35 then they would be liable for the payment of tax as if they were an employee. If it was Outside IR35 then this did not apply.
With the benefits of being Outside IR35 pretty clear cut – most contractors preferred that arrangement.
The problem is that some contractors were not as diligent (or just blatantly avoiding paying the additional tax) and declared themselves as being Outside IR35 when the contract and/or working conditions didn’t support that determination.
HMRC claims that as many as 9 out of 10 contractors are operating in this manner – but have not be able to substantiate this claim. The generally accepted figure is less than 30% of contractors are declaring themselves as being Outside when their working conditions are such that they should really be Inside.
So, in April 2020 HMRC will require the end-client to make the employment status determination instead of the contractor.
What could go wrong? If the end-client is using the same, unchanged, legislation as the contractors have been for years then surely this will put things right …. won’t it?
Well, along with the responsibility for making the determination comes the responsibility for getting it wrong. By wrong I mean making an ‘Outside’ determination which HMRC later decide should be ‘Inside’ (they won’t be interested in the other scenario).
Should an end-client incorrectly determine a role to be ‘Outside’ then they will be responsible for paying the tax that HMRC deems to be owed – which could be thousands of pounds here.
That’s the kicker here..! Companies are generally risk averse and locking horns with the taxman is something they would quite rightly want to avoid.
Companies have looked at their contractors and thought – “if we get it wrong and have to pay back-tax for them then is that a risk that we can sustain?”
The answer in most cases is, understandably, No!
Despite claims (lies?) by Finance Minister Jesse Norman in the House of Commons that it’s not happening, many companies are making blanket determinations that mean either:
They will not use contractors in anyway shape or form after the changes come into force
All roles will be deemed as Inside IR35 regardless of the outcome of a proper determination.
Many contractors are being walked out of the door by shortsighted clients fearful of HMRC while others are being told that they can stay only if they move to being ‘Inside’ (taking the tax hit in the process – for no perceivable benefit).
What are the implications?
This clearly shows a misunderstanding of the legislation and flies in the face of requirement for due diligence on a case by case basis that was assured (and even required by HMRC).
But just think about it for a minute – what are the implications of moving from being ‘Outside’ to ‘Inside’ with the same client? What is that actually saying?
Surely that indicates that, assuming the role hasn’t actually changed, the contractor accepts that they had previously been working on the wrong side of the legislation and is therefore liable for the tax they will now be deemed to have avoided as a result. Who in their right mind would sign up for that?
HMRC have apparently said that they will not investigate the retrospective status of contractors making this move from Outside to Inside – but after everything that’s gone on in the past few months, why would we trust them? Are they really saying that they would ignore cases of potential tax fraud?
Now, not all companies are making this blanket determinations – some are actually doing it properly and you can use the OffPayroll.org.uk website to see who is doing it right and who is not.
How’s the future looking?
If I’m being honest, as it stands right now, I’m not that hopeful. The House of Lords is conducting a review of the impact of the changes but I’m not sure what they will conclude. Even if they agree that the changes are excessively damaging I’m not sure whether they can actually call a halt to the roll-out or just make a recommendation.
It is clear that the government (small ‘g’ is intentional!) is going to plough ahead with the change – regardless of the evidence that it may mean that a significant number of contractors will be forced out of their current engagements and maybe have to close their businesses down. No doubt they will claim that these people were operating contrary to the legislation and that the changes have been successful in their aim.
Fortunately I’m currently engaged with a small start-up company which will be exempt from the proposed changes – so the employment determination remains with me.
I’ve had the contract independently reviewed and it has come back as being Outside IR35. The client is aware of IR35 and are happy for me to operate in a manner that will demonstrate that I am indeed Outside.
In a couple of months I will draw up a Working Conditions Declaration for the client to review and sign. This will help support the ‘implied contract’ concentrating on how the services are being provided and how they differ from employment.
The contract should run for another five months (but may finish earlier – I’m a genuine contractor remember) and when it concludes there is no obligation for the client to offer another (or for me to accept it).
So my hope is that, in the four months between the changes coming into place and the contract ending, clients will see that blanket determination and bans are not working for them and that the contract market is in recovery.
Failing that I will have to hope that I can secure a contract with another ‘small company’ where I will be responsible for my employment status determination or that a larger client is engaging with contractors and operating in a fair with regards IR35.
If these things do not come to pass then I will, with a heavy heart, have to close my business and look for a permanent position instead. My income will be lower and my flexibility will be gone but I will have employee benefits and paying the tax to ‘earn’ them.
Taken as a whole the taxes that HMRC will receive from me, i.e. personal and corporation, will be reduced as a result. With the stated intention of these changes being the increase of revenue this kind of flies in the face of what will actually happen.
There is still time for the government to delay the roll-out (maybe based on the outcome from the Lords, maybe common sense will prevail) – but all we, the Flexible Workforce, can do is watch and wait as nobody is listening to us.
It may sound odd but from time to time I get approached to review a book which is either due to be or has just been published.
I say odd because I’m just a regular developer – not a podcasting rockstar (or even a blogging one). Why would my option be worth a free copy of a book?
Maybe it’s because I’m just a regular developer – just like most of us.
Some of these I let pass me by, especially if I have no real interest in the content, i.e. a technology that I am not using and have no plans to use – F# for example. I frequently say that ‘you have to pick your fights when it comes to technology – you can’t win them all’.
So, when Packt asked if I would review this book it made me wonder:
“How much of a master can I be after reading a book that’s ‘only’ 200 pages?”.
I’m certainly not belittling the authors efforts, but I have a Microsoft Press book ‘Creating Mobile Apps with Xamarin.Forms‘ which is more than twice that length and that doesn’t claim to be able to make me a ‘Master’.
I’ve developed a number of Xamarin.Forms applications and do so on a pragmatic basis, i.e. I do what I know works without necessarily knowing (or really needing to know) the ins and outs of why it works. I get the job done and (hopefully) produce robust applications for my clients that satisfy their requirements.
The thing is that time passes and, like most other technologies, Xamarin.Forms is being constantly updated. It’s very easy to get out of date. That said, trying to keep up with every iteration can be soul destroying resulting in development paralysis – not being able to move forward in case you make a ‘wrong’ decision that may cost you dear in the future.
Every now and then it’s a good idea to ‘take stock’ and sharpen that saw. We can never know it all and we don’t know what we don’t know.
So, what about the book?
By assuming that the reader has a working knowledge of Xamarin and Xamarin.Forms the book is able to build on this and not waste time going over the basics. That said, we do start by creating a new project, discussing MVVM and Data Binding. These are a building blocks of a Xamarin.Forms application and it’s always useful to reinforce our understanding. You never know, it may just fill in a grey area or it may introduce some syntactic sugar that will streamline your development.
For me, the early parts of the book demonstrated a pretty slick method the validation – using base classes and INotifyDataErrorInfo (a new one on me). I can’t say I’d struggled with validation but my solutions always seemed like I was using a bit more code that I’d like – creating a potential maintenance headache for the future.
When it comes to Navigation, as in moving between views rather than physically getting from A to B, most of us may well use the built in Navigation API or rely on something like MVVM Light. The author decides to create a custom Navigation Service (and explains why), based on the built-in API to create a ViewModel to ViewModel navigation (similar to MVVM Light) that streamlines the code moves it to a central location. I really liked the result and will definitely be using this in the future. Don’t get me wrong, MVVM Light is all well and good but the simplicity of the presented code was compelling.
The development of the Navigation Service leads onto the use of the built-in Dependency Service but then quickly demonstrates how to replace this with third-party Dependency Injection, the author used Ninject. I’d recently used Unity in a project so while I knew this was possible it was interesting to see a different approach.
Building up the architecture in stages, swapping out bits and pieces the whole thing came together pretty quickly.
Some books I’ve read contain code that won’t compile due to typos and missing quotes and/or parenthesis which makes you wonder about the quality of what you’re reading.
All the code in this book worked first time – bear in mind that I wasn’t copy/pasting the code, preferring to hand type it in so that it has half a chance of sticking in my aging brain in the process. The only minor glitch was a call to Device.OpenUrl which is now deprecated (although it will still compile) – but at the speed with which Xamarin.Forms is moving this is hardly surprising and easily fixed.
The book goes on to cover Custom Renderers and Platform-Specific functionality – topics which can sometimes be overlooked as ‘out of scope’.
It doesn’t stop there though – we get to create an Azure based API with a database back-end. Then we add authentication (albeit Facebook authentication), crash reporting and application monitoring.
The end result is a fully testable (did I mention the chapter on Unit Testing?) application, with ;
Azure API and data storage
Crash Reporting and Monitoring
All in less than 200 pages! That’s no mean feat. The pace didn’t feel rushed or labored – I took a couple of days to work my way through the chapters and enter the code.
So, am I now a Master of Xamarin.Forms?
Well, I have to say – probably not.
What I can absolutely say is that I have leveled up and feel much, much better equipped to develop my next Xamarin.Forms application.
I gave this book a 5 star rating on Amazon and it could be said that it should only have been 4 – because I’m not a Master as the book ‘promised’.
But I feel that I learnt a great deal – while strengthening the foundation skills and knowledge that I had already.
So, I’ve had an idea for another privacy-focused application, this time aimed at mobile devices – Android in particular (I know that Apple are a little touchy about encryption apps – maybe I’ll venture into iOS at a later date).
Notwithstanding my desire to keep my skills up to date I knew that the project I have in mind would require a lot of platform specific logic. While Xamarin Forms can handle this I prefer to take the hit, roll my sleeves up and I opted for a native Android project instead – and that’s where the trouble/fun started.
If you go through the ‘New Project’ process below you will end up with an application which will look something like the one above;
Yep -just what I needed, an application with a slide out menu. Now all I need to do is to replace the default options with my own and then open the appropriate views when they are clicked – what could be eaiser?
Well, when you venture into the code you will find the following event handler within the MainActivity class:
Hmm – so no actual code in place for when an option is selected then!? Running the app and selection various options confirms this is the case. So how hard can it be … really?
In the past I’ve used the Xamarin Forms Drawer Navigation model to create this sort of interface so was a little out of touch with the way native Android was doing things. I knew that I was probably looking at using Fragments, rather than Activities, to act as the content views but had never really used them.
Fragment is Obsolete – eh, what?
I know enough about Fragments to know that I needed a Fragment class and an associated Layout file (the view if you like).
I created a Fragments folder and, using the Add > New Item option, added a Fragment class.
The class was duly created and Visual Studio displayed a green squiggly under the Fragment base class reference. No, big deal – we’ve all seen this before, probably nothing too worrying;
Oh! It would appear that Fragment is deprecated – what the what?
This was rabbit hole number 1 – if Fragment is deprecated what do I use instead?
After a couple of hours trawling the Internet and generally getting frustrated I began to piece together fragments of information (pun intended) which led me to a solution, actually a couple of them.
Drop the ‘Compile Target’ from 9.0 (Pie) to 8.1 (Oreo) where the Fragment class is not marked as obsolete.
Reference the Support Library implementation of the Fragment class instead
Right, option 1 isn’t really an option unless you are happy to tether your application to Oreo. This may be fine for say a proof of concept but not really for a production application. An app compiled against Oreo should run fine on Pie and above – but your mileage may vary so make you you check that out!
Option 2 should not have come as a surprise to you or anyone else familiar with Android development – very few apps these days can be written without using the Support Libraries.
The complication came because when you search the Internet for information on the Android Support Libraries you will run into posts about AndroidX and Jetpack – which are essentially the new Support Library implementations. Trying to ties these back to Xamarin proved to be excessively time consuming and in the end I found that their implementations, e.g. nuget packages, are still in pre-release and documentation is sparce so I was reluctant to use them unless I really had no option. At this point I was considering using the Xamarin Forms option instead – but where’s the “fun” in that..?
The fix for my Fragment was to simply update the Android.App using statement to target the Support library instead:
No more green squiggly line and the application builds just fine – all I need now is to create the Layout and write the code to swap out the Fragments based on the selected option from the menu in the slide out drawer – simple…..!
Wiring Up the Fragments
If you look at the structure of the solution that the template generated you will see that the content of the displayed in the main area of the UI is contained in a Layout view called content_main (Resources > layout > content_main.xml).
Opening this up we can see that this layout consists of a RelativeView with a TextView inside it.
Fairly straightforward stuff here – but how do we swap our fragments in and out?
Well, as it stands – we can’t..! What we need to do is to change the RelativeLayout to a FrameLayout, give it an Id and remove the TextView (as it won’t be needed).
Now we have a container for our fragments we need to respond to the menu selections, inflate the appropriate fragment and ‘inject’ it into our FrameLayout.
I have created three fragment classes with associated layouts – these are pretty basic with the layouts containing a single TextBox each and the corresponding classes just inflating them. You can download the finished solution from the link in the resource section at the bottom of this post.
The first thing we need to do is to set the initial layout state and for this we will display the ‘Welcome’ fragment as out ‘Home/Landing Page’
To do this we will need a FragmentManager, in particular – a Support Fragment Manager. Fortunately our generated MainActivity inherits from AppCompatActivity so it already has a property containing an instance of this class.
To set our initial layout we will need to create and commit a transaction via the Fragment Manager – don’t panic, it’s three lines of code which needs to be added to the OnCreate method of the MainActivity.
protected override void OnCreate(Bundle savedInstanceState)
var welcomeTransaction = SupportFragmentManager.BeginTransaction();
welcomeTransaction.Add(Resource.Id.fragment_container, new Welcome(), "Welcome");
This will add in instance of a WelcomeFragment to the FrameLayout – essentially pushing the view onto it’s internal stack.
Now, I’ve seen a couple of trains of thought as to how to handle displaying the appropriate transaction based on the menu selection and they each have pros and cons;
Add all of the required fragments to the FrameLayout, showing and hiding them as required (the FrameLayout will store the fragments in a Stack)
Swap out fragments on demand so that the FrameLayout only ever contains a single child view.
With option 1 all of the fragments are loaded into the FrameLayout we are using as a Fragment Container with all but the initial view, in our case the Welcome fragment, hidden as part of the transaction. The upside of this approach is that it will maintain the state of each fragment even when it is hidden. The downside is that you will need to keep track of the currently displayed fragment so that it can be hidden when another menu option is selected and of course there is the memory consumption to think about – but this may not be a concern depending on your requirements.
Because my app is aimed at a persons privacy I don’t want all of the state to be kept in memory – when a menu option is selected I want the current fragment to be destroyed. With this in mind I’ll be implementing Option 2 and replacing the fragments as required so that the FrameLayout stack only ever contains a single fragment.
Scrolling down to the OnNavigationItemSelected handler we can now add our code to swap out the fragments (I’ve just updated the Gallery and Slideshow options here)
else if (id == Resource.Id.nav_gallery)
var menuTransaction = SupportFragmentManager.BeginTransaction();
menuTransaction.Replace(Resource.Id.fragment_container, new Fragment1(), "Fragment1");
else if (id == Resource.Id.nav_slideshow)
var menuTransaction = SupportFragmentManager.BeginTransaction();
menuTransaction.Replace(Resource.Id.fragment_container, new Fragment2(), "Fragment2");
So, almost the same three line as when we added the Welcome fragment (so a refactoring target) but this time we are replacing the contents of the FrameLayout (not replacing the layout itself, just it’s child views).
The result will be when the menu it opened (using the hamburger button or swiping from the left edge of the screen) and the Gallery or Slideshow option is clicked that the appropriate fragment will be loaded into the FrameLayout, replacing the one that was already these.
Most apps need some form of menu and the fact that the NavigationDrawer template provides all the nice UI it does leave the developer having to trawl the internet to work out what to do next.
Even though I knew that fragments would be required there was very little in the way of documentation to be found, specifically about extending this template. Add this to the rabbit hole that is AndroidX/JetPack and it can become frustrating for developers new to Xamarin development.
While this post walks you through one implementation there are doubtless others out there. If you feel I’ve missed something then either leave a comment below or head over to the Github repository to post an issue of submit a pull request (whichever works best for you).