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.