Author: Dave Fancher

Dave Fancher is a Software Engineer at Performance Assessment Network in Carmel, Indiana, a Microsoft MVP for Visual F#, and author of The Book of F# from No Starch Press. He has been building software with the .NET Framework since version 1.1. Dave is active within the Indiana software development community as a member of IndySA, a speaker at user groups throughout the state, and a two-time contributor to Indy GiveCamp. When not writing code he enjoys spending time with his family, watching movies, photography, and gaming on on his Xbox One.

C# 6 Verbatim Interpolated String Literals

It’s no secret that string interpolation is one of my favorite C# 6 language features because of how well it cleans up that messy composite formatting syntax. A few days ago I was working on some code that contained a verbatim string that included a few of the classic tokens and I wondered if string interpolation would work with verbatim strings as well.

After a quick glance over the MSDN documentation for string interpolation revealed nothing I just decided to give it a shot by adding a dollar sign ($) ahead of the existing at (@) sign and filled the holes with the appropriate expressions. Much to my delight this worked beautifully as shown in the snippet below!

var name = "Dave";
var age = 36;

var sentence = $@"Hello!
My name is {name}.
I'm {age} years old.";

Console.WriteLine(sentence);

I later discovered that even though this feature doesn’t seem to be listed in the MSDN documentation (at least anywhere I could find it) that it is explicitly called out in the C# 6 draft specification so hopefully it’ll find its way to the rest of the documentation at some point.

Functional C#: Debugging Method Chains

One of the most common questions I get in regard to the Map and Tee extension methods I presented in my recent Pluralsight course is “That’s great…but how do I debug these chains?” I get it – debugging a lengthy method chain can seem like a monumental task upon first glance but I assure you, it really isn’t all that difficult or even much different from what you’re accustomed to with more traditional, imperative C# code.

I’ve found that when debugging method chains I typically already have a good idea where the problem is. Spoiler: It’s in the code I wrote. That means that I can almost always automatically rule out any chained in framework or other third-party library methods as the source of the problem. It also means that setting a breakpoint within a chained lambda expression or method is often an adequate first step in isolating the problem. This is especially useful when working with pure, deterministic methods because you can then write a test case around the method in question and already have the breakpoint right where you need it.

In some situations though, you want to follow computation through the chain but constantly stepping through the extension methods can be both tedious and distracting, especially when the chained method is outside of your control and won’t be stepped into anyway. Fortunately this is easily resolved with a single attribute.

The System.Diagnostics.DebuggerNonUserCodeAttribute class is intended specifically for this purpose. As MSDN states, this attribute instructs the debugger to step through rather than into the decorated type or member. You can either apply this attribute to individual methods or to the extension class to prevent the methods from disrupting your debugging experience. For my projects I opted to simply suppress all of the extension methods by decorating the class like this:

[DebuggerNonUserCodeAttribute]
public static class FunctionalExtensions
{
    public static TResult Map<TSource, TResult>(
        this TSource @this,
        Func<TSource, TResult> map) => map(@this);

    // -- Snipped --
}

With the attribute applied, you can simply set a breakpoint on the chain and step into it as you normally would. Then, instead of having to walk through each of the extension methods you’ll simply be taken right into the chained methods or lambda expressions.

Enjoy!

Functional C#: Chaining Async Methods

The response to my new Functional Programming with C# course on Pluralsight has been far better than I ever imagined it would be while I was writing it. Thanks, everyone for your support!

One viewer, John Hoerr, asked an interesting question about how to include async methods within a chain. I have to be honest that I never really thought about it but I can definitely see how it would be useful.

In his hypothetical example John provided the following three async methods:

public async Task<int> F(int x) => await Task.FromResult(x + 1);
public async Task<int> G(int x) => await Task.FromResult(x * 2);
public async Task<int> H(int x) => await Task.FromResult(x + 3);

He wanted to chain these three methods together such that the asynchronous result from one task would be passed as input to the next method. Essentially he wanted the asynchronous version of this:

1
    .Map(H)
    .Map(G)
    .Map(F);

These methods can’t be chained together using the Map method I defined in the course because each of them want an int value rather than Task<int>. One thing John considered was using the ContinueWith method.

1
    .Map(H)
    .ContinueWith(t => G(t.Result))
    .ContinueWith(t => F(t.Result.Result));

This approach does play well with method chaining because each method returns a task that exposes the ContinueWith method but it requires working with the tasks directly to get the result and hand it off to the next method. Also, as we chain more tasks together we have to drill through the results to get to the value we really care about. Instead what we’re looking for is a more generalized approach that can be used across methods and at an arbitrary level within the chain.

After some more discussion we arrived at the following solution:

public static async Task<TResult> MapAsync<TSource, TResult>(
    this Task<TSource> @this,
    Func<TSource, Task<TResult>> fn) => await fn(await @this);

Rather than working with TSource and TResult directly like the Map method does, MapAsync operates against Task<TResult>. This approach allows us to define the method as async, accept the task returned from one async method, and await the call to the delegate. The method name also gives anyone reading the code a good visual indication that it is intended to be used with asynchronous methods.

With MapAsync now defined we can easily include async methods in a chain like this:

await 1
    .Map(H)
    .MapAsync(G)
    .MapAsync(F);

Here we begin with the synchronous Map call because at this point we have an integer rather than a task. The call to H returns a Task so from there we chain in G and F respectively using the new MapAsync method. Because we’re awaiting the whole chain, it’s all wrapped up in a nice continuation automatically for us.

This version of the MapAsync method definitely covers the original question but there are two other permutations that could also be useful.

public static async Task<TResult> MapAsync<TSource, TResult>(
    this TSource @this,
    Func<TSource, Task<TResult>> fn) => await fn(@this);

public static async Task<TResult> MapAsync<TSource, TResult>(
    this Task<TSource> @this,
    Func<TSource, TResult> fn) => fn(await @this);

Both of these overloads awaits results at different points depending on the input or output but they each operate against a Task at some point.

So there you have it, a relatively painless way to include arbitrary async methods within a method chain.

Thanks, John, for your question and your contributions to this post!

Have fun!

Functional Programming with C# is Live!

After a few months in the works I’m excited to announce that my second Pluralsight course, Functional Programming with C#, is now live! In this course you can learn how to take advantage of several functional programming techniques including immutability, higher-order functions, and functional pipelining within your existing C# projects.

If you’re a .NET developer interested in functional programming but not yet ready to jump to F# or just want to leverage functional techniques in your existing projects please check it out!

Crashing Visual Studio 2015 with Explicit Interface Implementations

In F#, all interface implementations are always explicit meaning that the interface methods will only be accessible when treating the implementing type as that interface. This makes sense in F# because it removes all ambiguity around what the method applies to. Explicit implementations also force us into coding to the interface because other miscellaneous members of the implementing type aren’t exposed through the interface definition. For these reasons I’ve been hooked on explicit interface implementation and even use it almost exclusively with great success in my C# applications.

Imagine my surprise then when Visual Studio 2015 crashed when I tried to rename an explicitly implemented interface method! The first time it happened I figured it was probably just Visual Studio misbehaving but when I reopened the solution and tried again the same thing happened! Clearly there was something more to this.

RefactorCrash

Renaming an explicitly implemented interface method causes Visual Studio 2015 to crash.

Hoping that I’d perhaps stumbled upon something that was fixed and included in Update 1, I upgraded Visual Studio and tried again. The crash still occurred.

To narrow down the issue I created a brand new solution with a console application. Within the new project I defined a simple interface with a single method and explicitly implemented it in a class. At this point I attempted to rename the method and it worked as expected. I then tried renaming the interface method directly on the interface and that also worked as expected. Then I figured that it must have something to do with how the interface was being used so I created an instance of the class, converted it to the interface, and tried the rename again and it was successful. Finally, I added a line to invoke the interface method and tried the rename one more time. Oddly, it again worked as expected.

On a whim I decided to move the interface and implementation into a separate project. After adding the project reference and doing a test build I again tried to rename the method and sure enough, Visual Studio crashed. I’ve since played with a few different combinations and have been able to successfully recreate the crash as long as the interface is defined in a separate assembly and I tried renaming the method via the explicit implementation.

In summary, it appears that in order to recreate this crash the following conditions must be met:

  • Interface must be explicitly implemented
  • Interface must be defined in a separate assembly than where it’s used
  • Rename must be attempted against the explicit implementation
  • Interface method must be invoked – simply creating an instance won’t cause the crash.

I’ve submitted the issue to Microsoft on Connect but this seems like such an edge case I’d be surprised to see a fix anytime soon. In the mean time, if this is something you encounter you can safely rename the method on the interface itself or at the call site; neither of those seemed to be an issue.

If you’d like to mess around with this issue on your own, I’ve shared my sample project on GitHub.

Upcoming .NET Course at Eleven Fifty Academy

Well, I’ve really done it this time – I agreed to lead the Intro & Intermediate Microsoft .NET course at Eleven Fifty Academy here in Carmel, Indiana. I know that the target audience for this course isn’t likely reading my blog but if you know someone who would be interested please pass this along.

In this seven day bootcamp style course we’ll cover the following topics:

  • Walkthrough of the Visual Studio IDE
  • Declaring Constants and Variables
  • C# control statements, loops, and enumerators
  • String manipulation
  • Working with Arrays, Dictionaries, and Hashtables
  • Function Declarations
  • Anonymous functions
  • Class definitions, Structures, Enumerations, Generics
  • ASP .NET MVC 5 Overview
  • ASP .NET MVC Lifecycle
  • Controllers and Routing
  • Entity Framework 6 Code First and Database First
  • Validating form input
  • Building and Consuming RESTful services
  • Interacting with third-party API’s
  • Debugging

The course runs from October 10 through October 16 and costs $2,500 but thanks to the generosity of our sponsors T2 Systems, Do It Best Corp, and BitWise Solutions, the discount code ‘OpenHouse50’ is available for a 50% discount!

Reshaping Data with R

I was scrolling through my Facebook feed yesterday afternoon and one post stood out among the endless stream of memes. A friend had a data transformation question! She said:

Data handling question! I fairly frequently receive “tall” client data that needs to be flattened to be functional. So for example, Jane Doe may have twelve rows of data, each for a different month of performance, and I need to compress this so that her monthly performance displays on one row only, with columns for each month. Anyone know of a relatively painless way to do this quickly? I’ve been sending files like this to our data guy to flatten, but I’d love to be able to do it myself.

I immediately thought: “Hey! This sounds like a job for R!” Unfortunately, my R knowledge is limited to knowing that it’s a statistical programming language so in the interests of both helping out my friend and getting a little experience with something I’ve wanted to play around with, I set out to see how easy – or difficult – this task would be in R. It turned out to be quite simple.

Naturally I didn’t even have the R environment installed on my laptop so I obtained the installer from the R project site. Once it installed, I was off.

I started by creating a CSV that would simulate the scenario she described. My highly contrived data looked like this:

Name Month Value
Jane Doe January 10
Jane Doe February 11
Jane Doe March 5
Jane Doe April 8
Jane Doe May 10
Jane Doe June 15
Jane Doe July 12
Jane Doe August 8
Jane Doe September 11
Jane Doe October 7
Jane Doe November 9
Jane Doe December 13
John Doe January 5
John Doe February 3
John Doe March 8
John Doe April 7
John Doe May 6
John Doe June 5
John Doe July 5
John Doe August 8
John Doe September 4
John Doe October 2
John Doe November 5
John Doe December 9

With some source data ready it was time to move onto reading the data. It turns out that R has some nice capabilities for reading CSV files so I loaded it as follows:

df <- read.csv(file="C:\\Dev\\Data.csv", header = TRUE)

Here we’re reading the CSV and binding the resulting data frame to df.

Next, I needed to transform the data. After a bit of research I found there are a few ways to do this but using the reshape2 package seemed like the easiest approach. I installed the package and referenced it in my script.

library(reshape2)

Reshape2 is designed to transform data between wide and tall formats. Its functionality is built around two complementary functions; melt and cast. The melt function handles transforming wide data to a tall format whereas cast transforms tall data into a wide format. Given that my friend was trying to convert from tall to wide, cast was clearly the one I needed.

The cast function comes in two flavors: dcast and acast which result in either a new data frame or a vector/matrix/array respectively. To (hopefully) keep things simple I opted for the data frame approach and used dcast for this transformation.

To transform the data I simply needed to apply the dcast function to the CSV data. That is done like this:

pivot = dcast(df, Name~Month)

Here, the first argument df is our CSV data. The second argument specifies the column names that will serve as the axis for the transformation.

Finally I needed to persist the data. Just as with loading, R can easily write a CSV file.

write.csv(pivot, file="C:\\Dev\\Pivot.csv")

Finally, I executed the script and here’s the result:

Name April August December February January July June March May November October September
1 Jane Doe 8 8 13 11 10 12 15 5 10 9 7 11
2 John Doe 7 8 9 3 5 5 5 8 6 5 2 4


Although the data was transformed correctly it wasn’t quite what I expected to see. There are two problems here:

  1. The row numbers are included
  2. The months are alphabetized

It turns out that both of these problems are easy to solve. Let’s first handle eliminating the row numbers.

To exclude the row numbers from the resulting CSV we simply need to set the optional row.names parameter to FALSE in the write.csv function call.

write.csv(pivot, file="C:\\Dev\\Pivot.csv", row.names=FALSE)

Fixing the column order isn’t quite as simple but it’s really not bad either; we simply need to manually specify the column order by treating the frame as a vector and using the concatenation function to specify the new order.

In the interest of space I used the index approach but it’s also acceptable to use the column names instead.

pivot = dcast(df, Name~Month)[,c(1,6,5,9,2,10,8,7,3,13,12,11,4)]

Putting this all together, the final script now looks like this:

library(reshape2)

df <- read.csv(file="C:\\Dev\\Data.csv", header = TRUE)

pivot = dcast(df, Name~Month)[,c(1,6,5,9,2,10,8,7,3,13,12,11,4)]

write.csv(pivot, file="C:\\Dev\\Pivot.csv", row.names=FALSE)

Run this version and you’ll get the following, cleaned up result:

Name January February March April May June July August September October November December
Jane Doe 10 11 5 8 10 15 12 8 11 7 9 13
John Doe 5 3 8 7 6 5 5 8 4 2 5 9

So I ask this of my friends and readers that are more versed in R than I. Is this the preferred way to handle such transformations? If not, how would you approach it?