.NET Framework Extension Methods

Going over the Design Patterns coined by the Gang of Four (GoF), and working with the Decorator pattern quite a bit recently, I did a comparison of this pattern and the .NET Framework extension methods. So, does an extension method extend a class such as the Decorator pattern advocates? On first looks possibly, but an extension method doesn’t wrap the class being extended, it is a compiler “trick”. I think that extension methods are more akin to the Visitor pattern.

Advertisements

A simple Quicksort in place

I’ve been “practising” my quicsort skills lately, and tried various ways of implementing it, but I think the Lomuto partition scheme is the best and potentially the easiest to implement.

int Partition(ref int[] intArray, int low, int high) {
    // Pivot is set to the last element   
    var pivot = intArray[high];
    var i = low - 1;
 
    for (var j = low; j <= high; j++) {
        if (intArray[j] <= pivot) {
            i++;
 
            if (i != j) {
		// Swap ints at pos i & j
                var tmp = intArray[i];
                intArray[i] = intArray[j];
                intArray[j] = tmp;
            }
        }
    }

    return i;
}
 
int[] Sort(int[] intArray, int low, int high) {
    if (low < high) {
        var p = Partition(ref intArray, low, high);
        intArray = Sort(intArray, low, p - 1);
        intArray = Sort(intArray, p + 1, high);
    }
 
    return intArray;
}
 
Sort(intArray, 0, arraySize - 1);

Visual Studio 2017 Extension Load Error

After installing quite a few extensions by using the Extensions and Updates command on the Tools menu, I started to get a load error every time I opened Visual Studio, telling me to check the ActivityLog.xml in the C:\Users\…\AppData\Roaming\Microsoft\VisualStudio\15.0_709865ab folder. I opened the file and found numerous entries like this one:

System.ComponentModel.Composition.ImportCardinalityMismatchException: Duplicate EditorFormatDefinition exports with identical name attributes exist. Duplicate name is PowerShell Interactive – Black

I suggested to me I had to check for duplicate extensions, and I had indeed installed two editions of the same extension, PowerShell Tools for Visual Studio 2017 as well as the old one, PowerShell Tools for Visual Studio 2015. Uninstalling the latter solved the issue. 🙂

C# Singleton

There are a number of ways to implement the Singleton pattern, and most will work well. This is the easiest implementation I can think of, making use of the various language features and the .NET Framework.

public sealed class Singleton : ICloneable {
    // Ensure lazy loading
    private static readonly Lazy<Singleton> Lazy =
        new Lazy<Singleton>(() => new Singleton());
 
    public static Singleton Instance => Lazy.Value;
 
    private Singleton() { }
 
    // Prevent cloning
    public object Clone() => throw new NotImplementedException();
}

I’m using the Lazy the class for the lazy loading, very easy. The readonly modifier ensures the Instance property cannot be assigned to after the first call to Instance. The private parameterless constrcutor ensures that you cannot create or new up an instance of the Singleton class. Finally, by implementing then ICloneable interface, you can prevent cloning using the MemberwiseClone method of the Object class.

var s = Singleton.Instance;
var s1 = s.Clone();

Console.WriteLine(s.GetHashCode());
Console.WriteLine(s1.GetHashCode());

Now you’ll see one hascode printed in the console, but the second call will throw an exception. You could of course choose not to implement the ICloneable interface, but then it wll be possible to create an extension method, like this:

public static class ObjectExtensionMethods {
    public static T Clone<T>(this T o) {
        var instance = o.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance |
            System.Reflection.BindingFlags.NonPublic);
 
        return (T) instance?.Invoke(o, null);
    }
}

However, this will fail if you do implement the ICloneable interface.

Visual Studio Editor Pet Peeve

VSEditorPetPeeve

We all have our quirks and one of mine is when you create a new project or just a new class or form, there’s always that extra line at the very bottom of the Editor window. Why? Obviously it shouldn’t matter, but it just ticks me off, and the first thing I do, is to delete the extra line.

What are your pet peeves when programming?

 

Error : DEP0001 : Unexpected Error: A Prerequisite for an install could not be satisfied. (Exception from HRESULT: 0x80073CFD)

I was getting this error when deploying a Universal Windows Platform (UWP) app to my Lumia 830, so I did a quick search online to see if anyone else encountered it. There were quite a number of reports on this error, but none of them did anything to help me. Turns out I had the MinVersion and MaxVersionTested in the Package.appxmanifest file set incorrectly. Once corrected to allow for the lower build number of the Windows 10 Mobile version, it worked just fine.

Windows 10 Build 10130 so ready for us geeks

I’ve been running Windows 10 in a Hyper-V virtual machine for a few months now, but the other day I decided to upgrade my laptop, which I work with!!! I can honestly say that it was a massive surprise to see how smooth the upgrade went. All drivers on my Lenovo Flex 2-15 were upgraded and I’m yet to see a crash. I run Visual Studio 2013, Visual Studio 2015, Office 2013, Skype, OneDrive, GitHub, TortoiseGit, Facebook, SQL Server 2014 and a lot of other programs. Granted, I haven’t tested all of my applications, but so far they’ve all worked as I was hoping for. My laptop has a full HD touch screen, and the new standard font Segoe and the spacing used, makes it such a delight to look at, compared to Windows 8.x. Don’t get me wrong I was one of those that actually liked Windows 8, but this is so much better and the speed of it is just awesome. I do have a 400GB SSD Samsung EVO drive installed, but this release just is faster than Windows 8 on the same hardware. How is that for a pre-release version, eh? Oh, almost forgot, the new Edge browser, previously known as project Spartan, is so much faster and better than IE (IE 11 is still installed), given that the backwards compatibility has been removed.

My Nokia Lumia smartphones (735, 830, 1520) have been running a pre-release version of Windows 10 Mobile for the last few months, and that hasn’t been the same revelation. I have been close to tears at times, because I just couldn’t use any of them for a specific task, such as email (Outlook Mail) or even texting and calling someone. However, the latest build, which I installed after first flashing the devices back to Windows Phone 8.1 (Windows Phone Recovery Tool 2.1.1), and then upgraded to Windows 10 Mobile, is a different beast. I don’t recommend to anyone but the geeks, but it is slick and the performance improvement is there to see and feel.

If you want to take it for a spin yourself, go to the Windows Insider page, https://insider.windows.com/. Good luck and do enjoy!

—————————- UPDATE June 8, 2015 —————————-

Now running build version 10162 on my laptop, and the speed and stability has definitely increased, getting close to RTM. 🙂

On my phone I’m running the Mobile build 10149 and it is, surprise, surprise, the most stable so far. Still some rough edges, but I’m not going back to Windows Phone 8.1 on any of my devices!

There was no endpoint listening at http://… that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.

This error message is often searched for and posted about online, but none of the posts managed to help me fix my issue with a WCF service. Turns out in my case it was a binding issue, it had to be httpsBinding and not httpBinding for the bindingConfiguration attribute in the endpoint element.

<endpoint binding="..." bindingConfiguration="httpsBinding" contract="..." address="..." listenUri="..."/>

Nokia Lumia Internet connection issue

I have a Nokia Lumia 1520, which I love, but dread bringing with me when running. So, I bought a Lumia 735, which has a perfect size for a run, and I love this one too, despite the obvious omision of Glance… Anyhow, I’ve found that it often has an Internet connection issue, and if I’m not wrong, it always happens, after I’ve been on WiFi. I might have a few bars in 4G, but still I can’t connect. Eventually I tried switching to Flight Mode and back, and voila, it fixed the issue… 🙂

UPDATE: The issue is also to be found with Lumia 830 and 930.