[Updated] On an older Lumia Windows Phone? Why you should get Windows 10 Mobile now, how to do it, and what you will lose.

[Update 7/29: Microsoft has now officially blocked this route, pushing the Anniversary Update to the Release Preview ring, and removing support for the older devices.

If you have one of those phones affected and want Windows 10 Mobile, the only option now is to buy a new device, maybe on ebay or auction sites or discount retailers if money is a reason you haven’t upgraded yet. Low end Lumia 550, the 650 in the mid tier and 950/950 XL at the high end are all better devices than the windows phones that have come before them and are designed to run Windows 10, and so will be fully supported, as are devices such as the Lumia 830, Lumia 640 and 640 XL, BlU Win HD LTE and more. A full list is here ]

Windows 10 mobile was promised to all Lumia device owners running Windows Phone 8.1 and unfortunately Microsoft broke this promise with the official update. They did, however, run a preview program including those devices and it seems that the reason to drop those devices was partly based on feedback from users of those phone. That said, I still think users of those devices should get Windows 10 mobile.  This article is aimed at owners of devices such as Lumia 630, 635, 820, 920, 925, 1020 and others of the series.

  • Can my device be upgraded? For how long and what version of Windows 10 will I get?
  • Why should I upgrade?
  • What will I lose and what other reasons are there to not take the upgrade?
  • Will I get Skype?
  • How do I upgrade?

Can my device be upgraded? For how long and what version of Windows 10 will I get?

TLDR: Lumias ending in 20 or 25, as well as Lumias ending in 30 but with only 512MB ram can  though the Windows Insider app (choosing Release Preview), but for a limited time and only to version 10586. Newer devices can get Windows 10 with official support through the Upgrade Advisor app.

The Windows Insider program began with just a few devices, but expanded to include many of the Windows 8.1 Lumia devices.  It was hoped that with this expansion, all the WIndows 8.1 phones would get Windows 10, and indeed that’s what Microsoft had said. As already mentioned, this didn’t happen and many phones running Windows Phone 8.1 were cut off from official releases of Windows 10 Mobile. That said, you could still always join the insider program and get it. The good news is that this is still an option, though it won’t be for long.  The Windows Insider program was set up with 2, and then 3 different levels of risk and they are known as rings.

  • The Fast ring is the latest, greatest versions of Windows 10 but potentially buggiest ring.
  • The slow ring is more stable, and relatively stable releases that are pushed to the fast ring will get pushed to the slow ring after the fast ring folks have had some time using it and given feedback.
  • The Release Preview ring was launched with the launched to push previews of updates and fixes for the current production version of Windows 10 and doesn’t get the fast or slow ring bits until the next production release.

As we approach August 2nd, the date when the next Windows 10 version will begin rolling out for PC and mobile, we should expect that around that date the anniversary update will be pushed to Release Preview. When that happens, we believe the older lumia devices will no longer be able to get that version.

Technically, Microsoft has never said when they would cut older devices out from release preview, but that seems to be a reasonable date to do so, but they could do any time. So in my opinion, you should move fast and do it while you can.

Phones eligible for Windows 10 (redstone) anniversary:

  • All devices that launched with Windows 10 mobile pre-installed
  • Lumia 930, Icon, 830, 640, 640XL, 635 (1GB), 636 (1GB), 638(1GB), 1520,  730, 735, 532, 535, 540, 430, 435
  • BLU WinHD  and WinHD LTE
  • MCJ Madosma Q501
  • Xiaomi M4

Phones eligible for Windows 10 (threshold) production via Release Preview:

  • Lumia 630, 635 (512MB), 720, 820, 920, 925, 1020, 1320
  • BLU Win JR  and Win JRLTE
  • HTC Windows Phone 8X

Why should I upgrade?

TLDR: UWP, office, mail and calendar, notifications, settings, personalization, groove.

Windows 10 Mobile makes lots of small improvements over Windows Phone 8.1. Yes, not every change will be to everyone’s tastes and below is a section about that, but there are many improvements, to the OS as a whole, and to the first and 3rd party apps.

The number 1 most important reason to upgrade in my opinion is the new Universal Windows Platform apps or UWP. This is a new application framework that allows developers to write one application that will run on Windows 10 PC and Mobile (and Xbox, HoloLens, and “Internet of Things” devices). Microsoft and 3rd party developers are focussing their efforts on releasing apps using this platform, mostly due to the approx. 300 Million Windows 10 users they can get. These apps are not blown up phone apps on the PC, or scaled back PC apps on phone (or at least the well-done ones are not).  In general these applications are improvements over the Windows Phone versions they are replacing, offering more functionality and / or an improved layout.  As Windows 10 still runs Windows Phone 8 apps, if the developer hasn’t created a UWP version, you are not missing out. Plus, as this is where the developer focus is, this helps prolong the device and you are not relying on companies to continue to maintain the Windows Phone version.

More on the apps in a minute. What has improved about the OS in general? Well, you get more personalization options, with the ability to choose start screen backgrounds to be in the tiles or behind the tiles, change the font size (this can give you an extra column of tiles on small screens, or help with ease of use on big ones), and more control over the notifications area. There are visual and organizational improvements, most notably in settings which is now nicely organized and more easily searchable, though I also like the larger tiles on the start screen. Cortana gets some more functionality too. The notifications are now allows you to respond in the notification – i.e you don’t need to launch the app. Taking advantage of this is up to the developer but for SMS it’s very useful. There are other small changes all over – another one being the addition of a ‘nubbin’ to the on-screen keyboard to assist with cursor positioning which can help with awkward minor cursor position changes.

Here are a few pictures for comparison. Both phones pictured are Lumia 635’s.

Improved first party apps are a big part of it – some standouts include Mail and Calendar, Photo’s, Edge, and Groove Music, plus the OneNote and the office apps. All of these have undergone a massive overhaul and the results are very good. The Groove app in particular is leagues ahead of Xbox music and Edge brings improved rendering, capabilities and web site compatibility.

3rd party app improvements have also been noted. For exemple Wells Fargo, as well as some returning to the platform after killing their Windows Phone 8 versions, such as Bank of America.

What will I lose and what other reasons are there to not take the upgrade?

TLDR: Rooms, me tile, some people hub integration, here maps. Also potentially poor performance and unofficial support.

There are some losses of functionality and features, though in some cases it’s expected they will be turned off eventually anyway. For example, the Rooms feature is absent in Windows 10 Mobile and while you can access the shared OneNote, shared photo albums and the contact cards for people, you can’t access the chat’s that were part of the Room.  Microsoft would probably suggest GroupMe as a replacement, though it doesn’t have the same functionality as rooms did.

The Me tile, that allowed you to send a message simultaneously to services like LinkedIn, Facebook and Twitter and also provided notifications is gone. You just have to use the apps for each one instead. In a related change, there is less people hub integration now too.

Here Maps is not available for Windows 10. Indeed, I believe they have decided to cease making pdates for Windows Phone 8.1 as well, but if you have it installed it’s still there. You simply can’t get it for Windows Phone 10, unless it hangs on through an upgrade. That said, the Windows 10 Maps app is generally good, and much improved from since the Windows 10 launch when it was not good.  I do have a few issues with it still, the biggest being that traffic isn’t shown during navigation (it is shown when choosing a route) but I’m hopeful it will be fixed soon.

Lastly, is the reason that Windows 10 didn’t make it to these devices in the first place – it may perform worse on these devices than Windows Phone 8.1 did. I  have been using Windows 10 mobile on 3 devices, the Lumia 635, 925 and 830. The 830 has the fast ring build on and is my everyday phone, but from what I’ve seen on the other two, it’s perfectly usable and has performance is more than good enough, though your mileage my vary. This has improved as Microsoft has continued to release patches to the Release Preview ring and these fixes have made a positive difference to the performance and reliability of the system.

Will I get the new version of Skype?

TLDR: Maybe but probably not.

Skype support detal for Windows Phone
Skype support detal for Windows Phone

Skype has recently let folks know they were running 2 systems side by side and the old system will turn off in October and apps that relied on the old architecture will cease to work. This includes the Windows Phone 8.1 version, but not the Windows 10 version, which is currently in preview. This detailed on the Skype support page.  Being in preview, it’s only available for users on the Windows 10 anniversary fast and slow rings.  This makes it a guessing game as to who will eventually be able to install it once it releases. On the one hand, the Skype support page just says Windows 10 and it’s reasonable to assume that all windows 10 users will be able to get access to this, and when it comes out of preview, it will be available regardless of windows 10 version. On the other hand, it could be that it’s previewed only in the anniversary edition because it uses features only available in that edition.

My hope is the first version of events is true, but my expectation is sadly for the second. It might come, but don’t bet on it.

How do I upgrade?

TLDR: Make a backup, then get the Windows Insider app and follow instructions. Check for updates afterwards.

1.Make a backup of your device by going to Settings -> Backup. Select as may options as you might want to restore later. Also copy any files and folders that aren’t included in the backup  from your devices and it’s SD card to a PC, using a USB connection.

2. Download and install the WIndows Insiders app from the store. in the app, choose the Release Preview ring and agree to the terms. It should finish by saying that updates will be available via the Phone Update settings.

3. Prepare your phone by making sure you have at least 3GB space on the phones main device memory. This may be harder on devices with only 8GB of storage. Deleting music, videos, offline maps and podcasts, or large games should get you most of the way.

4. Go to Settings -> Phone Update and search for updates. You should see a pending update for Windows 10 Mobile 10586.xxx there.  (It may take some time for this to show up).  Choose to install it and be prepared to wait several hours for it to do it’s thing, especially on low end devices like the Lumia 635.

5. Once the update is installed, look for additional patches by going to Settings -> Update & Sercuity -> Phone Update and tap Check for Updates. Repeat this until there are no more (you should now be at  version 10.0.10586.494 or greater). Also open the store and from the menu, choose Downloads and Updates there and then Check for Updates and install any app updates – you will likely see a lot after the initial install.

Lumia 635, 925 and 830 all running Windows 10 showing app list.
Lumia 635, 925 and 830 all running Windows 10 showing app list.

So in the end, it’s do-able and in my opinion, the benefits outweigh the losses. Not everyone will agree with that but I honestly don’t think staying on Windows Phone 8.1 is a good option any more. It may have been 6 months ago, but not now. Of course, one way to change without going through this is just to buy a new phone – Lumia 550, 650, 950 etc, if you like Windows Phone and want to stay with a similar experience. Or there’s Android or iOS, but if you were headed that way, I’d imagine most have already gone.

Are there reasons to upgrade or stay put that I’ve missed? Probably – this has been an emotive topic for many, so lets have the conversation one last time. August 2nd is coming up fast so soon this won’t matter anymore. Or put another way, don’t put this off any longer.

Get the Windows Insider app
Get the Upgrade Advisor app

One design time strategy

Visual studio (and Blend) provide great tools to help you get an awesome design, and see how your screens / pages / controls are going to look.  Yet I work with several developers who never use the designer, at all, and go 100% XAML. On the other hand, I like to see what I’m doing without having to launch the app to test every little tweak.

The idea behind MVVM is that your View, View Model and Model are separate and don’t know (or even need to know) about each othero. However, as I create a view, I will use data binding to bind some content of the view to the properties of the view model, and if those properties are only populated at runtime, then it can be hard to tell how out view will look in the designer.

There are several ways of making your design time experience, but ultimately, most come down to generating design time data, or using a design time view model.  I prefer the latter so it’s that which I will focus on here.

Design Time View Model

Here’s the route I currently prefer, creating a design-time view model. The main advantages of this are easily customizable design time data and design time intellisense for bindings. The down side is the design data may get compiled in to your solution, and you may need to re-build to see changes in the designer.

While you can use your run-time view model with a default constructor to populate some design time data, this has many restrictions (if your run-time version would also use a parameterless constructor, it can be hard to decouple effects of setting one property on others for example – remember it’s real code being run). Therefore, I prefer to create an entirely separate class for the design-time version. However, I also propose using an Interface to help with having parity between the bindable properties of the real and design time view models.

The example below is for a view model for displaying some weather data.

	//for design data, you only need the property getters - things you will Bind to
public interface IWeatherDataViewModel
{
   string Location { get; }
	int CurrentTemp { get; }
	int TodaysHigh { get; }
	int UVlevel { get; }
	string TemperatureUnits { get; }
}

//real implementation has dependencies, etc
public class WeatherDataViewModel: ViewModelBase, IWeatherDataViewModel
{
    public WeatherDataViewModel(WeatherModel model, Settings settings)
    {
        this.model=model;
        this.userPrefernces = settings;
        RefreshModelCommand= new DelagateCommand(executeRefreshModel);
    ....
    }

    public string Location => userPrefernces.SelectedLocation.DisplayString;
    public int CurrentTemp => model.CurrentTemp;
    public int TodaysHigh => model.HighTemp;
    public int UVlevel => model.UV;

    public string TemperatureUnits => userPrefernces .SelectedUnits.DisplayString;

   
}

//Design time class just has raw values and parameterless constructor
public class WeatherDataDesignViewModel : IWeatherDataViewModel
{
	public string Location => "Minneapolis";
	public int CurrentTemp => 85;
	public int TodaysHigh => 87;
	public int UVlevel => 7;
	public string TemperatureUnits => "F";
}

In the above example, the implementation has a command, which I could have added to the interface, since we will likely bind to it, but as the button to refresh the data isn’t likely to impact the view of the screen at design time I didn’t. However, I might do if I was using the CanExecute delegate and some particular enabled/disabled styling on the button to make sure that when CanExecute is false, the button looks ok.

Getting it into the XAML

Having created the designtime view model, using it in your view is easy.

<UserControl
  x:Class="MyWeatherApp.CurrentWeatherControl"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  ...
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"	
  xmlns:local="clr-namespace:MyWeatherApp"
  ...
  mc:Ignorable="d">	
  <Grid  d:DataContext="{d:DesignInstance local:WeatherDataDesignerViewModel, IsDesignTimeCreatable=True}">
....
</UserControl

The d:DesignInstance attribute tells XAML that the data context will be of a given type. This provides design time intellisese when creating bindings and the properties in this class will show in the list of choices. The IsDesignTimeCreateable attribute tells the designer in Visual studio that it’s OK to create an instance of this class at design time, and that means that it wil create an instance and use those properties that you assign to it. In this way, you can see what your app might look like with real data in at design time.

Tip: If you exclude IsDesignTimeCreatable, you can’t use it for design time data, but you do still get design time intellisense, even for view models that don’t have a parameterless constructor.

Considerations for UWP and x:Bind

If you use DataContext and traditional binding in UWP, the above will work exactly as I have already described it. But what about compiled bindings and x:Bind?

It looks like the current recommendation may be to use traditional bindings via DataContext until you are happy with your design, than swap to x:Bind for improved performance.

See this response on the GitHub for a sample application: Microsoft PhotoSharing App Sample issues. Hopefully there will be a better solution in future.

Hopefully you liked this look at one way of working with data at deign time. Which way do you like to see design time data be generated? Do you never use the designer and purely type you XAML? Let me know in the comments below.

Top podcasts for developers

I really enjoy podcasts and listen to them most days on my commute to and from work, sometimes at work, sometimes when bathing my son and getting him ready for bed, sometimes when mowing the lawn or walking the dogs.  It’s a great way to keep up, or at least get a high level overview of what’s going on in tech.

I think this is where UWP also can be seen living up to the hype. I’ve used Cast and more recently Grover Pro and both apps are well designed and consistent on phone and PC. When I use Grover Pro, I miss Cast’s organizational options, dividing podcasts into categories. Sadly I was seeing a few bugs with Cast, at least with the insider preview – it seems the developer was trying to clean this up and I’ll give it another try soon. Anyway, the key thing both do is allow you to listen to one podcast on your phone and pick up from where you left off on the PC, or vice versa and if you are looking for a podcast app that rises above the pack, I can recommend both of them.

These are some of the podcasts I have found the most useful and interesting for me as a .Net/C#/Windows developer.

The MS Dev Show

This isa weelk podcast from a couple of Microsoft employees and benefits from getting great access to people to come and tak about new projects and technologies that Microsoft has released. The MS dev show covers a very broad range of developer topics and products that are relevant to the .Net, web and Windows developer community and follows the news followed by guest format.

.Net Rocks

An oldie but a good one. With over 1300 episodes behind them, Carl Franklin and Rich Campbell are good at what they do, at digging in on a technology and going about as deep as you can in 30 mins or so discussion with their guests. Similar to the MS Dev Show in format (news followed by guest) in most shows, they have also been doing guestless “geekout” shows on other topics such as reusable space travel, GMO’s, and of course, Whiskey. They release several episodes a week.

Coding Blocks

Ran by 3 full time software developers who do corporate web applications on the ASP.Net stack, this show focusses more on principles and patterns around software development e.g Design patterns, unit testing, how to be a good programmer. The show is monthly, but when it comes out, it’s usually about 2 hours long which allows them to go in depth and have a good discussion around the topic.

Developer on Fire

An inspiring podcast created by Dave Rael. He interviews people from the software development world, usually published or on the conference circuit, and asks them a standard series of questions. The stories told in these interviews are often inspireing though and encourage me to keep learning, and it doesn’t seem to matter if they are F# or ruby or .NET folks being interviewed, the language or domain is rarely that important, which is nice. They also come out several times a week so although it’s only just turned one year old, there’s already a good back catalog including (Uncle Bob) Robert Martin, Scott Hanselman, Rob Eisenberg, John Sonmez and the aforementioned Carl Franklin.

A few others worth a listen from time to time that are also aimed at developers are Hanselminutes, Software Engineering radio, and East, sleep code. Non developer focused ones I’d recommend are Windows Weekly, 361 Degrees and All About Windows Phone.

Unfortunately, the podcast most directly relevant to me is no longer – the Windows Dev Show, hosted by brothers Ryan and Travis Lowdermilk.  That has some interesting stuff in it’s history that’s still available through podcast apps, including several episodes containing good encouragement and advice for developers who sent in their own apps for them to take a look at.  The last episode was June 2015 when they talked about Bing Solutions.

Do you have recommendations for podcast that developers should seek out? Let me know in the comments.

Learning to do Async / Await – 4 mistakes I initially made

As part of work on updates for my Shoppers Calculator app, I stumbled into bugs caused by my not using Async await properly and not really understanding how it worked.

Some errors I was making:

  • Believed it was spawning new threads
  • Returned void from methods when there would have been no return when doing synchronous programming
  • Used goofy code patterns to make async work, thinking that was what you had to do.
  • Decided it was OK to use async methods without awaiting and call them synchronously from other methods (you get a warning but no error).

Shoppers Calculator 1.8 introduced a shopping history.  Previously there was a single shopping trip or single cart. If you wanted a new trip/empty cart you opened the app bar and clicked “clear everything”. Now we have a history, and to do this you click New Shopping Trip on the main screen.  your previous one is saved and you can view it later. So now, rather than saving a single collection of items as a trip, I am saving a collection of collections of items.

Not really a problem, and my app works just fine, but I could see quickly that I needed a follow up update that addresses the issue of performance by making my save method asynchronous.  Not likely to be a problem as folks only go shopping a few times most weeks, and even an avid shopper won’t have as much data as to cause a big issue yet.

So starting with the save method, I started adding async into method signatures and await into calls, using asynchronous overloads when I could and not worrying too much about it when I couldn’t. I did this all the way up the call stack to the UI though all the various ways save would be called, and moved on to other perceived poorly performing scenarios.

In the end, a large number of methods got the async keyword.  It didn’t work and I instantly had problems loading and saving data, despite my reading of the code to be fine. So I took to the web, and to channel 9 videos, and now it works. My app is performant and smooth.

So what have I learned?

  • The Async method doesn’t spin up a new thread.

Actually this is pretty key to understanding how it all works and why the other things can cause a problem.  It’s more of a deferred action, or a do-it when you get to it type thing.  Basically, what it’s really saying is as this method executes, there will be a moment that takes time and rather than wait for that next line to run, you should do something else, and return to it once that response has come in.

public async void ButtonClicked(object sender, EverntArgs e)
{
    Spinner.Visibility=Visibility.Visible;   
    await StartProcessing()
    Spinner.Visibility = Visibility.Collapsed;
}

This code would probably be suitable in either asynchronous or synchronous code. The reason is that the await keyword doesn’t mean that any new thread is being spun up – things still happen in order. If await was causing a new thread, the equivalent of calling Task.Run(()=>StartProcessing), the spinner would show for approximately 0 seconds. Using await still means the last line won’t execute until the one before it done, but also that while we are waiting, control is released back to the caller, in this case unblocking the UI so the user can interact with it. It doesn’t mean the processing will finish any faster, but it does mean the user can do other things while we await the completion of processing.

  • Don’t use async void (except for handlers)

The compiler is expecting async methods to return a task and hooks into the task as a callback. By not returning a task, there is no callback created. It’s fire and forget and the caller has no idea when the awaited method has returned.

Instead, use Task as the return type. This gives the caller something to hook into and check the status of.

Are there cases when async void is ok? Yes, event handlers, such as the button example above would be ok.

  • You should (mostly) just code like you would for a synchronous method

Due to my belief that it was spinning separate threads, I wrote code in a way that tried to maximize thread efficiency.  A big waste of time really, as all it did was make methods less readable. In most cases, just write the way you normally would. There is however, one gotcha. You have to remember that everything after the method you are awaiting, may not run immediately as control will be returned back up the stack. If there are things that need to happen immediately, call them first as long as they don’t depend on the result of the awaited method. You would probably just do this anyway if you were writing synchronous code, but perhaps in synchronous code you would do hold off on some actions while the thread is blocked due to processing something or getting data. These should be removed, or moved to occur before the awaited method if possible.

For example:

public void Add(double value)
{
   model.Add(value)
   model.Save();
   OnPropertyChanged("Total");
}

Could become:

public async Task Add(double value)
{
   model.Add(value)
   OnPropertyChanged("Total");
   await model.Save();
}

In this change, we are making sure the UI is updated quickly, before the potentially slow process of saving the model state.

Calling synchronous methods as if they were async doesn’t work

I mentioned at the start that I began my async journey with the save method which I perceived as an IO method and a natural fit for async.await. However, the place I was saving this single collection of collections didn’t have an async method to it. So I pretended it did and wrapped it in an async method and called it from an async method with an await etc, up the chain.

Ultimately, we are waiting for some task that takes some time to run. Sticking async Task in the method signature by itself doesn’t do too much. This is basically what I was doing at one point, using Windows Phone 8 Silverlight synchronous storage methods assuming that because it’s a storage method, some sort of real IO was going on and therefore I should do that.

I don’t remember now which bugs if any we caused by that specifically as I was also using async void and all the other failings mentioned above and they were more responsible for issues with my app. However, it’s fair to say that if you are not ultimately using framework methods that are async, but hitting on a long running process, something along the way should create a new task that executes the code and return that task from the method, or use something like TaskCompletionSource (see links below).  Being able to trust that async methods are really async is important as we have seen above – it can affect the expectations you have for them and the way you use them. It affects scalability and is generally a bad idea, as this post explains.

Clearing up these errors have helped me create a more performant application and fixed some nagging errors. It was frustrating going through the process of learning this while trying to launch a product update but it was valuable lesson and something I wouldn’t have learned without having a side project (I don’t get to use this stuff at work where we’re having to support Windows XP.

A couple of resources that really helped me with this:

Video: Six Essential Tips For Async on Channel9 by Lucian Wischik
Written: Asynchronous Programming with Async and Await on MSDN
Written: Should I expose asynchronous wrappers for synchronous methods? Steven Toub on MSDN
Written: TaskCompletionSource – Trying to understand threadless async work – Stack overflow (This links to several useful posts on the subject).

My favorite features of C# 6

Earlier this year, Microsoft released C#6.0 and that bought a long a few really nice features that help streamline code. Some features are sadly only make sense with newer versions of the .Net Framework and my day job is stuck on .Net 4.0, but others are there for whatever framework you need.

I haven’t been able to jump on C#6 right away ue to build servers needing to be updated at work, and I suppose i have to admit i could have at home, but didn’t. Since  I have done a few months back, there one some features I have I started using as soon as I have been able to and think they really help clean up boilerplate or generally make code better.
1. Auto-Property Initializers

public class MyObject
{
public MyObject(string name)
{
   Name=name;
}

public string Name {get;}
public DateTime TodaysDate {get; } = DateTime.Now;
}

There are two ways of initializing these properties but they both amount to the same thing – at the point of instantiation. They can be assigned a value inline or in the constructor, but nowhere else.

2. Expression body methods and properties

public class MyViewModel
{
   //constructor and stuff
   ...
   //property
   public bool IsEnabled => _MyModel.IsEnabled;

   //property
   public string SelectedName => _MyModel.Names.FirstOrDefault(x => x.IsSelected);

   //method
   private void OnSelectionChanged() => SelectionChanged?.Invoke(this, new EventArgs());

   public event EventHandler SelectionChanged;
}

So this is really good for quick and simple methods and properties and removes a lot of boiler plate. Note that the properties are ‘get’ only.

3. Null-Conditional operator (Elvis operator)

This was previewed above, but this ha been really useful in some places, a particular example is the null check around event invoking. One place I thought I’d get more use out of it is in if statements, but actually it’s more awkward there as it makes the statement return bool?  (i.e nullable bool)rather than bool. One way around that is to use a the ?? (null-coalescing) operator to give null a value.

public class MyViewModel
{
   //some stuff
   ...
   public event EventHandler SelectionChanged;

   private void OnSelectionChanged() => SelectionChanged?.Invoke(this, new EventArg());

   //if there is a selection, return it's length, else -1.
   public int GetSelectedNameLength()
   {
      return _MyModel.Names.FirstOrDefault(x => x.IsSelected)?.Length ?? -1
   }

   public int ChanceItsTheSamePerson(Person a)
   {
      if (a?.SelectedName == GetSelectedName ?? false)
      {
         return 100;
      }
      else
      {
         //inspect some other properties and return a value
      }
   }
}

There are far more of course, and I would like to have made more use of string interpolation which puts variable names directly in a string, replacing string.Format. The downside is that the projects I work on are culture sensitive and require a new .Net 4.6 keyword to take advantage of culture when doing this. It does give me a chance to show static class import though.

using static System.FormattableString;

public PrintFruit()
{
   //This bit works for all .Net versions
   var fruit = "apple";
   System.WriteLine($"My favorite fruit is {fruit }");

   //By default the culture is current culture. If we want to use Invariant 
   //culture (or any other culture setting) we would need the .Net 4.6 
   //FormattableString static class, imported above, and it's Invariant method.
   var appleCost=2.99;
   var coststring = Invariant($"IN America, they cost ${applecost}");
   System.WriteLine(cost);
}

So there we are, a brief walk through some of the C# 6 feature I have found useful so far. To find out more about C#6 and it’s new features:

Read: C# : The New and Improved C# 6.0 at MSDN Magazine
Watch: What’s new in C# 6.0 by Mads Torgersen on Channel9

 

 

The Command Pattern and MVVM

Update 3/10/2017: Added Code Sample, plus minor fixes.
Update 9/22/2016: Note that in these code snippets, I’m inheriting ViewModelBaseClass which is where methods like SetProperty reside, and where INotifyPropertyChanged is implemented. If you are using a framework like MVVMLite or Prism, you will probably be using their base class. I’ll be covering what goes in a MVVM base class in a future post

This post was prompted by listening the excellent Coding Blocks podcast, that somewhat failed in my opinion when describing the Command Pattern.  The problem is that these 3 guys are all web guys, and their treatment of some patterns that are primarily used by desktop/client apps shows this up. The most recent podcast reflects this in the discussion of the Command Pattern (where they seem to struggle to find implementation examples), and contrasts strongly with their discussion of the Repository Pattern.

This is the bit where I now fall flat on my face trying to do a better job, but here we go.  If you are for some reason put off MVVM, WPF, UWP or any other sort of app with a XAML front end because you might have to encounter the command pattern, don’t be. While I might agree with them that a dictionary definitions might sound confusing, implementation of this pattern is not bad at all. You may find it’s already been done for you if you choose an MVVM framework such as Prism or MVVMLite.

So what’s involved?

  • ICommand implementation
  • Delegates for Execute and CanExecute (the methods that ICommand implements)
  • Usually, Some properties to bind UI controls to.

I’ve seen books showing a full complete implementation of ICommand for every command you wish to do, but in practice, there is a better way. The problem with creating new command classes for each case is that for each button or action you might want to do you may find you need to create a new command, so if you have  a simple app with a few buttons and dialogs you will quickly finds you have a whole host of ICommand implementations.  The better way is to have one generic implementation, and pass into the constructor delegates that know about the state of the object it’s being called from. Usually this object will be your view model and may contain delegates for several instances of the ICommand implementation.

So here’s some code:

using System;
using System.Windows.Input;

namespace MVVMBase
{
  public class DelegateCommand : ICommand
  {
    //These delegates store methods to be called that contains the body of the Execute and CanExecue methods
    //for each particular instance of DelegateCommand.
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _Execute;

    //Two Constructors, for convenience and clean code - often you won't need CanExecute
    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
    {
      _canExecute = canExecute;
      _Execute = execute;
    }

    public DelegateCommand(Action<object> execute)
      : this (execute, null)
    { }

    //CanExecute and Execute come from ICommand
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
      return _canExecute == null ? true : _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
      if (!CanExecute(parameter))
        return;

      _Execute(parameter);
    }

    /// <summary>
    /// Not a part of ICommand, but commonly added so you can trigger a manual refresh on the result of CanExecute.
    /// </summary>
    public void RaiseCanExecuteChanged()
    {
      CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
  }
}

I’ve called this class DelegateCommand, though RelayCommand is also a common name for it. So now that you have this implementation of ICommand, how do we hook it up to do something. Here’s a way to do that:

public class MainScreenViewModel :  ViewModelBaseClass
  {
  public MainScreenViewModel()
  {
    //Initialize the command
    ShowMessageCommand = new DelegateCommand(ExecuteShowMessage, CanExcuteShowMessage);
  }

  //The execute and can execute methods.
  private bool CanExcuteShowMessage(object obj)
  {
    return !string.IsNullOrWhiteSpace(MyName);
  }

  private void ExecuteShowMessage(object obj)
  {
    MessageReady = true;
  }

  //The command property
  private DelegateCommand _ShowMessageCommand;
  public DelegateCommand ShowMessageCommand
  {
    get { return _ShowMessageCommand; }
    set { SetProperty(ref _ShowMessageCommand, value); }
  }

  //A couple of bindable properties. Note the RaiseCanExecuteChanged in the  first of them.
  private string _myName;
  public string MyName
  {
	get { return _myName; }
	set
	{
		SetProperty(ref _myName, value);
		ShowMessageCommand.RaiseCanExecuteChanged();
	}
  }
  private bool _messageReady;
  public bool MessageReady
  {
    get { return _messageReady; }
    set { SetProperty(ref _messageReady, value); }
  }
}

And last bit, to bind this to a button. In this case, I’m using a UWP app and compiled bindings, but the XAML is virtually the same in WPF, Windows Runtime or Silverlight XAML.

<StackPanel Margin="24,0">
      <TextBlock FontSize="24" Margin="0,24">My Simple test app</TextBlock>
      <TextBlock>Please enter your name</TextBlock>
      <TextBox Text="{Binding MyName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
      <Button Content="Press to see your message!" Command="{x:Bind ViewModel.ShowMessageCommand}" Margin="0,12" />
      <TextBlock Visibility="{x:Bind ViewModel.MessageReady, Converter={StaticResource boolToVisibility}, Mode=OneWay}" >
        <Run Text="Hello" />
        <Run Text="{x:Bind ViewModel.MyName}" />
      </TextBlock>
    </StackPanel>

Note that when we do this, the CanExecute method of the command is in control of enabling and disabling the button. so there is no need for a separate IsEnabled property to bind to.

OK, so this is a slightly contrived example. The TextBlock allows you to enter some text and when text has been entered, it allows you to click a button, which then shows a second message. It might be more reasonable if the execute took you to a second screen, or showed the message in the message box. Still, hopefully it illustrates the point and concept of commands.

It’s worth noting that there are several built in commands that you can bind to. They are found in System.Windows.Input.ApplicationCommands and can be hooked up like this:

<StackPanel>
  <Menu>
    <MenuItem Command="ApplicationCommands.Paste" />
  </Menu>
  <TextBox />
</StackPanel>

 From the MSDN Commanding Overview

As I said earlier, you might get a leg up by using a framework with built in implementations for you, such as Prism, MVVMLite, Template 10 or others. and some of these may have additional implementations, such as DelgateCommand<T> in Templat10.

If this helped, or I’m botching this up, please let me know. Also, do listen to Coding Blocks, even though I think they missed something by neglecting to mention XAML at all in their discussion of the Command Pattern, I heartily recommend their podcast as an entertaining and in-depth look at software development.

Code Sample: MVVMBase.Zip

Why create a developer blog about the Windows ecosystem right now?

So here I am launching my blog.  It’s called OneWindowsDev.com and will focus on topics relating to developing software for Windows, be it UWP, Win32, Windows Phone / Windows 10 Mobile, or websites. But hang on, why do that, aren’t all those things either in decline or only recently launched and unproven? Yes, that’s probably true. So why am I writing a blog about it? Here’s 3 reasons.

It’s my area of knowledge

I am a software developer. I was educated primarily in Java, but since starting work in the professional world, it has been almost all done in the .Net Framework, using C# or VB, Windows Forms or WPF and using Visual Studio. In addition to my professional work, I have done some bits for myself, initially using C++ and QtQuick back when I owned a Nokia 900 and Nokia N9, but over time that too came to be in C#, though using the Windows Phone 7 or 8 SDK. You can read more of that at my old blog here. So in short, it’s something that I car about, and will be encountering frequently.

I’m still learning

One of the reasons for starting this is to help cement the things I learn for myself, and to share those insights with others. With UWP and  .Net Core, plus the rise of Xamarin and it’s incorporation to Visual Studio, there is plenty to learn about for the seasoned pro.  Throw in things like .Net Native, Unit testing, SOLID, deign patterns and good design (things my employer is both very good and very bad with) and that’s even more. Plus, it  at be clear by now that I’m not a web developer (this site is on WordPress rather than me writing my own and hosting in Azure, or even using the .Net Blogging engine), but the web world is changing rapidly, as is what it means to be an ASP.Net developer. Regardless, As I learn, I will be writing about it here.

I care about the Windows ecosystem

Yes, this is a part of it. It does matter to me if these things are successful. For better or worse, I am a Windows 10 insider both on phone and PC.  The laptop I’m using to write this is dual boot with Windows 10 insider fast ring in one partition and Windows 10 production in another. I have 4 phones, 3 Windows and one Android. I haven’t used the Android device in over a year, and of the 3 Windows Phone devices, one is running Windows insider fast ring, and the others are running release preview ring. My PC at home runs Windows 10 as well, and I own a Microsoft Band. At this point you are probably right to call me a fanboy or schill or whatever. I am realistic about the prospects for Windows 10 Mobile (I think) and fully intend to write cross platform code (and update the Android phone, maybe even use it). I like what Microsoft are trying to do and would like them to succeed in terms of universal apps and all that. I like XAML and think WPF and UWP are excellent as a result of it. I like the tooling Visual Studio provides.

Despite all this, the tech world is writing off Windows 10 Mobile and by extension UWP as dead. Should I just learn Java instead? Maybe.  There’s a fair argument there, though I think it’s less dead than some would make out, but perhaps more dead than others. I figure either in a year I will still be writing this blog with this name, or it will have been renamed to OneDev or something and be full of Java post about how I’m creating apps for Android and Chrome.

My last blog faded and I hope this one will be different. I can’t promise that it will, but my goal is to post at least once a week, and to not get distracted by tech news (one of my past failings) unless it’s really relevant to developers. In most cases, tech news is well covered by sites like Engadget, the Verge, the Register, or Windows specific sites like Thurrott.com, WindowsCentral and WinBeta. I will however, allow myself the occasional opinion piece as I’m sure you can appreciate, being a developer in the Windows space right now, there are certainly times when a good rant is justified, as well as recognition of the things that some people are doing well.

What I will post are posts that feature code snippets, posts that talk about design, testing and implementation of software and my own commentary on the state of the ecosystem, some talk about my own apps and other peoples, posts about managing, marketing, monetizing apps.  This should be enough variety for me to find something to write about, without resorting to posts about the Bank of America app releasing, or T-Mobile’s new uncarrier plan or some governments latest plan to spy on us all even more.

Scott Hanselman talked today in the DotNetConf day 3 session about how bloggers are an important part of the .Net Community. So here goes, my re-entry to the .Net community as a content creator. Blogger, and developer.