Tag Archives: .net

Simple .DistinctBy Extension

LINQ’s Distinct extension has largely been a disappointment to me. Sure, it’s nice when I’m working with a collection of integers, but more often than not, I’m working with a collection of objects and don’t have an IEqualityComparer<TSource> available to me. I know I could just create one, but I just want to use a lambda like just about everything else I do with LINQ!

To the internet!, right? I learned I could use the following trick to accomplish what I want:

collection
  .GroupBy(x => x.key)
  .Select(x => x.First());

Works like a charm, but I got tired of dot-GroupBy-dot-Select-ing and adding a comment about what I was doing for future maintainers, and I think it’s a lot better to just chuck it into an extension method.

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector
{
    return
        source
            ?.GroupBy(keySelector)
            .Select(grp => grp.First());
}

Ahh, nice! Alternatively, could score this functionality by adding MoreLINQ to your project. On a neat side-note, you can also cherry-pick which MoreLINQ functionality you want by installing individual packages.

Advertisements

The Way of the Ninject

In recent months, I’ve come to be a big fan of Ninject. I’ve used Microsoft’s Unity Container and Object Builder in the past, but most of what I’d done previously just involved exposing dependencies as properties with lazily-loaded default implementations. I really dig Ninject because it’s so lightweight and easy to use, and it integrates really well with mocking frameworks like Rhino Mocks and Moq.

Getting started with Ninject is really easy and accomplished in just a few steps:

  1. Install the NuGet package
    Install-Package Ninject
  2. Create a module
  3. Create a kernel
  4. Get objects from the kernel

Let’s look at an example. Assume we have the following interfaces and classes.

public interface IFoo {
    void Run();
}

public class Foo : IFoo {
    private readonly IBar _bar;

    public Foo(IBar bar) {
        _bar = bar;
    }

    public void Run() {
        _bar.Print();
    }
}

public interface IBar {
    void Print();
}

public class Bar : IBar {
    public void Print() {
        Console.WriteLine("Yay!");
    }
}

We can create a NinjectModule to create an instance of IFoo like this.

public class FooModule : NinjectModule {
    public override void Load() {
        Bind<IFoo>().To<Foo>();
        Bind<IBar>().To<Bar>();
    }
}

Now, we need to tell our Ninject kernel to use our new module.

IKernel kernel = new StandardKernel(
    new FooModule());

And, finally, we use the kernel to request the objects we need. Note that Ninject does the work of figuring out the default implementation of IFoo (Foo) has a single constructor that accepts a dependency, IBar, and that the default implementation of the dependency is Bar.

class Program {
    static void Main(string[] args) {
        IKernel kernel = new StandardKernel(
            new FooModule());
        IFoo foo = kernel.Get<IFoo>();
        foo.Run();
        Console.ReadLine();
    }
}

Output:

Yay!

String Formatting with Regex

My latest favorite trick with regular expressions is to shortcut string formatting. We’ve all written some code like this:

if (/* string is not formatted a certain way */)
{
    /* make it formatted that way */
}

Now, there’s nothing wrong with that code, but for simple examples you could do it all in one step with a regular expression!

Here are a few examples:

// remove "www." from a domain if one exists
// domain.com     -> domain.com
// www.domain.com -> domain.com
Regex.Replace(input, @"^(?:www.)?(.+)$", "$1");

// format phone number
// 1234567890       -> 123-456-7890
// (123) 456-7890   -> 123-456-7890
// (123) 456 - 7890 -> 123-456-7890
Regex.Replace(input, @"^\(?(\d{3})\)?\s*(\d{3})\s*-?\s*(\d{4})$", "$1-$2-$3");

Yay, regular expressions!

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!

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();
}

Enum.HasFlag

In not-so-new news, I just found out about .NET 4’s Enum.HasFlag method. This nice little method makes life with flags a little bit cleaner since you can use it instead of performing a bitwise AND and compare.

[Flags]
enum Options
{
	None = 0,
	A = 1,
	B = 2,
	C = 4
}

void Main()
{
	var options = Options.A | Options.C;
	
	// old (bitwise AND and compare)
	Console.WriteLine("A:{0}", (options & Options.A) == Options.A);
	Console.WriteLine("B:{0}", (options & Options.B) == Options.B);
	Console.WriteLine("C:{0}", (options & Options.C) == Options.C);
	
	// new (HasFlag method)
	Console.WriteLine("A:{0}", options.HasFlag(Options.A));
	Console.WriteLine("B:{0}", options.HasFlag(Options.B));
	Console.WriteLine("C:{0}", options.HasFlag(Options.C));
}

/* Output:
A:True
B:False
C:True
A:True
B:False
C:True
 */

Database SpecFlow Scenarios and TransactionScope

My team has been using SpecFlow to verify that our data access components are working correctly. In an effort to write repeatable tests that won’t pollute the database, we’ve decided to wrap each scenario in a transaction.

Creating and rolling back the transactions is very simple to do with SpecFlow’s BeforeScenario & AfterScenario hooks.

using System.Transactions;

[Binding]
public class TransactionHooks
{
    private TransactionScope _transactionScope;

    [BeforeScenario]
    public void BeforeScenario()
    {
        _transactionScope = new TransactionScope();
    }

    [AfterScenario]
    public void AfterScenario()
    {
        _transactionScope.Dispose();
    }
}

By including these hooks, you’re placing your test scenarios in the loving embrace of a transaction scope. The act of instantiating the TransactionScope will update the ambient transaction that will be used by all subsequent code unless you explicitly tell it to do otherwise.

If you’re testing code that uses TransactionScope itself, using TransactionScopeOption.Required will allow the code to use the ambient transaction if one exists. Note that this is the default value, so it’s what you’re using if you’re not explicitly specifying an option. However, the other TransactionScopeOption values will cause code to execute outside your test scenario’s ambient transaction by either creating a new/different transaction (RequiredNew) or executing outside the transaction (Suppress).

Paste as Plain Text in Windows Store App

I was working on a Windows Store app that used a RichEditBox for text entry. Everything worked great until I pasted some formatted text into it. The dumb thing kept all the formatting! Okay, I guess that’s probably good since it would be pretty annoying if you wanted the formatting, but I didn’t.

Good news, though: it’s easy to remove that formatting and paste as plain text. So easy, in fact, that you can do it in a single line. RichEditBox has an ITextDocument property (Document) that has an ITextRange property (Selection). And guess what ITextRange has? A Paste method! However, this is where it got a little tricky for me because Paste takes an integer parameter, and it took me some googling to find a list of valid values. (Sorry, text-pasting enthusiasts, but you can’t use DataFormats in a Windows Store app.) In the end, I was able to find what I needed here.

Once you’ve got the code, you just hook up a handler to the RichEditBox’s Paste event and–voila!–pasting as plain text.

XAML:

<RichEditBox Paste="OnPaste" />

Code-behind:

private void OnPaste(object sender, TextControlPasteEventArgs e)
{
    var editBox = sender as RichEditBox;
    if (editBox.Document.CanPaste())
    {
        editBox.Document.Selection.Paste(1);
        e.Handled = true;
    }
}