My Year in Gadgets

I like gadgets, and so I tend to buy a lot of them. Some are life-changers, and some fizzle out after a few weeks or months. Here’s a rundown of notable gadgets I’ve acquired this year.

Bose SoundLink Mini Bluetooth Speaker

This little guy ended up on my wish list after playing with a demo at Best Buy. I definitely had a “whoa” moment when I heard it for the first time. So, when I moved into an office at work, I decided it was time to pull the trigger. I mean, it would be silly for me to listen to headphones in a room all by myself, right?

This is one purchase that I have zero regrets about. I use it almost every day. I listen to music in the office, NPR in the kitchen, and have toddler dance parties in the living room. It’s also great for being outside. The battery life is really good. I can’t tell you exactly what it is because I think it’s only gone dead on me once or twice. (It has a charging dock that I keep on my desk, and that’s it’s usual resting place.) I think you get a good 10+ hours on a full charge, though.

JayBird BlueBuds X Sport Bluetooth Headphones

After going to the gym for a few weeks, I decided it was time to invest in a pair of quality workout headphones. I wanted to go wireless because I’ve never really liked having the cord flopping around while I run, but I also wanted great sound since I could be using them 5-10 hours each week between workouts and other uses.

First, the good. The sound quality did not disappoint. I was nervous that I’d regret not going for a pair of wired buds with better quality, but these were great. The battery life is pretty good. I charge them every few days, and that’s sufficient to keep them from ever dying on me.

There is some bad with these, though. It took me a week or two to get used to them. In the first few days, I was really disappointed. I had tried a few different configurations (cord over the ear, under the ear, different size buds & wedges), but they weren’t comfortable and kept falling out during workouts. However, I stuck with them, found a configuration that I like, and no longer have any problems–so don’t give up! The only problem I have with them now is that every now and then, I’ll have problems with the audio just stopping. I don’t know if it’s my phone or the headphone that’s the culprit, but I’ll be listening to a song and it will just stop. There is no indication that I have disconnected, but I can take a few steps to reconnect and everything will be fine. I have tried rebooting my phone, power-cycling the headphones, and anything else I could think of. Most days everything is fine, but it’s super annoying on that one day every other week where it’s being temperamental. There have been a couple of days where I’ve given up on them and just stuffed them into my pocket during a workout.

One final gripe is that when I’ve used these to watch Netflix in bed, the audio has been out-of-sync with the picture. The audio sounds great, so I don’t blame the headphones here, but it’s out-of-sync due to bluetooth. So it’s not a problem that I’d have if I’d gone with wired ear buds.

Despite this seemingly negative review, I’m happy with what I’ve got. I’m sure that if I’d selected a wired pair, I’d have regrets about the cord. I love the sound and they’re comfortable. Great for listening to music, not-so-much for video.

Jackery Giant+

A portable power bank is one of those things that I never seemed to think about unless I was in need of one. Before my most recent trip out to the west coast, I decided to pick one up. I was initially deciding between the Lumsing 10400mAh and the Jackery Giant. I liked the Lumsing because it’s super-economical ($25), but I ultimately went with the Giant+ because of–of all things–the location of the USB ports.

One of the reviews of the Lumsing pointed out that it was awkward to use the charger from a pocket. I don’t expect that I’ll be doing my charging from my pants (but who knows), but I like that I can stick the Giant+ in an inner pocket of my backpack and still have the ports exposed. When I need some juice on the go, I can easily plug-in without any fuss and toss the device in need of charging into my backpack. The Giant+ is also slightly bigger (12000mAh) and has a flashlight. The flashlight seems like it could be useful, but the question is whether I’ll have the Giant with me when I need it!

Microsoft Band

When the Band was first announced, I was very “meh” about it. I had been looking for a watch with a built-in timer or stopwatch to help me with my workouts, and so I convinced myself to try it out. I headed over to my local Microsoft Store and they were all out of stock. Now that I couldn’t have one, I really wanted one. So I got myself on a list and waited.

It came a couple of weeks later. I’ve had it for about a month now, and I’m pretty happy with it. The thing I like most is something that I did not expect: the email and text alerts. You can’t really read or reply to these messages, but it’s great to take a quick peek by flipping your wrist to then determine if the it’s worthy of bringing my phone out of my pocket and dealing with it. Payment notification from Verizon, ignore. Text from wife, address immediately.

I haven’t really tried the guided workouts, I don’t really go on runs, and I don’t really care about my step count. I like the workout tracker (essentially just a timer + heart monitor) and sleep tracking, and, as mentioned previously, I really like the email and text alerts. It’s still early with this one, but it seems like a win.

Kindle Voyage

The Kindle Voyage is my latest toy. I had a 1st generation Kindle Fire that was ironically lost in a fire. I like it for reading at night, but I didn’t use many of the tablet features (browser or apps) and the glare was not so good for daylight reading at times. So, I decided to go for a pure e-reader this time. I’ve read just one book so far, but the more I use it, the more I like it.

I decided to get the Voyage for the auto-brightness adjustment, and it works nicely. I also like the page turn buttons on the side but wouldn’t consider this to be any sort of killer feature. All-in-all, I’m happy with this. It’s definitely better for reading than my Kindle Fire was, but I can’t say how it compares to another pure reader like the Paperwhite.

Wagan Power Dome EX 400-Watt Jump Starter with Built-In Air Compressor

This is less techy, but it is no less awesome. I’m a stickler for tire pressure, but the condo that I’ve been living in does not have a nearby power source for me to connect my small air compressor. The gas station air is a pain since it’s usually not free, and I probably don’t have correct change. So, I wanted to find a wireless air compressor that I could keep in my car to use when I need it.

There were mixed reviews about this, but I decided to take a chance. I’m glad I did–I love it. Low pressure? I just pull this puppy out of the cargo area, and I’m back to normal in no time! It doesn’t fill up super fast (about 1-2 lbs every 30 sec), but it definitely gets the job done. Putting a few pounds of air into all four tires is easy work. There are gripes about the valve cord not being long enough, but just tip it on its side and it’s plenty.

It’s also got a jump starter. I haven’t had to use it, but it’s nice to know that I’ve got it. (I’ve been burned by jump starters in the past, so I’m keeping regular jumper cables around, too!) It has USB ports for charging devices, a radio, a flashlight, and both AC and DC power outlets. Plus it looks cool and seems to impress dads and grandpas. I’m happy with this thing just as a portable air compressor, but it does a lot more!

About these ads

Getting Started with Selenium in Python

I just spent a day doing some browser automation with Selenium in Python, and man-oh-man is it fun! I was surprised at how quickly I was able to get setup and productive, and I thought I’d put together a quick getting started guide to celebrate.

Installation

If you’re starting from scratch (no Python), then the first thing you’ll want to do is install Python. Head on over to python.org and grab a copy. If you install Python 2, you’ll also want to install pip. (Python 3 ships with pip, so it is not necessary to install it yourself.)

With Python and pip, installing Selenium is done with a single command:

pip install selenium

That’s it, now you’re ready to get to automatin’!

Hello World

Open your favorite text editor and create a new file. The first thing you’ll do is import the selenium.webdriver module. Then, you’ll instantiate a webdriver. And then you’ll automate whatever you want!

Here is a script that goes to google and types “hello world” into the box.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com")
driver.find_element_by_id("gbqfq").send_keys("hello world")
driver.close()

Development

I only have one day’s worth of knowledge as I’m writing this, but what I’ve found to work well is to use Chrome’s right-click > Inspect element function for each element that I need to find or interact with and type it into my Python script.

For example, if I wanted to automate entering data into a form, I’d inspect the element to find its id or other identifiable trait (name, css), then type it into my script.

Here’s how you might automate logging into a website:

<form>
    <input id="username" type="text"></input>
    <button id="login-submit" type="submit">Submit</button>
</form>
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("admin")
driver.find_element_by_id("login-submit").click()

And here’s how you might validate that the login was successful:

<div class="banner">
    <span>Welcome, admin</span>
</div>
assert "Welcome, admin" in driver.find_element_by_css_selector("div.banner span").text

Super easy, super fun! Want to learn more? Start here!

Output Parameters in Argument Constraints with Rhino Mocks… Again!

One of my favorite things about being a blog owner and operator is when I’m looking for something and find that I’ve already answered my own question. This just happened to me as I was trying to re-figure out how to use output parameters with argument constraints with Rhino Mocks.

I found an article on this very topic written by me (thanks, self!), but as I was reading I noticed that I left something important out. So here’s a quick, mini do-over!

Let’s say we need to stub function Bar as it’s defined in the following interface:

public interface IFoo
{
    bool Bar(out string outty);
}

To use an argument constraint with the output argument, I need to do two things. First, I need to use Arg<T>.Out. The second thing–the thing that I failed to mention in my previous post–is that I need to use the Dummy property to make it compile.

Here’s what an example might look like. I stubbed the Bar function to return true and assign the value fake value! to the output argument.

IFoo mockFoo = MockRepository.GenerateMock<IFoo>();
mockFoo(x => x.Bar(out Arg<string>.Out("fake value!").Dummy)).Return(true);

Not too shabby!

Edit Environment Variables in the Registry

I’m annoyed with the state of environment variables, more specifically the PATH variable. It used to be not entirely intuitive but relatively easy to edit. You’d right-click My Computer > Properties > Advanced > Environment Variables and be home free.

Recently, I needed to add a value to my PATH variable. In Windows 8.1, finding the advanced system properties is a little different, but I made it there without too much trouble. So, I selected the PATH variable, clicked the edit button, and was presented with a dialog box. It looked good, but I couldn’t type anything!

I believe I wasn’t able to type because my existing value exceeded the the character limit of 1024. I’m sure this limit has been there all along, but it was super annoying to deal with. I was able to get around the problem by using PowerShell. This worked fine for adding a new path to the environment variable, but I don’t think it would be so great for editing to remove an unneeded path or correct a mistake. But whatever, it worked, and I thought I was in the clear until today when I found that my added path had inexplicably been removed! Gah!

I headed back to Google for a better solution, and I think I found a winner. You can edit the values in the registry, which gives me everything I’m looking for. I can copy the entire existing value into a text editor, make whatever changes, and then copy it back into the registry and save. Oh, and then you have to reboot. (Ugh.) This all seems WAY harder than it should be, but it does work, and I found it to be less annoying than the alternatives I could find.

Here are the registry keys:

  • User – [HKEY_CURRENT_USER\Environment]
  • System – [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]

 

nullybool == true

It’s always been a pet peeve of mine to see conditions where a boolean variable is compared to a boolean value.

if (someBoolean == true) // ew!
{
    ...
}
if (someBoolean) // omg, better!
{
    ...
}

It bothers me because it’s redundant. You already have a true or false, do you really need to compare it to true or false to know if it’s true or false?

I picked up this little bugbear back in the VB6 world. As I moved into the .Net realm, I was introduced to a new spin on booleans: Nullable<bool>. At it’s core, it’s still a boolean though, right? So my peeve lived on.

if (nullybool.HasValue && nullybool.Value == true) // blech!
{
    ...
}
if (nullybool.HasValue && nullybool.Value) // omg, yes!
{
    ...
}
if (nullybool.GetValueOrDefault()) // OMG, EVEN BETTER!
{
    ...
}

But alas, I have just learned that comparing nullable booleans to boolean values is actually quite nice. It saves you a lot of .HasValue-ing. I am officially ending my lifelong campaign against removing “== true” and “== false” from any and all code I come across; I’m making exceptions for nully-bools.

if (nullybool.GetValueOrDefault()) // gettin' paid per keystroke?
{
    ...
}
if (nullybool == true) // noice!
{
    ...
}

Now, all that said, there is still a place for HasValue. Sometimes you need to know if the value has actually been set, but I won’t want to see any more nullybool.HasValue && nullybool.Value-business. I’m done with that! (And a new peeve is born…!)

Async/Await Crash Course

I’ve known about Microsoft’s asynchronous programming since hearing the announcement at PDC 2010. I’ve been aware of it, and I’ve dabbled here and there, but I haven’t really gotten into using it as part of my standard toolkit for a variety of reasons. First, it was that the product I was focused on could only use .Net Framework 3.5. Then I was on another product that used .Net 4.0, but we didn’t have much need for performance tuning.

But now I’m in a world where I have access to it AND a need for it–hooray! And so, with that, I present to you my crash course on asynchronous programming in c# using the async and await keywords.

Let me set up a scenario for my examples. Imagine a function that matches records between two systems. Data must be retrieved from each of the two systems before the matching can be performed.

Here’s what a fully-synchronous version of the problem might look like. Note that data is being loaded one-type and one-source at a time, followed by matching for that type.

public void DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    Match(fooFromA, fooFromB);
    Console.WriteLine("{0} foo matched!", fooFromB.Count(x => x.IsMatch));
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    Match(barFromA, barFromB);
    Console.WriteLine("{0} bar matched!", barFromB.Count(x => x.IsMatch));
}

public IEnumerable<Foo> GetFooFromA()
{
    var data = new Foo[] { new Foo(1), new Foo(2), new Foo(3) };
    return data;
}

public IEnumerable<Foo> GetFooFromB()
{
    var data = new Foo[] { new Foo(2), new Foo(3), new Foo(4) };
    return data;
}

public IEnumerable<Bar> GetBarFromA()
{
    var data = new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") };
    return data;
}

public IEnumerable<Bar> GetBarFromB()
{
    var data = new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") };
    return data;
}

public void Match(IEnumerable<Foo> fooFromA, IEnumerable<Foo> fooFromB)
{
    foreach (var foo in fooFromB)
    {
        if (fooFromA.Any(x => x.Id == foo.Id))
        {
            foo.IsMatch = true;
        }
    }
}

public void Match(IEnumerable<Bar> barFromA, IEnumerable<Bar> barFromB)
{
    foreach (var bar in barFromB)
    {
        if (barFromA.Any(x => x.Id == bar.Id))
        {
            bar.IsMatch = true;
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Foo(int id)
    {
        Id = id;
    }
}

public class Bar
{
    public string Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Bar(string id)
    {
        Id = id;
    }
}

The first thing we can do to optimize this code with async/await is to make the data retrieval methods asynchronous. This is done in just three steps:

  1. Change the return type to Task<T>
  2. Add async to the function declaration
  3. Use await to return the value

If the logic in your function blocks the CPU, like mine which just has a hard-coded result, you can make it async-friendly by executing it via Task.Run.

Here’s what the new, async version of my data-getters.

public async Task<IEnumerable<Foo>> GetFooFromA()
{
    return await Task.Run(() => new Foo[] { new Foo(1), new Foo(2), new Foo(3) });
}

public async Task<IEnumerable<Foo>> GetFooFromB()
{
    return await Task.Run(() => new Foo[] { new Foo(2), new Foo(3), new Foo(4) });
}

public async Task<IEnumerable<Bar>> GetBarFromA()
{
    return await Task.Run(() => new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") });
}

public async Task<IEnumerable<Bar>> GetBarFromB()
{
    return await Task.Run(() => new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") });
}

Okay, so that takes care of half the problem, but now we need to make sure the match functions are executed once the data they need is available. One way to do this would be to use the await keyword, like this:

var fooFromA = GetFooFromA();
var fooFromB = GetFooFromB();
Match(await fooFromA, await fooFromB);

But wait! We don’t want to do that because we’ll be preventing the data retrieval and matching of our Bar records while we process our Foo records. Instead, we can use Task.WhenAll to tell our match function to process once the data it needs becomes available.

var fooFromA = GetFooFromA();
var fooFromB = GetFooFromB();
Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
{
    Match(fooFromA.Result, fooFromB.Result);
    Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
});

Note that in my ContinueWith block, I’m using the Result property of the asynchronous tasks. It’s safe to use the property since WhenAll makes sure they’re finished before getting there. If we wanted to be extra safe, we could check the status of the Task (t) that’s passed into our anonymous function–probably a good idea to verify that nothing went wrong while retrieving the data.

You’ll also notice that I moved the Console.WriteLine into the ContinueWith block. This needs to happen for two reasons. First, the code’s running asynchronously so the matching wouldn’t have occurred by the time the statement was run. Second, the collection might not be accessible if the task hadn’t completed; you could use the await keyword, but even then you could not guarantee that matching had finished.

So now we’re in business. The data retrievals all occur asynchronously, and matching begins as soon as the requisite data is received for each of our respective data types. We haven’t done anything with our DoMatching function, though. If we want to make it awaitable, we just need to keep track of our work tasks and make use of WhenAll again. Notice that we’ve added the async keyword to our method signature and that void has become Task.

public async Task DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    var matchFoos = Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
    {
        Match(fooFromA.Result, fooFromB.Result);
        Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
    });
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    var matchBars = Task.WhenAll(barFromA, barFromB).ContinueWith(t => 
    {
        Match(barFromA.Result, barFromB.Result);
        Console.WriteLine("{0} bar matched!", barFromB.Result.Count(x => x.IsMatch));
    });
    
    await Task.WhenAll(matchFoos, matchBars);
}

Complete example:

void Main()
{
    DoMatching().Wait();
}

public async Task DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    var matchFoos = Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
    {
        Match(fooFromA.Result, fooFromB.Result);
        Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
    });
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    var matchBars = Task.WhenAll(barFromA, barFromB).ContinueWith(t => 
    {
        Match(barFromA.Result, barFromB.Result);
        Console.WriteLine("{0} bar matched!", barFromB.Result.Count(x => x.IsMatch));
    });
    
    await Task.WhenAll(matchFoos, matchBars);
}

public async Task<IEnumerable<Foo>> GetFooFromA()
{
    return await Task.Run(() => new Foo[] { new Foo(1), new Foo(2), new Foo(3) });
}

public async Task<IEnumerable<Foo>> GetFooFromB()
{
    return await Task.Run(() => new Foo[] { new Foo(2), new Foo(3), new Foo(4) });
}

public async Task<IEnumerable<Bar>> GetBarFromA()
{
    return await Task.Run(() => new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") });
}

public async Task<IEnumerable<Bar>> GetBarFromB()
{
    return await Task.Run(() => new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") });
}

public void Match(IEnumerable<Foo> fooFromA, IEnumerable<Foo> fooFromB)
{
    foreach (var foo in fooFromB)
    {
        if (fooFromA.Any(x => x.Id == foo.Id))
        {
            foo.IsMatch = true;
        }
    }
}

public void Match(IEnumerable<Bar> barFromA, IEnumerable<Bar> barFromB)
{
    foreach (var bar in barFromB)
    {
        if (barFromA.Any(x => x.Id == bar.Id))
        {
            bar.IsMatch = true;
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Foo(int id)
    {
        Id = id;
    }
}

public class Bar
{
    public string Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Bar(string id)
    {
        Id = id;
    }
}

Several Patterns for Refactoring Static Classes for Testability

Static classes and methods can be tricky business for unit tests, and I’ve had to do a lot of refactoring them lately to get some tests going. Here are a few different ways to make your static classes test-friendly.

For the examples below, assume we need to refactor the following class to make it more testable:

public static class Foo
{
    public static void Bar()
    {
        // do something
    }
}

Convert to Instance Class

A simple and straightforward solution is to convert your static class to an instance class. If you need to prevent multiple instances from existing, you can implement the singleton pattern in your class. It’s easy to do this, but it can be risky or tedious to implement across a solution depending on how much your static class is being used. For example, if your class is being accessed hundreds or thousands of times across many different projects, you may not want to do this because you’ll have to update each and every caller.

public class Foo : IFoo
{
    private static IFoo Instance { get; set; }
    
    static Foo()
    {
        Instance = new Foo();
    }
    
    private Foo()
    {
    }
    
    public void Bar()
    {
        // do something
    }
}

Keep Static Class, Extract Implementation #1

If you want or need to keep your static classes/methods as static without having to change every caller, you can extract the implementation of your static class to a new instance class and adjust the static class to use that. The implementation class uses the singleton pattern to expose a single static instance that will be used by the static class.

public static class Foo
{
    public static void Bar()
    {
        FooImplementation.Instance.Bar();
    }
}

internal class FooImplementation : IFoo
{
    public static IFoo Instance { get; private set; }
    
    static FooImplementation()
    {
        Instance = new FooImplementation();
    }
    
    private FooImplementation()
    {
    }
    
    public void Bar()
    {
        // do something
    }
}

public interface IFoo
{
    void Bar();
}

This works great, but it does require unit test authors to have knowledge of the new implementation class. This strikes me as slightly non-intuitive for developers since you go to class B to mock the behavior of class A. And that brings us to our next option…

Keep Static Class, Extract Implementation #2

Another option is to tweak the above strategy slightly so that the static property is added to the static class instead of on the implementation instance class. The nice thing about this approach is that you don’t need to have any awareness of the default implementation when providing the static class with an alternate implementation.

public static class Foo
{
    private static IFoo Implementation { get; set; }
    
    static Foo()
    {
        Implementation = new FooImplementation();
    }
    
    public static void Bar()
    {
        Implementation.Bar();
    }
}

internal class FooImplementation : IFoo
{
    public void Bar()
    {
        // do something
    }
}

public interface IFoo
{
    void Bar();
}

Create a Wrapper

Another option is to create a wrapper. Much like the first option presented, this approach has the downside of needing to update all callers to use the wrapper. However, if you are unable to modify the contents of your static class, this may be your best bet.

public static class Foo
{
    public staic void Bar()
    {
        // do something
    }
}

public class FooWrapper : IFoo
{
    private static IFoo Instance { get; set; }
    
    static FooWrapper()
    {
        Instance = new FooWrapper();
    }
    
    private FooWrapper()
    {
    }
    
    public void Bar()
    {
        Foo.Bar();
    }
}

interface IFoo
{
    void Bar();
}