Alternatives for Groove

Last week Microsoft announced that Groove Music streaming service, and the ability to buy music from the store in Windows 10 will end on December 31st. Users will be able to Download their content or port to Spotty until January 31st, at which point all the Groove streaming service features and store features for music will be killed. The groove app will still be there for playing your local music, and music you stored on OneDrive , but unfortunately, the extra OneDrive storage given for being a groove subscriber is also going away.

Microsoft is offering porting to Spotify and may have some as yet unspecified deeper integration to come. For now, that’s an offer inn the groove app to port your content to Spotify and a 60 day trial offer from Spotify, for anyone who’s never tried Spotify before. I imagine, given how long Spotify has been around, that this is a very small pool of users. So should you go to Spotify, or someone else.  This is my attempt at comparing the main options.

I haven’t used the services I’m listing much – I’ve been a groove user (and Xbox music user before that) but I have used Pandora and Spotify in the past. However, I’d need to try these to give a more qualified comparison. So this is a high level stat-for-stat look.

Pricing

[table id=1 /]

Features

[table id=2 /]

Apps

[table id=3 /]

Stats

[table id=4 /]

My View

My initial view is that Microsoft is partnering with the wrong service in Spotify, just due to the gap in songs. There will be a lot of users who find that their music isn’t available, and indeed, that was a reason why I use Groove in preference to Spotify.  I can totally understand Microsoft not wanting to partner with Amazon, Google or Apple on music and Spotify is the obvious choice, but perhaps Deezer and Tidal with larger catalogs (and in Deezer’s case, global availability and UWP apps) might have been better.

If you are a Windows 10 Mobile user or Xbox user and want integration in those devices, you would certainly also want to check out Deezer,  Tidal and Pandora, which all have apps for Windows 10 Mobile. The Deezer app in particular is well rated, as is the unofficial Tidal app. Spotify does of course have an app on Windows 10 Mobile, but that app isn’t well loved and feels dated.

If this doesn’t matter to you Amazon and Google and Apple do have some advantages over the pure streaming services – playing local music (amazon and Apple) and cloud storage. Especially if you are already a Amazon prime member, the cheaper price for individual plans on amazon would be appealing, and $25/year isn’t a ton of money for the cloud storage. If you don’t care about local playback, Google includes offline storage for free. Apple has both of these and is putting iTunes in the Windows store so yeah, a good option.

I’m waffling now – I’m sure these are all good options. I’ll be checking out Deezer, Spotify and Amazon music.

Basic MVVM Base class / INotifyPropertyChanged implementation

A while back, (OK, a long while back), I promised an article on how to create a MMVM view model base class.  This class will implement the INotifyPropertyChanged interface, and add some common sugar on top of it to make it really easy to use.

In all project types that use XAML, you can bind items in the UI to properties in the view model. The purpose of INotifyPropertyChanged is to notify those binding of when the underlying property changes so the updated values can be pulled in. It has one item, an event called PropertyChanged. However, just adding an event is not super helpful. So here’s an example of a base class that adds a bit more.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace MVVMBase
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        //The interface only includes this evennt
        public event PropertyChangedEventHandler PropertyChanged;

        //Common implementations of SetProperty
        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName]string name = null)
        {
            bool propertyChanged = false;

            //If we have a different value, do stuff
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                OnPropertyChanged(name);
                propertyChanged = true;
            }

            return propertyChanged;
        }

        //The C#6 version of the common implementation
        protected void OnPropertyChanged([CallerMemberName]string name = null)
        {
           PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

So what does it do:

  1. Implement INotifyPropertyChanged – yup, the event is there, job done.
  2. Creates a handy SetProperty method that does the following:
    1. Takes the property name, a reference to it’s backing field and the new value
    2. Checks if the new value is actually different
    3. If so it updates the backing field and invokes the property changed event
    4. Returns a value to indicate if the property actually changed
  3. Creates an OnPropertyChanged method (this is often also called RaisePropertyChanged) that can be used to force the PropertyChanged event to fire for a given property.

Now that I’ve got this, using it is pretty simple. First, make you view models inherit from this. Then write your properties this way:

private bool _messageReady;
public bool MessageReady
{
    get { return _messageReady; }
    set { SetProperty(ref _messageReady, value); }
}

Note that although SetProperty is generic, you don’t have to pass in a Type, and although it takes 3 propereties, and the third is the name of the property is being changed, you don’t have to as the default is set to the CallerMemberName attribute. Of course, you can do both and if you needed to do some thing where you set the property indirectly as part of some other method, you could then call SetProperty<bool>(ref _messageReady, true, “MessageReady”);

Some Properties are getter only and depend on the values of other properties and fields in the class. This is a place where that OnPropertyChanged method is useful.

private bool _messageReady; 
public bool MessageReady 
{ 
    get { return _messageReady; } 
    set 
    { 
        if (SetProperty(ref _messageReady, value))
        {
            OnPropertyChanged(() => BackgroundColor);
        }
    } 
}

public Color BackgroundColor
{
    get { return MessageReady ? Colors.Green : Colors.White.
}

In this example, we have a property called BackgroundColor that is normally white, but becomes green when a message is ready. But as it’s just a getter, how does our UI know when it’s value changes? We call OnPropertyChanged for BackgroundColor when the MessageReady property is updated.

So that’s a brief tour of a view model base class.  If you look around, you will find others who may have more, or that have different implementations of these methods. For me, this is the basics of what you need – an implementation of INotifyPropertyChanged that you only need to make once, and that makes updating bound properties easy to do.

CodeSample: MVVMBase.zip

Covariance and Contravariance

OK, so this is my attempt to help me to commit something to memory. I am not an expert in this area by any means.

Variance which is, loosely, the subtyping relationship for objects and substitutions that may be permitted for those types. Generally, more derived types can be assigned to objects of less derived types e.g Cat objects can be used in places where we call for an Animal. This particular type of variance is called co-variance, but there is also Contravariance and Invariance in C# types.

Generally speaking….

Covariance allows you to return a more derived class from a method. True contravariance would allow you to change the method signature so you would have in the Animal class, a method Animal GetAnimal() and in the Cat class, it’s override as Cat GetAnimal().

Contravariance would allow a less derived class to be used in method arguments so if the Animal class had a method called BuyAnimal(Animal animal), the Cat class could override this with BuyAnimal(Object animal).

Neither of these are supported in C#, though Java & C++ have some support.  So what do we need to know about convariance and contravariance in C# or .Net?

Covariance

Some sources refer to it as preserving the standard variance or similar words to that. Basically, it means that if I override a method, the return can be the same as the parent, or a descendant type. This sounds a lot like following the standard inheritance pattern, and while methods in a subclass can’t declare a more derived return type when overriding base class methods, they can of course return a more derived type. Maybe calling this covariance is generous, though it meets some of the definition, as it’s really just polymorphism that is a part of object oriented languages.

More explicit examples of Covariance can be found in generic types, such as IEnumerable<T> and in usage, it looks pretty much the same. The key here is that a generic method can return either T or a subclass of T and can be declared to return different T’s. This works because IEnumerable uses the ‘out’ variance modifier.

//Covariance - all bout how the return type can be a child of a parent
Animal spot = new Dog(Gender.Male);
Animal[] mammals = new Mammal[10];
IEnumerable<Animal> animals = new List<Dog>();

You can also see covariance in IEnumerator<T>, IQueryable<T> and IGrouping<TKey, TElement>.

Contravariance

Contravariance is reversing this – contrary to the normal variance. In C# Contravariance is limited to delegates and interfaces It means that I am allowed to change the input args to a base class of whatever the args the base class takes. In the case of delegates, I can assign a more general method to more specific delegate.

static void Main(string[] args)
{
  //Contravariance lets a method take parameters that are from a superclass of the type expected by a
  //delegate.
        //Here the delegate takes a Dog
  Dog dog = new Dog(Gender.Female);
  Action<Dog> barkingDog = Bark;
  barkingDog(dog);
}		

//Method here takes a Animal
public static void Bark(Animal animal)
{
  Console.WriteLine($"Woof, im a {nameof(animal)}");
}

You may look at the code above and say, what’s the point of that? While it’s true that it doesn’t buy us much in this case, consider scenarios where those delegates are representing methods with a less direct relationship. In this case it starts to become more useful. For example, if the Dog class has a property called Action<Dog TalkDelegate. You can pass the Bark(Animal animal) method to that property, even though the method signature doesn’t match what the property requires. This is because as Dog is a Subclass of animal, a method working with an animal will also be able to work with a Dog.

You also see Contravaraince in IComparer<T>, IEqualityComparer<T> and ICompatible<T>

Invariant classes

Some types and interfaces are invariant. For example, while IEnumberable<T> is covariant. ILIst<T> is invariant. That means that the code below will not compile.

//Invariance
IList<Animal> animals = new List<Dog>();

Variance Modifiers

There are two variance modifiers that can be applied: ‘in’ and ‘out’. Only delegates and Interfaces can take Variance modifiers. The reason IEnumerable supports Covariance is that it’s declared as IEnumerable<out T>, and delegates by default are constructed using ‘in’, such as Action<in T>. These keywords can be seen a linking the variance of the output or the inputs.

  • out T – Covariance lets a method return a value from a subclass of the result expected by a delegate
  • in T – Contravariance lets a method take parameters that are from a superclass of the type expected by a delegate.

Variance is supported by reference types only and just because a class implements one of the interfaces listed here, it doesn’t mean those types support it. For example, List<T> implements IEnumerable but is invariant.

Hope you found this helpful.

Sources/References:

 

Why Windows Developor Day & Creators Update gives me a wee bit of hope

It’s been a while since I have posted anything. Busy with work, family life, snow removal and the like. However, the Windows Developer Day event has spurred me to life a little and I’m feeling, for the time being anyway, positive about UWP and Windows 10. Here’s a few reasons why:

Adobe XD (and others)

It’s not Adobe XD per se that is exciting, but more that Adobe is creating a full featured, UWP application. The perception that there are no full feature apps or that the store is full of toy apps has some truth to it thought there are exceptions. In part, this is fueled by versions of mature apps being added that are less feature rich. Of course, it takes time to develop an application and an often cited example is Office, which is a little harsh considering the Windows 32 codebase has had about 30 years of development and the UWP / Mobile version about 5. That said, users don’t care if it took 5 minutes of 50 years, they care if it has the features they need and doesn’t crash. As a user of office mobile, I can say I rarely see it crash, but just the other day I submitted feedback for a feature I needed to use but couldn’t find.

So a powerful, full featured apps from a publisher of the stature of Adobe is great news, as is the news that they will be converting various components of other apps to have UWP support. Also good news around apps using Centennial (Slack, Kodi, Evernote, Audible, Deezer, and more) and that Kodi is also going to do a full UWP, and come to the Xbox in future.

Open Features and bugs lists

Microsoft is increasingly developing in the open and this is demonstrated with the launch of the Windows Developer Platform website. Being able to see what might be coming, and what they are doing about problems and issues with the SDK is a nice step and will hopefully encourage folks when it comes to the direction and speed of development of the platform. The Creators Update changes are good, but what really excites me is the list of features under development or under consideration. Several of those under consideration have a linked UserVoice request, so if you see something you like the sound of, go and vote on it – it might sway  if and when that features is developed.

Store improvements

There are several improvements to the store that I am looking forward to, some because they might help bring in more developers (new pricing models for example), and others because I have felt the pain (doing minor updates for Shoppers Calculator over 6 languages took ages, I can’t think what it would take for large applications translated 20 or 40 or more languages.

UWP improvement

The improvements to the UWP platform are good. Nothing earth shattering, I think the biggest deal is probably around live tiles, but the shape recognition for windows ink, and progress bar in notifications are also nice. You might have something else that jumps out when you see the list, but certainly, it gives me a couple of ideas for apps I might be more willing to do now. As a bonus, the Telerik UI controls for UWP are now open source.

So no, this isn’t going to save windows 10 mobile, or flood the store for windows 10 desktop with new apps instantly. But it helps, the platform feels interesting, powerful and while we’ll have to wait and see, the list above gives me hope for at least UWP as a platform being a going concern for the foreseeable future, and a bit of excitement to get back in to writing some code.

Watch: Windows Developer Day Video
Read: Windows Developer Platform
Download: Windows 10 Preview SDK

Implementing IDisposable

IDisposable is a deceptively simple interface, but with some rules around how and when to use it you really ought to follow.  Some recent work I did around it showed the extent to which myself and others have misunderstood how to properly dispose of items and what needs disposing. So this is my attempt at putting some of the good practices to “paper” so if nothing else, I’ll remember them in future and hopefully a few others can find this helpful.

So when should you implement IDisposable? When a class either has unmanaged resources, or owns managed types which are IDisposable.

Why should you implement IDisposable? It can also be used to ensure cleanup of managed resources that could cause a leak – for example, to enforce unsubscribing from an event in the case of there not being a natural place to otherwise do so (thought it’s probably better to find a good place in the code execution to unsubscribe than to make the object IDisposable for this only).

This how-to attempts to suggest a good way to implement IDisposable and provide some context around common mistakes. There are a couple of resources on IDisposable that may be useful for a more general picture:

Note that these don’t reflect how we have implemented IDisposable in some cases and CA1063 should be suppressed in current Gen. I will add more on this below.

Simplified Definitions

  • Managed Resources – .Net CLR types and types created using .NET, except for types that contain unmanaged resources
  • Unmanaged Resources – Pointers, handles, HWind’s and other COM types.
  • Garbage collection – The process of cleaning up of managed resources that are no longer in use. Hereafter known as GC.
  • Finalization – A process, related to Garbage collection, of cleaning up unmanaged resources. This runs after Dispose, in garbage collection, or on the shutdown of the application domain. (https://msdn.microsoft.com/en-us/library/system.object.finalize%28v=vs.110%29.aspx)

The common Implementation

The common implementation involves 3 methods and looks something like this:

IDisposable common implementation
public class SomeClass : IDisposable
{
    // some fields that require cleanup
    private bool disposed = false; // to detect redundant calls
 
    // Constructor
    public SomeClass()
    {
        // allocate resources
    }
    
    // Finalizer
    ~SomeClass()
    {
        Dispose(false);
    }
    
    // Dispose method and only public part of IDisposable
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
 
    // Dispose method that does the actual work. Should be overridden when needed in sub-classes.
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // dispose-only, i.e. non-finalizable logic
                // Managed resources
            }
            // shared cleanup logic that can run from a finalizer
            // Unmanaged or native resources
 
            // Set the disposed flag
            disposed = true;
        }
    }
}

So what does each part do?

Disposed flag:

  • A local private bool used to reduce time spent and errors that may occur by running dispose logic on an object that has already been disposed.

Finalizer (Only needed if you have unmanaged resources):

  • Overriding the finalizer (there in one in System.Object) tells the CLR that there are unmanaged resources to clean up relating to a given object
  • Calls Dispose(false) to execute the finalizer logic
  • A sort application level equivalent to the finally block of try/catch.finally – This code is executed last before an object is destroyed. This means that CLR types related to the class may have been destroyed prior to the finalizer running and so it cannot access those types.

Dispose()

  • The only method in IDisposable
  • Calls Dispose(true) to execute disposal of managed resources
  • Runs during garbage collection, or from a direct call to Dispose, or from the close of a using block.
  • If there is a Finalizer, calls GC.SupressFinalizer(this) to tell the GC that the finalizer logic has been executed and the object can be safely destroyed. This will mean the object can be destroyed 1 GC cycle earlier

Dispose(bool disposing)

  • Contains the logic for disposing of an object
  • Should contain an (if disposing) block for disposal of managed resources
  • Code outside this block should be accessible by a finalizer. This means no calls to other types native to your project should be here. Dispose of unmanaged resources here.
  • Set the disposed flag to true. The dispose method may be called several times on an object, and this is an easy performance boost.

Some General IDisposable tips

  • If you implement a Finalizer, you should always implement IDisposable
  • If you do not have any unmanaged resources, you should not implement a Finalizer
  • If your subtypes are IDisposable, consider implementing IDisposable on the base and than just overriding Dispose(bool disposable) in your subtypes, ensuring you call base.Dispose(disposing) as the last call in the overridden method.
  • Only implement IDisposable on classes when the parent has already done so – don’t re-implement Dispose() or the finalizer.
  • Do not throw exceptions in the Finalizer or Dispose methods
  • Do call dispose on child object that are Disposeable, that are owned by this class.
  • Do call GC.SupressFinalizer(this) in your Dispose() method
  • Put all Finalizer logic in the Dispose(bool disposing) method and make sure that method is structured such that when called from a finalize, it will only attempt to access object accessible by the finalize.
  • Dispose() may be called multiple times, even on an already disposed object, and is supposed to handle that situation properly.

When to use a different implementation and which guidelines can we ignore?

The pattern that I have chosen in some cases does differ slightly from this. The key reason for the differentiation (and the only reason I can think of to do something different) is that the base class, nor any of it’s sub classes need to have finalizers.  This means the call to Dispose(bool disposing) would always be passing in true and there is no need to call GC.SupressFinalizer(this) because we don’t have one. I didn’t want to create one just to support the pattern because the presence of one will add cycles at either garbage collection or shutdown (more likely the latter, we would have suppressed it during dispose). So here is the answer:

  • When you will never use a finalizer the class, or any sub-classes that derive from it.

That said, you should keep the pattern close to the standard one, still creating the Public Dispose() method that calls another virtual method that contains the disposal logic and have sub-classes over-ride that.

A different implementation of IDisposable

protected bool Disposed { get; private set; }
private bool _disposing;
 
public void Dispose()
{           
    if (!_disposing && !Disposed)
    {
        _disposing = true;
        PerformDispose();
    }
}
 
protected virtual void PerformDispose()
{   
    // Disposal of managed resources here       
    Disposed = true;
}

In this version, there is no finalizer. I am keeping the actual disposal logic out of the Dispose method.  The sub classes override PerformDispose(). The disposing and Disposed flags handle checking to see if the object is already disposed, or is being called by recursion or in other cases where we are already in the process of disposing. PerformDispose is used as a substitute for Dispose(true) and as a guard against people attempting to add finalizes or Dispose(false) in subclasses.

Common Mistakes

These examples are all things I came across in a recent task at work

Shouldn’t override dispose
public class AClass: BaseClass, IDisposable
 
public override void Dispose()
{
    someObject.IsMinChanged -= new EventHandler(someObject_IsMinChanged);
    someObject.IsMaxChanged -= new EventHandler(someObject_IsMaxChanged);
    base.Dispose();
}

In this example, we are overriding the dispose method.  We should move this logic protected virtual method called by Dispose on the base class instead, and not actually implement IDisposable on this class.

Managed and Unmanaged the wrong way around

private void Dispose(bool disposing)
{
    // Check to see if Dispose has already been called.
    if (!_disposed)
    {
        // If disposing equals true, dispose all managed
        // and unmanaged resources.
        if (disposing)
        {
            // Dispose managed resources.
            // WE HAVE NO UNMANAGED RESOURCES
        }
        if (_transaction != null)
            _transaction.Dispose();
 
        _someObject = null;
        _someOtherObject = null;
 
        // Note disposing has been done.
        _disposed = true;
    }
}

In this case the all caps comment that “WE HAVE NO UNMANAGED RESOURCES” is true. Therefore all resources being disposed could only be disposed by the GC and not by the finalize (there is one).  Everything outside the “If (disposing) block should do a swap with the comment about unmanaged resources, except the last line setting the _disposed variable to true.

Unmanaged resources includes managed ones

private void Dispose(bool disposing)
{
    if (disposing)
        DisposeManagedResources();
 
    DisposeUnmanagedResources();
}
 
private void DisposeManagedResources()
{
    // Nothing yet
}
 
private void DisposeUnmanagedResources()
{
    if (_disposed)
        return;
 
    var disposable = _aClass as IDisposable;
    if (disposable != null)
        disposable.Dispose();
    _disposed = true;
}

On the face of it, this is a really clean and well organized implementation. However they need to swap the content of DisposeUnmanagedReosurces() and DisposeManagedResources(), and move the checks on _disposed to the Dispose(bool disposing) method.

Conclusions

I Disposable is a simple and useful interface that is misunderstood. Hopefully this blog post has been helpful.

A memory leak may occur when you use data binding in Windows Presentation Foundation

This is old news, in fact it’s been known about since 2007 and it’s by design. However, it came up at work today and it’s a surprise to me. Since it’s by design however, it’s both easy to fall into and easy to work around.

Here’s the Microsoft support ticket.
https://support.microsoft.com/en-us/kb/938416
Note that it hasn’t been modified since 2007, and yet, this is the first I’ve heard of this. Maybe this makes me a bad developer, or someone who didn’t fully take on the technicalities of what’s actually happening under the hood. The latter, hopefully.

The ticket does a decent job of explaining the detail it in fairness so please go and read that.

Here’s the short, simplified version:

  • Bindings are designed to work with Dependency Properties or classes that implement INotifyPropertyChanged.
  • Bindings that are to properties that don’t fit that criteria bind via the PropertyDescriptor and create strong object references, which can stop these objects from being garbage collected.

So how should you avoid this

<Label Name="MyLabel">
   <Stack Panel Name="MyStackPanel">
      <TextBlock Text="{Binding ElementName=MyStackPanel, Path=Children.Count}" />
   </StackPanel>
</Label>

The good news is that the ways to avoid these things have long been seen as good practice. That said, it’s good to be reminded, and things like the sample above really are not that obvious.

  1. In general, don’t create data bindings to plain C# classes. Follow the MVVM pattern and implement INotifyPropertyChanged, and have the properties you bind to use it.
  2. When you want to bind to a collection in your view model and use the properties of the collection in your binding (rather then properties on the collection items, which should come under point 1), use ObservableCollection which does implement INotifyPropertyChanged, or CollectionViewSource to wrap a different collection type, rather than collections or interfaces like List or IEnumerable which don’t.
  3. Use OneTime binding.  This is one way to not need to implement INotifyPropertyChanged. Of course, it’s only really useful if the view you are using is showing static information and not likely to be interacted with. TextBlock’s are often great candidates for OneTime binding (I think the default in WPF for the Text Property is OneWay, meaning they respond to ViewModel updates).
  4. Bind to dependency properties part 1. One place you might do this is binding to elements in a custom control to properties on an associated class.
  5. Watch out when binding to properties on other controls.  As the example in the Microsoft explanation points out (and copied above), it’s easy to quickly bind to regular CLR properties. e.g StackPanel.Children.Count (Children is a UIElementCollection that doesn’t implement INotifyPropertyChanged or INotifyCollectionChanged).

If you do think you might have memory leaks created by this, there are some bits of info on solving these in the following (dated but still useful) posts:

Cory Plotts: WPF and Memory Leaks
Jossef Goldberg: Finding Memory Leaks in WPF-based applications