JavaScript: Parsing dates with the destructuring assignment syntax

As I was scraping some stuff in a node module I got dates that were either full dates with time (“2017-01-01 12:00”) or just dates without time (“2017-01-01”) but I wanted to do some checking with months and days before sending back a proper Date-object, so I had to parse it out. Using the new ES6 destructuring assignment syntax it got really good looking:

/**
 * Converts a standard format date string, such as "2017-01-03 12:30" or "2017-05-06"
 */
module.exports = (dateRaw) => {
    if(dateRaw === undefined) {
        throw new Error('Invalid date provided!');
    }

    // Returns ['2017-01-03', '12:30']
    const [date, time] = dateRaw.trim().split(' '); 

    // Returns ['2017', '01', '03']
    const [year, month, day] = date.split('-'); 

    // Returns either the time, or, it it's missing, 0 hours and 0 minutes
    const [hours, minutes] = (time !== undefined) ? time.split(':') : [0, 0]; 

    // Do stuff...

    // To get the timezone correct, use Date.UTC
    return new Date(Date.UTC(year, month - 1, day, hours, minutes));
};

Just thought I’d share, because this used to get slightly ugly in ES5…

Windows 10: Choose an operating system-problem

As I was moving my Windows 10 installation from an old borken HDD to a new, fresh SSD I ended up just using Microsofts super-easy Media Creation Tool to create a bootable USB stick. I booted it up and created a new installation on my new SSD after formatting it. All of this went great and I was happy as a hamster.

Then, when I rebooted, I got this horrible screen:

Horrid horrid screen
Horrid horrid screen

I had no idea why this happened and I got it on every boot, so I did some frantic googling and I found in various suspicious forums that the solution was to do this:

1. Open the windows run dialog (Win + R)

2. Enter ‘msconfig’ and click ‘Ok’run_msconfig3. Go to the boot tab (second tab) and remove all other Windows references than the one marked as default

In this screenshot I have only one Windows 10 entry, but I had two when this problem first occurred.
In this screenshot I have only one Windows 10 entry, but I had two when this problem first occurred.

If you save that and reboot (after you have removed the other Windows 10 entries your boot section should look like mine in the above image, minus the enormous red arrow).

Finished, and the problem is gone!

Git: Rewriting commit messages through a rebase

So I accidentally failed in entering a correctly spelled commit message and pushed it. Someone saw it and I felt I wanted to redo it. If it just the latest commit then no problem, you just do an amend, but I had committed once more afterwards. And pushed.
Since I was still in my own branch the solution was to do an interactive rebase and then use reword. So instead of using the pick command I use reword . I start by executing the rebase command with the interactive flag (-i):

git rebase -i master

Then you will see the interactive feature where you can edit your commits. This may be what it looks like:

pick 0db9efc MAF-105: A fantatsic fix!

# Rebase 552b628..3bc00d5 onto 552b628
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Now change the command pick to reword and alter the text. Then you just continue your rebase and your commit comment is changed, like this:

reword 0db9efc MAF-105: A fantastic fix! It's so good!

# Rebase 552b628..3bc00d5 onto 552b628
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Let the rebase finish and you’re done!

SQL SERVER: Checking all tables row count and size

This is one of those posts where I just blurt out neat stuff I just learned! Today I talked to a man who knew a lot more about databases than I do (especially SQL Server) and one of the neat things he taught me were the SQL Server stored procedures sp_msForEachTable and sp_spaceused. This enabled me to put together a very wonderful little function to loop over all tables (using sp_msForEachTable) and fetch information about how much space they use (with sp_spaceused).

I created a function that puts it all in a temporary table because otherwise you just got a whole bunch of individual outputs which may be both hard to read and difficult to export:

CREATE TABLE #tableInformation
(
	name VARCHAR(255),
	rows INT,
	reserved varchar(255),
	data varchar(255),
	index_size varchar(255),
	unused varchar(255)
)

INSERT #tableInformation
	EXEC sp_msForEachTable 
		'exec sp_spaceused ''?'''
		
SELECT name, rows, reserved, data, index_size, unused
FROM #tableInformation
ORDER BY name

DROP TABLE #tableInformation

The output can look like this:

The result table
The result table

EPiServer: Unit test classes with Injected properties

This will be a very short entry but I thought it’d be useful to write it down. When you work with EPiServer you may end up having to use property injection. It is very simple, you add a property of type Injected<T>, where T is the interface of whatever you want injected, and the implementation of your interface (according to your DI-settings) will be injected in to this property.
Even though I’m not a huge fan of this solution it seems to be pretty widely used and if you use it, you want to unit test code that uses it.

To test classes with injected properties you want to create your own ServiceLocator which returns a mock of whatever is being used in the code you want to test. I’ve compiled a small scenario where a class of mine, TestClass, has a property of type Injected<IContentLoader> which a method, StuffDoer, uses. I want to mock the injected property to see if it’s being called, here is the code:

public class TestClass
{
    private Injected<IContentLoader> _contentLoader;

    public void StuffDoer(SiteDefinition definition)
    {
        var stuff = _contentLoader
            .Service
            .Get<PageData>(definition.StartPage);

        //And a whole lot of other stuff...
    }
}

[TestFixture]
public class StuffDoesTests
{
    private Mock<IContentLoader> _mockContentLoader;
    private TestClass _testClass;

    [SetUp]
    public void CreateRequirements()
    {
        //Mock the content loader
        _mockContentLoader = new Mock<IContentLoader>();

        _testClass = new TestClass();
    }
    [Test]
    public void IsGet_Called()
    {
        using (ShimsContext.Create())
        {
            //Mock the service locator
            var serviceLocator = new Mock<IServiceLocator>();
            serviceLocator
                .Setup(x => x.GetInstance<IContentLoader>())
                .Returns(_mockContentLoader.Object);

            //Set your mocked service locator to be used
            ServiceLocator.SetLocator(serviceLocator.Object);

            //Call your method
            _testClass.StuffDoer(new SiteDefinition());

            //Verify that the Get<T> method was called!
            _mockContentLoader
                .Verify(x => x.Get<PageData>(It.IsAny<ContentReference>()), Times.Exactly(1));
        }
    }
}

EPiServer: How to unit test with all those static methods…

So, I’m working with EPiServer now and I want to unit test my code. It is hard. Very hard. The code base I have is not wrapping any of the EPi dependencies and there isn’t time to re-write the code just for unit testing so I have to figure out another way to test my code. I’ve tried to find good frameworks to mock static methods, but there aren’t any free ones (well, as I’m writing this, I actually found one, so keep on reading).

There are, however, commercial frameworks that does this. One of them is Microsoft Fakes. Now, this is a bit price heavy as it is only available in the VS Premium/VS Ultimate bundle (Premium is about $6000, so it’s really not free) but if you have it available then this is the article for you :).

These are the alternatives I’ve found, even though this article will use Microsoft Fakes:

  • Microsoft Fakes ($6000, with Visual Studio 2012 Premium or above)
  • Just Mock (Telerik, $399)
  • Type Mock ($399)
  • Prig (Free, I just found this when writing the article, I’ll get back to you on this one :P)

 

So, your underlying problem would be these static methods. The following code depicts an example where I want to get carts from EPi Commerce using the OrderContext singleton. I also use the static LocalizationService for getting an error message if I can’t find any carts. Disclaimer: the following code is just an example, returning a Tuple as a result isn’t great and the general standard of the code is abysmal. Take it for what it is, an example.

 

public static class Foo
{
    public static Tuple<string, Cart[]> GetCarts()
    {
        var parameters = new OrderSearchParameters(); //Fill with whatever
        var options = new OrderSearchOptions(); //Fill with whatever
        int recordCount;

        var carts = OrderContext.Current.FindCarts(parameters, options, out recordCount);

        if (recordCount == 0)
        {
            string errorMessage;
            LocalizationService
                .Current
                .TryGetString(
                    "/general_error", out errorMessage);

            return Tuple.Create(errorMessage, new Cart[0]);
        }

        return Tuple.Create(string.Empty, carts);
    }
}

So, we have a static method that returns a Tuple. If something goes wrong the Tuple contains an error message. I don’t expect you to like this code, the point of it is that it has static dependencies and you need to test the method. You may not even have written the code yourself, but you want to test it anyway to find ways to improve it (without wrapping and changing it too much).

To use Microsoft Fakes you must have either Visual Studio 2012 Premium/Ultimate (or probably 2013+). To generate the fake versions of your static methods you need to fake the DLL’s they’re in. You do this by, in your test project, right-clicking on the reference and selecting Add Fake Assembly. This will generate a folder in your project called Fakes in which you will find a .fakes file with the references name first. In this example I need to fake EPiServer.Framework and MediaChase.Commerce so in that folder I now have two files called EPiServer.Framework.fakes and MediaChase.Commerce.fakes.
This gives us Stubs and Shims on everything available in those DLL’s. Read more about the difference between stubs and shims on this link.

Using Microsoft Fakes you can now write tests on the above code like this (notice that all usage of shims must occur inside a ShimsContext):


[TestFixture]
public class FooTest
{
    [Test]
    public void IfCarts_AreFound_ReturnCarts()
    {
        using (ShimsContext.Create())
        {
            //Set the OrderContext singleton up!
            ShimOrderContext.CurrentGet = () => new ShimOrderContext();
            ShimOrderContext
                .AllInstances
                .FindCartsOrderSearchParametersOrderSearchOptionsInt32Out =
                (OrderContext t, OrderSearchParameters parameter, 
                    OrderSearchOptions options, out int recordCount) =>
                {
                    recordCount = 1;

                    //This part is important. FormatterServices allows
                    // for you to create an instance of a class without
                    // the usage of its inherit constructs. The Cart class
                    // has a lot going on during instantiation which
                    // causes problems when you just want a "mock".
                    var deadCart = (Cart)FormatterServices
                        .GetUninitializedObject(typeof(Cart));
                    return new[] { deadCart };
                };

            //Run test
            var resultTuple = Foo.GetCarts();

            //Check the results
            Assert.That(resultTuple.Item1, Is.Empty);
            Assert.That(resultTuple.Item2.Length, Is.EqualTo(1));
        }
    }

    [Test]
    public void IfCarts_AreNotFound_ReturnErrorMessage()
    {
        using (ShimsContext.Create())
        {
            //Set the localization service up!
            const string errorMessage = "An error!";
            ShimLocalizationService.AllInstances
                .TryGetStringStringStringOut =
                (LocalizationService instance, string input, out string output) =>
                {
                    output = errorMessage;
                    return false;
                };

            //Set the OrderContext singleton up!
            ShimOrderContext.CurrentGet = 
                () => new ShimOrderContext();
            ShimOrderContext
                .AllInstances
                .FindCartsOrderSearchParametersOrderSearchOptionsInt32Out =
                (OrderContext t, OrderSearchParameters parameter, 
                    OrderSearchOptions options, out int recordCount) =>
                {
                    recordCount = 0;

                    return new Cart[0];
                };

            //Run test
            var resultTuple = Foo.GetCarts();

            //Check the results
            Assert.That(resultTuple.Item1, Is.EqualTo(errorMessage));
            Assert.That(resultTuple.Item2.Length, Is.EqualTo(0));
        }
    }
}

You have now created a fake (shim) version of you static dependencies. The tests run and you can go back to being happy again!

Additional extra super-duper note: EPiServer contains a whole bunch of classes such as the Cart-class which during instantiation does a whole world of things which requires you to feed it with proper data or have a working database connection or else it crashes horribly. In order to bypass those constructs I’m using the FormatterServices.GetUninitializedObject method which allows for you to create an instance of a class without calling the constructor of that class. It’s brilliant and very useful when unit testing EpiServer.