A pleasant walk through computing

Comment for me? Send an email. I might even update the post!

Disable Windows 10 Photo Automatic Albums

image

It’s dumb that:

  1. Windows 10’s default photo viewing app automatically creates albums for you.
    image
  2. You can’t disable that feature.
  3. Instead, you have to remove the application using PowerShell.
  4. Which means your default photo viewing app becomes something dumb like Paint.

image

http://answers.microsoft.com/en-us/windows/forum/apps_windows_10-photos/is-there-any-way-to-disable-the-windows-10-photo/ce616a54-7ce0-44e3-8d47-d56589fc3743?page=1

PowerShell command to remove Photos:

Get-AppxPackage *photo* | Remove-AppxPackage

Note: According to some, setting another program (like Paint) as your default photo viewer might disable automatic album generation without removing the app. I didn’t test it, because the only thing I’d use the app for is as a viewer. Not an editor. Just an on-the-fly viewer.

------------ EDIT 1 -------------

It’s possible to restore using the Windows 7 Windows Photo Viewer as the default. The program is still installed in Windows 10, it just doesn’t have its file associations enabled by default. Follow these instructions:

http://www.tenforums.com/tutorials/14312-windows-photo-viewer-restore-windows-10-a.html

Note: I haven’t tried the above, but TenForums (and its sister, SevenForums) is reputable.

------------ EDIT 2 -------------

I’ve installed the free (for home use) FastStone Image Viewer, set it as as my default photo viewer, and changed one setting. I’m now happy. I can already see this app will make me more productive, and I’ll likely be donating money to it.

Setting I Changed

The default behavior of FastStone is to open a double-clicked image file in full screen mode. I prefer opening in a window because I often need to view the photos while doing something else.

  1. Open FastStone
  2. Settings (F12) > Viewer
  3. Associated image launches in: Windowed View
    image

Features

In full screen mode, moving the mouse to the top, bottom, right or left of the screen reveals a specific menu. For instance, at the top is thumbnails and some command buttons.

FastStone has a lot of features, but here are my needs and how FastStone met them.

Double-click an image and view in window.

  1. Search > Default Programs
  2. For Photo viewer, choose FastStone.

image

Easily move to next/previous image.

  • In any view, use the arrows to navigate.
  • In windowed view, there are buttons in the tool bar.
  • In any view, bring the mouse toward the screen bottom and arrows will appear/

image

Quickly get some image properties.

  • In any view, press “I”.
    image
  • In full screen view, move cursor to right side.

View as a slide show.

  • In windowed view, click the Slide Show button image
  • In full screen, move mouse to top, bottom or left and find the Slide Show option in the menu.

image

References

Here are 4 Best Image Viewers for Windows 10

A Layman’s Explanation of Mocking and Dependency Injection

A Sad Tale of Woe Again

image

So your husband or wife is a software engineer, and you’re not. You like the idea of software, you even use software, but you are as interested in what goes into creating software as you are in soap manufacturing. He (or she, but programming is still a stupidly male-dominated field, so we’ll stick with the percentages) comes home, blathering on about his day. The conversation goes something like this:

Him: “They handed me a legacy codebase today. It’s ancient .Net 2 stuff. I’m supposed to refactor the existing code and, in parallel, rewrite it to .Net 4.5.”

You: (silent, but thinking, “I wonder if crocodiles attack alligators. Or can they mate with them? You only hear about crocodiles or alligators, not crocodiles and alligators. Is a ‘crocogator’ a thing?”)

Him: “I spent about five hours just looking at the stack. What a mess! I mean, it’s not bad, really, but before I make any changes I need a way to unit test, and it’s not architected for that. I don’t want to go down the rabbit hole since I’m rewriting the whole thing using SOLID DDD principles, but I’ve got to get some DI going, and I’m going to have to figure out how to mock some of the internals.”

You: (nodding, and thinking, “If I pull weeds today, then I can mow tomorrow and feel virtuous two days in a row, and treat myself to wine at lunch on Saturday.”)

Him: “Can I brainstorm the unit testing with you? Just, you know, talk it out? That would really help.”

You: (nodding slowly, thinking, “O! M! G! Just cut off my head and pour cabbage into it! Still, he’s a good man. All I have to do is listen.”

Him: “Stop me any time if I can explain how something works.”

You: “OK, honey.” (but thinking, “The weeds. I was going to pull the weeds.”)

Unbaffling Language to the Rescue!

The only thing worse than listening to a software developer talk about code is asking a sailor about an upcoming voyage. Here are some actual nautical terms and phrases: cumshaw, geedunk, abeam, baggywrinkle, beat to quarters, by and large, coxswain. The definition of “death roll”?:  “In a keel boat, a death roll is the act of broaching to windward, putting the spinnaker pole into the water and causing a crash-gybe of the boom and mainsail, which sweep across the deck and plunge down into the water.” [Wikipedia]

Water. I drink water. I understand water.

Programmers don’t need to live lives of unending, habitual obfuscation. We can explain, if we but remember the lessons of literature.

The Totally Contrived, Ridiculous Metaphor

Imagine you’re a high school teacher. Now, imagine that you have a four-inch wood splinter going through your left eyelid. Which is easier on your mental state? If you say “splinter,” you must be a teacher.

Now, imagine a magical school where you don’t have to grade your own papers. You finish your eight-hour work day, go home, take an hour planning the next day’s lessons, have dinner, and study an hour or two for your required continuing education course, but you don’t have to grade at least twenty-five of the 120 five-page essays from mid-term exams.

Instead, you get to hand the exams to your Grading And Reports Department. It works like this:

  1. Give Mr Michael Murphy your stack of 120 essays.
  2. A few days later, pick up the graded essays and a formatted report of the students’ grades, broken down by class period, by student, and summarized with comparative aggregates. It’s a great report.

Recently, you were tasked with testing the GARD system. You’re a great choice, because you helped create the department. Here’s what you know:

  1. Mr Murphy takes the papers and gives them to Dr Marcia Malone. Dr Malone grades every paper. She gives the results back to Mr Murphy.
  2. Mr Murphy aggregates the grades and creates the formatted report.
  3. You helped train Dr Malone, who is brilliant. She can grade anything. But teachers have no control over how she grades.
  4. The grading scale Dr Malone uses could change at any time. Today, 90-100% could be an “A.” Tomorrow, 93-100% could be an “A.” (Remember, this is a contrived example.)

Here’s a lousy illustration.

You give the papers to Mr Murphy

image

Mr Murphy gives the papers to Dr Malone, who does mysterious, magical mischief.

image

Mr Murphy gives you back the papers.

image

You have only been asked to test the report formatting. This is critical! You are not verifying the grades are correct. You only care about the report. You devise this test

Given a stack of 120 papers, if the grades are abc, then report should look like xyz.

So here’s your challenge. You are going to give Mr Murphy 120 papers. He’s going to create the report. You’re going to compare what he gives you with how you know the report should look, right down to the numbers and letter grades on it. If they match, the test passes. If not, the test fails.

“Crap!” you think, “I can’t depend on Dr Malone to always give Mr Murphy the same grades! Besides, it takes her three days on average to grade that many papers, and I want my tests to be done in a day. It only takes Mr Murphy a few hours to prepare a report.”

You develop a plan. You are a genius.

  1. You build an automaton that looks like Dr Malone. But, it doesn’t actually grade anything. It just gives back a consistent set of scores that you tell it.
  2. When you give Mr Murphy the papers, you’ll also give him the automaton.
  3. Instead of Mr Murphy handing the papers to Dr Malone, he’ll hand them to the automaton and immediately get back your scores from it.
  4. Mr Murphy formats the report and gives it to you.

More laughable illustrations, but let’s include the programming terms.

We have a dependency on our grader, Dr Malone. We’ll change the GARD room so that we can give it a real or fake grader. This is called Dependency Injection.

image

Mr Murphy doesn’t care which grader he gets answers from. For our test, he uses the fake one. That is, he uses a Mock (also called a fake, or stub, or substitute).

image

We get back the report made from data we injected. We just want to compare the reports, the work Mr Murphy does.

image

If they match, the test passes. If not, fail!

image

How a programmer sees this

A programmer sees it the same way. Except it’s all words that look like English, but are alien-ese.

The Interface

image

The Production Code

image

Using the Production Code

image

The Test Code

image

Wrap Up

Dependency Injection and Mocking solve two problems that affect how well software can be tested.

  1. Dependency Injection lets us control what external dependencies, like a grading engine, a method uses. If we couldn’t do this, we’d have to always use production data, when that’s not what we’re always testing.
  2. Once we can inject a dependency, we can Mock its behavior. That is, we can make it do whatever we want, giving the method under test consistent results. Again, we’re not testing the dependent service. We’re testing the method that is using it.

It takes some work, but once you get your head wrapped around these concepts and their implementation, their importance becomes clear.

Catching Up on Coding - TDD Part 3

I’ve been a software developer for twenty years, but am behind in some skills. This series chronicles my self-improvement.

It turns out that unit testing exercises a lot of coding methods for more maintainable code. Some methods involve deception, so who better to inspire us than our “Butch Cassidy/Sundance Kid” knockoffs from 70s show Alias Smith and Jones? The difference is, I’m not trying to “get out of this business.”

Previously on CUOC: TDD Part 2
Next Episode: Claims-Based Identity Part 1

 

Teaser

Unit testing benefits from mocking and Inversion of Control. I’d argue that it’s hard to effectively unit test without these techniques. Parts one and two of this TDD series used hand-crafted mocking and IoC. Today, we’ll redo some tests using 3rd party tools/frameworks.

Act 1 – Choosing the Tools

I researched what developers are recommending for mocking and IoC. Of course, opinions abound, but in the end I came to a few conclusions.

Mocking

  • No one recommends Rhino Mocks anymore. It appears to be a mostly dead project.
  • Moq is still used, but is falling out of favor.
  • Developers like NSubstitute and FakeItEasy.
  • NSubstitute has a more concise API. FakeItEasy is more natural language and less ambiguous.
  • My reaction to seeing them side-by-side is that I like FIE’s syntax more. I like tests that are immediately easy to understand.
  • But I’m a little put off by the verbosity, so I’ll try NSubstitute first.

References

C# Test Mocking Frameworks

NSubstitute: A Refreshingly Simple Mocking Framework for Unit Tests

Mocking: why we picked NSubstitute

Easy Mocking with FakeItEasy

IoC

  • Ninject is the most popular, and has the worst performance (though some developers argue that IoC container performance doesn’t matter).
  • Unity is supported (for now) by Microsoft, but people have complained about some limitations.
  • StructureMap, Autofac, and Simple Injector remain as the choices. Based on a few reviews—but mostly gut instinct—I’m going to use Simple Injector. (Autofac would be my second choice.)

References

IoC Container Benchmark – Performance comparison

Inversion of Control Containers Basic Comparison

IoC Battle in 2015 results: Using Ninject – think again!

Generic variance in DI containers

Simple Injector Migration Guide <-I love that they include how to migrate away from their product. Also serves as a coding comparison.

Act 2 – Making a Mockery of Testing

Install NSubstitute

  1. Install the package into the unit test project using NuGet.
  2. After installation, a nice readme.txt file opens. Read it.

Replace a Previous Test

In my previous tests, I created my own mock Registry wrappers from IRegistryWrapper and IRegistryMockWrapper. These are interfaces I created to allow Inversion of Control of the Registry. IRegistryWrapper looks like this

    public interface IRegistryWrapper
    {
        object GetValue(string keyName, string valueName, object defaultValue);
        void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind);
    }

the hand-crafted mock looks like this

    class RegistryMock : IRegistryWrapper
    {
        public object GetValue(string keyName, string valueName, object defaultValue)
        {
            //this may become cumbersome, but for now specify some return values
            switch (keyName)
            {
                case @"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent":
                    if (valueName == "Version") return defaultValue;
                    break;
            }
            throw new Exception("Invalid keyName");
        }

        public void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind)
        {
            throw new NotImplementedException();
        }
    }

here’s the unit test

    public class RegistryService_GetRegistryKeyValue_Should
    {
        IRegistryWrapper _registry = new RegistryMock();
        IRegistryKeyWrapper _registryKey = new RegistryKeyMock();

        [Fact]
        public void ReturnNullConstantTextIfValueIsMissing()
        {
            var service = new RegistryService(_registry, _registryKey);
            var result = service.GetRegistryKeyValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version");
            Assert.Equal(result, service.NoValue);
        }
    }

and finally, here's the RegistryService method that passes the test

        public string GetRegistryKeyValue(string keyName, string valueName)
        {
            try
            {
                //value will be null if no value found, and the default value if the key is missing. But we only care that there's no value.
                //Null can't be returned to the client. Don't return empty, since that's ambigious (did the key exist?).
                //Return a magic string.
                object value = _registry.GetValue(keyName, valueName, null); //guarantees null if no value or missing key.
                return value != null ? value.ToString() : NoValue;

            }
            catch (Exception ex)
            {
                return "Error attempting keyName '" + keyName + "' and valueName '" + valueName + "'\r\n" + ex.GetBaseException().Message;
            }
        }

All I’m going to do is refactor the test so that I use NSubstitute instead of my own mocks. I’ll need a mock for IRegistryKeyWrapper because the class expects it, but I won’t set any behavior on it.

Note: remember to add “using NSubstitute;”

In my hand-crafted mock, I specified return values based on the arguments to GetValue, and otherwise threw an exception. For my unit test, I need to do something similar. Here’s my first attempt, and it does indeed pass.

            
            var registry = Substitute.For<IRegistryWrapper>();
            var registryKey = Substitute.For<IRegistryKeyWrapper>();
            //Registry.GetValue will return null if the valueName doesn't exist.
            registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version", null).Returns(null);
            var service = new RegistryService(registry, registryKey);
            var result = service.GetRegistryKeyValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version");
            Assert.Equal(result, service.NoValue);

The problem is (or seems to be), if I change the substitute's argument "Version" to "Blamo", the test still passes. This is happening because given an unknown argument the method will still return null. I need to tell the substitute that it should only return null if it gets the right arguments.

Or do I?

No, I don’t. I’m attempting to give my mock too much behavior. I only want the mocked Registry to pretend that the value was missing and return null. Elsewhere I’ll test the behavior if the value exists. My hand-crafted mock was eventually going to give me trouble because it was doing too much and it wasn’t really behaving like the Registry class.

The Heart of Mocking

The method I’m testing happens to be  a good one for getting at the essence of mocking. RegistryService.GetValue is almost a pass-through to Registry.GetValue. But, it has its own behavior and is supposed to call Registry.GetValue.

As the developer and tester, I know three things:

  1. How external dependencies behave (Microsoft.Win32.Registry).
  2. How my test behaves.
  3. What’s in my method.

That last one is the problem. I know my method calls Registry.GetValue(), because I wrote it. But that’s a serious mental mistake when it comes to the test. I need to write my tests, whether before or after, as if I knew nothing about the method’s code. I should pretend the only things I know about the method are:

  1. The parameters it’s called with.
  2. The dependencies it has.
  3. The result when it’s called with particular values.

In short, my method is a black box. It could be empty, for all I know. That’s why TDD starts with an empty method, so that it fails first. If it succeeds when empty, that’s a problem. When my method has a dependency, I need to only mock up what that dependency will do if it’s called with the expected value.

But, I mustn’t assume the mocked dependency has been called at all.

So, here’s how my test should look.

            //Arrange
            var registry = Substitute.For<IRegistryWrapper>();
            var registryKey = Substitute.For<IRegistryKeyWrapper>();
            //Registry.GetValue will return null if the valueName doesn't exist.
            registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version", null).Returns(null);
            var service = new RegistryService(registry, registryKey);
            //Act
            var result = service.GetRegistryKeyValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version");
            //Assert
            //First, make sure the mocked Registry was called at least once. Otherwise, we might have a false positive.
            registry.Received().GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\EduAgent", "Version", null);
            //Now make sure we got back the expected value from our method.
            Assert.Equal(result, service.NoValue);

To sum up, some key lessons of unit testing are:

  1. Treat the method under test as a black box.
  2. Test behaviors of the method, not its dependencies.
  3. Verify mocked dependencies are called.

A mocking framework gives more value than just controlling return values. It lets you know that your dependencies are being used the way you expect.

Act 3 – Ouch! Injecting Dependencies

  1. Interfaces are used in production code to make it easier to inject dependencies.
  2. Mocking frameworks are used in unit testing code to control injected dependencies.
  3. IoC containers are used in production code to manage injected dependencies.

For the first two, see Act 2, above.

I don’t have  to use an IoC container. I can write code like this:

//pass the live registry wrappers
RegistryService service = new RegistryService(new RegistryWrapper(), new RegistryKeyWrapper());

I could also let my class have default dependencies. This might be OK, as long as the caller knows what to expect. It would be considered "convention over configuration."

    public class RegistryService
    {
        private IRegistryWrapper _registry;
        private IRegistryKeyWrapper _registryKey;

        public RegistryService()
        {
            _registry = new RegistryWrapper();
            _registryKey = new RegistryKeyWrapper();
        }
        public RegistryService(IRegistryWrapper registry, IRegistryKeyWrapper key)
        {
            _registry = registry;
            _registryKey = key;
        }
        ...
    }

    //usage, by default uses the Windows Registry.
    var service = new RegistryService();

For simple cases, using an IoC is overkill. In fact, I would say:

Don’t use an IoC container unless you have to.

When do you “have to”?

  • Where there are lots of dependencies.
  • When you have lots of nested dependencies.
  • When you want your dependency initialization to be in one place.

There are probably other reasons, but those will do for now.

Install Simple Injector

  1. Get it from NuGet, install to the project that’s injecting the dependencies.

Injection!

First, I prepare my RegistryService class for dependency injection.

    public class RegistryService
    {
        private IRegistryWrapper _registry;
        private IRegistryKeyWrapper _registryKey;

        public RegistryService(IRegistryWrapper registry, IRegistryKeyWrapper key)
        {
            _registry = registry;
            _registryKey = key;
        }

My Windows service, EduAgent, is calling the RegistryService, which is in a separate DLL. I want all my dependencies initialized once, in one place. The service’s Main method is the starting point. But, you know what, to make it easier for another developer, I’ll create a class called DependencyInjection, which we’ll call from Main. That makes it pretty clear where the dependencies are maintained, and how.

All we’re doing here is saying “if I request from ‘container’ a type of IRegistryWrapper, give me an instance of the class RegistryWrapper.”

    public static class DependencyInjection
    {
        public static Container container;
        public static void InitializeDependencies()
        {
            //create container
            container = new Container();
            //register interfaces
            container.Register<IRegistryWrapper, RegistryWrapper>();
            container.Register<IRegistryKeyWrapper, RegistryKeyWrapper>();
            //register concrete types
            container.Register<RegistryService>();
            //optionally verify
            container.Verify();
        }
    }

I initialize the dependencies.

    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        static void Main()
        {
            DependencyInjection.InitializeDependencies();
            ServiceBase[] ServicesToRun;
            ...

Notice that during initialization, I’m also registering the concrete type RegistryService. I’m doing this so that I can request an instance of RegistryService without passing any constructor arguments. The container knows what to pass in on my behalf.

   //pass the live registry wrappers, which are auto-wired by Simple Injector
   RegistryService service = DependencyInjection.container.GetInstance<RegistryService>();

This is the same as if I had done this:

   RegistryService service = new RegistryService(new RegistryWrapper(), new RegistryKeyWrapper());

But by using an IoC container, if I use a different (again, fictitious) registry provider, I only need to set it in one place: InitializeDependencies.

Tag

There’s a lot more to mocking and dependency injection than the above samples show. I ran into a pretty significant problem because my original IRegistryKeyWrapper included IDisposable, which plays hell with dependency injection.

Lesson: Sometimes these tools add complications. But other times, they reveal problems in your code.

On the subject of complications, one of the stars of Alias Smith and Jones killed himself during the first season. He suffered from depression and alcoholism. To this day, that makes me sad. Pete Duel, I miss what you could have done.

image