Visual Studio

CTRL + BACKSPACE

I’ve been working in Visual Studio for years – long enough that many of the most useful keyboard shortcuts are now permanently embedded in my finger muscle memory. Sure, there are plenty of shortcuts I need to look up from time to time but I usually think I have a pretty good handle on them. Every once in a while though, I do something silly and Visual Studio either rewards or punishes me in an unexpected way. Today was one of those days.

For whatever reason, I was holding the ctrl key when I hit backspace in VS2013 and suddenly the entire property name just disappeared! I tried it again and the preceding dot disappeared. One more time and the object name disappeared.

I have no idea how it’s taken me this long to stumble upon this shortcut but I’m glad I did! You can see the behavior in the animation below.

VisualStudioQuickBackspace

Advertisement

Receiving Webhooks With IIS Express

One of the projects I’m currently working on is using a service that reports various events back to our system via webhooks. Since the features I’m working on aren’t ready for deployment yet I was looking for a decent way to test the integration in my development environment to ensure that I’m not only receiving the correct data but also that I’m handling it properly.

The service’s documentation recommended pointing the webhooks to another service such as RequestBin to inspect the contents. I did mess around with that approach for a bit and although I was certainly able to see the requests in the RequestBin log and push them on to the application with fiddler, it really didn’t seem like an adequate solution and I was tired so I went to bed.

It turns out that sleeping on it was exactly what I needed. Sometime overnight I subconsciously worked out a better solution; I could open up IIS Express to handle remote connections and configure NAT on my router to forward requests for that port directly to the IIS Express instance. It turns out that getting all this working was actually quite simple.

Allowing Remote Connections

Allowing remote connections to IIS Express requires a little work but it’s pretty straight-forward and is outlined in this stackoverflow post. In short we need to:

  1. Create an additional IP binding for the IIS Express site to allow traffic from all hosts.
  2. Allow connections to the port from anyone
  3. Create a firewall rule to allow traffic to the port on the development machine

Creating an IIS Express Binding

IIS Express sites are managed per-user. To create the IIS Express binding we simply need to create a new entry for the site in the configuration file located at %userprofile%\documents\iisexpress\config\applicationhost.config. In the file locate the site then duplicate the binding, changing the allowed host to *. For example, if the current binding is:

I’ve used port 99999 in these examples for demonstration purposes only. You’ll want to use the port listed in your configuration file.

<binding protocol="http" bindingInformation="*:99999:localhost" />

You’d create a copy and change localhost to * such that it reads like this:

<binding protocol="http" bindingInformation="*:99999:*" />

It’s very important that you leave the original binding in place. Yes, it is redundant to have a binding for all hosts and another for only localhost but Visual Studio uses the localhost binding to initialize IIS Express. If that binding isn’t present Visual Studio will create a duplicate site entry and you’ll likely start seeing errors such as the one pictured below.

URL Binding Failure

URL Binding Failure

Setting Security on the Port

Once you’ve created the IIS Express binding you need to allow connections to the port. This is done by executing target=”_blank”>netsh to add a URL reservation for the new binding. In this case we’ll be using netsh http add urlacl to register the address we bound to the IIS Express site and granting permission to everyone.

netsh http add urlacl url=http://*:99999/ user=everyone

Note that “everyone” refers to the Everyone group in Windows. If you’re using a non-English version you’ll need to change that to the localized name for your language.

Creating a Firewall Rule

The final step is allowing traffic to that port through the local firewall. Accomplishing this varies according to which firewall solution you’re using. For Windows firewall you can control this through the control panel or by executing the following netsh command which changes some advanced firewall configuration settings.

netsh advfirewall firewall add rule name=”IISExpressWeb” dir=in protocol=tcp localport=99999 profile=private remoteip=any action=allow

Configuring NAT

Configuring NAT is not something I can really help with in this article because each environment will have its own instructions and restrictions. For me and my home office network it was easy because I simply had to add a custom application that referenced the configured port and host machine in my router’s firewall configuration.

Alternatively, I could have configured the IP Passthrough to route traffic to the development machine but I deemed this to be too much exposure to the outside world and left it with NAT.

Accepting Webhooks

Once I’d configured everything on my network to accept the webhook traffic I went to the external application’s dashboard and registered my computer as a webhook recipient using the WLAN IP address I obtained from my router’s status page and the port I bound to IIS Express for the application. I then set a breakpoint in the webhook processing logic, ran the application, made a change in the remote system to initiate sending an event, then watched in amazement as my breakpoint was hit and the watch window showed data received from the remote service.

Mission accomplished.

C# 6.0 – String Interpolation

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

I really debated about whether I should write about C#’s upcoming string interpolation feature yet. On one hand it’s an interesting feature that I’m looking forward to. On the other hand, it has already been announced that the feature is going to change from its implementation in the current preview. With that in mind I decided that it’s interesting enough to go ahead and write about it using the current syntax but highlight how it will change, much like how it has been done in the feature description document.

When I first heard that string interpolation was coming to C# I immediately experienced flashbacks to the very early days of my career when I was working with some Perl scripts. I really hated working with the language but something that always stuck with me and I missed when jumping to other languages was its string interpolation feature.

At a glance, Perl’s string interpolation feature let us embed variable names inside string literals and the compiler would handle the details of replacing the variable name with the value. My Perl is rusty to say the least but a simple example would essentially look like this:

my $name = "Dave";
print "My name is $name";

Upon execution, the script would write out the following text:

My name is Dave

Side note: I think this is the first time Perl has appeared on this blog. Hopefully it’ll be the last!

Perl’s implementation is more advanced than I’ve shown in this example but it clearly shows the usefulness of the feature. When .NET finally came along and I learned about String.Format I had hopes that it could evolve into something like the Perl feature described above. String.Format is certainly a useful method but it can quickly become a maintenance headache.

Traditional format strings have a number of problems each stemming from the index-based hole approach. First, each value must be supplied in the order that corresponds to the index which isn’t necessarily the order that the values appear in the string. Next, as the number of holes increases, it can be difficult to discern what each hole represents. This isn’t normally a problem for strings with only a few holes but consider the nightmare of keeping indices straight on a format string with more than 50 holes like I once encountered. Finally, String.Format validates only that enough values were supplied to fill each of the holes but if values were provided than there are holes there’s not even a compiler warning. Combine this with one of those 57-hole strings and good luck finding which indices are off or which values should be removed.

C#’s string interpolation aims to fix each of the aforementioned problems. The current implementation uses a slightly clunky version of the traditional format string syntax in that each hole must be prefixed with a backslash. Here’s how the previous example would be written in C# 6.0 using the syntax that’s in the current preview:

var name = "Dave";
WriteLine("My name is \{name}");

Just as in the Perl example, the compiler will resolve the name and fill the hole with the appropriate value. What’s more is that the compiler also verifies that each name exists in the current context and flags anything it can’t resolve as an error.

Per the upcoming features document, this syntax will be changed to something a bit friendlier. Rather than prefixing each hole with a backslash, the string will be identified as an interpolated string by prefixing it with a dollar sign like this:

var name = "Dave";
WriteLine($"My name is {name}");

In this trivial example the net effect on the code is moving and replacing a single character but it’s easy to imagine more complex interpolated strings becoming significantly shorter. (There will also be a FormattedString class added to the System.Runtime.CompilerServices namespace to facilitate custom formatting via the IFormattable interface but I won’t cover that in this article).

That interpolated strings (in either form) closely resemble traditional format strings is not entirely coincidental because ultimately, each interpolated string is syntactic sugar for invoking String.Format. Essentially, the compiler replaces each of the named holes with indexed holes and constructs the value array from the provided names. The benefit of this is that anything you can do with traditional format strings such as including alignment and format specifiers also is also possible with interpolated strings. For instance, we could easily represent a date in ISO 8601 format as follows:

"Current Date and Time (UTC): \{DateTime.UtcNow:o}"

So that’s C#’s string interpolation feature in a nutshell and I’m pretty excited about the direction it’s going because it’ll gradually clean up a lot of code. Since the feature is still under development there’s an active discussion in progress over on the Roslyn site. If you’re interested in seeing some of the thought process behind where this feature is going I encourage you to check it out.

C# 6.0 – nameof Expressions

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

I’ve lost track of the number of times I’ve needed to pass along the name of something be it a property, method, or type. Historically we’ve relied on hard-coded strings to convey this information but as we’re all too well aware, relying on strings in such a manner is just asking for future problems. For a prime example, we need look no further than our old friend INotifyPropertyChanged.

Consider the following Circle class which typifies the basic INotifyPropertyChanged implementation pattern:

public class Circle
  : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  private double _radius;
  public double Radius
  {
    get { return _radius; }
    set
    {
      _radius = value;
      RaisePropertyChanged(&quot;Radius&quot;);
    }
  }

  private void RaisePropertyChanged(string propertyName)
  {
    if (PropertyChanged == null) return;

    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

Although this class is pretty boilerplate, it highlights the problem well. First, we’ve violated the DRY principle by encoding a member name in a string. Next, we’ve introduced fragility by relying on the string always reflecting the property name exactly; should the property name ever change we need to remember to change the string as well lest we waste some cycles tracking down why an event handler isn’t picking up the property change. What’s worse is that by encoding the name within a string, we get no compile-time support alerting us to the discrepancy.

The story around INotifyPropertyChanged and other similar scenarios has improved over the years as people have come up with some creative solutions. For instance, I’m particularly fond of the expression tree approach because despite its added complexity, it adds the compile-time support lacking in the string-based approach and ties in nicely to Visual Studio’s built-in refactoring capabilities.

.NET 4.5 improved the story a bit more by introducing a few attributes we could apply to optional parameters to get information about the method caller with CallerMemberNameAttribute being the most notable for this discussion. By decorating a parameter with CallerMemberNameAttribute as shown in the revised RaisePropertyChanged method that follows we’re instructing the compiler to inject the name of the member that invoked the method.

private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
  if (PropertyChanged == null) return;

  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

With this revised version, we could simply invoke the method without passing the name and the compiler would resolve the name for us. The problem with this approach is that there’s nothing in IntelliSense to inform us that the parameter is decorated with the attribute and there’s nothing stopping us from providing a value. In fact, the compiler won’t even warn that a name won’t be resolved if we do provide a value. Furthermore, while CallerMemberNameAttribute works nicely for this example, it’s only useful when we need the caller name so it won’t help us if we need the name of anything else such as a parameter name. That’s where the new nameof operator comes in.

C# 6.0’s nameof operator is used to resolve the name of an item at compile-time, essentially inserting the string into the compiled code. What’s really great about it is that it’s simple to use and works on any symbol.

In keeping with the INotifyPropertyChanged example, in C# 6.0 we can add compile-time safety to the original example code simply by replacing:

RaisePropertyChanged("Radius");

with:

RaisePropertyChanged(nameof(Radius));

There are plenty of other places I can see the nameof operator coming in handy. For instance, I often like to use a Guard class to perform a variety of pre-condition checks against method parameter values. Such a class typically looks a bit like this:

public sealed class Guard
{
  private static Lazy<Guard> _against = new Lazy<Guard>();

  public static Guard Against { get { return _against.Value; } }

  public void Null(string arg, object value)
  {
    if (value == null) throw new ArgumentNullException(arg);
  }

  // additional guard methods here
}

I generally create the Guard class as a sealed singleton class rather than as a static class to not only create a more English-like API, but also to allow extension methods in certain scenarios. I also like defining the Guard class methods as a fluent interface but omitted that for brevity.

Given that the Guard class operates off of arguments rather than callers, adding parameters decorated with CallerMemberNameAttribute clearly won’t work in this scenario. Instead we can simply update calls to the various methods to use the nameof operator instead of a hard-coded string and our code will immediately be less fragile.

C# 6.0 – Expression-bodied Members

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

Expression-bodied members are another set of features that simply add some syntactic convenience to C# to continue streamlining type definitions. C# type definitions have always been a bit tedious, requiring us to provide curly braces and explicit returns even when the function consists of only a single line. Lambda expressions have spoiled us by abstracting away most of the syntax that’s typically associated with functions and finally making delegation feel like a natural part of the language. Expression-bodied members extend the convenience of lambda expressions to type members… to an extent.

According to the Visual Studio “14” CTP3 notes, expression-bodied members can be used for methods, user-defined operators, type conversions, and read-only properties including indexers (although expression-bodied indexers don’t work properly in the CTP).

To demonstrate the feature, I’ll define a custom RgbColor class and using expression-bodied members for both a hexadecimal formatting method and a custom negation operator.

public class RgbColor(int r, int g, int b)
{
  public int Red { get; } = r;
  public int Green { get; } = g;
  public int Blue { get; } = b;

  public string ToHex() =>
    string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue);

  public static RgbColor operator - (RgbColor color) =>
    new RgbColor(
      color.Red ^ 0xFF,
      color.Green ^ 0xFF,
      color.Blue ^ 0xFF
    );
}

As convenient as expression-bodied members appear on the surface, they seem rather limited in their utility since their very nature requires expressions. This fact is compounded by the fact that C# isn’t an expression-based language; if it were (as F# is) we could get away with defining more complex bodies including some intermediate values such as a regular expression match result. As it stands today it’s not possible to do this without first defining that logic in a separate method that can be invoked from the expression-bodied member but that seems to defeat the purpose. Perhaps this would be a good use for the semicolon operator since we can’t even include that logic within curly braces as we could with a lambda expression.

C# 6.0 – Params IEnumerable

[7/30/2015] This article was written against a pre-release version of C# 6.0 and didn’t make it into the final product. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

One of the items currently listed as “planned” on the Language Feature Implementation Status page is params IEnumerable. This is one of those features that I’ve thought could be nice but I’ve never really felt strongly about it one way or another mainly because I avoid params arrays whenever possible. I think the only time I actually use them consistently is with String.Format and its cousin methods. Before diving into the new feature, let’s revisit params arrays so I can better explain why I avoid them and why I’m so apathetic about this proposed feature.

The idea behind params arrays is that they let us pass an arbitrary number of arguments to a method by defining said method such that its final parameter is an array modified by the params keyword. When we invoke the function, the compiler implicitly creates an array from the final parameters and is then passed to the method. In the method body, we typically access those values through the array. The following function shows this in action:

string MyStringFormat(string format, params string[] tokens)
{
  return
    Regex.Replace(
      format,
      @"\{(?<index>\d+)\}",
      m => tokens[Int32.Parse(m.Groups["index"].Value)].ToString());
}

We could then invoke this function as follows:

var format = "[{0}] Hello, {1}.";
var time = DateTime.Now.ToShortTimeString();
var name = "Guest";

var str = MyStringFormat(format, time, name);
// [10:35 PM] Hello, Guest.

Back in the early days of the .NET Framework, before we had collection initializers, the above was far more convenient than using an array directly. Now that collection initializers let us define arrays inline, we can simply write this:

var str = MyStringFormat(format, new [] { time, name });
// [10:35 PM] Hello, Guest.

Arguably, the former is a bit cleaner than the later because of the inline array definition but I have two problems with it. First, it masks the fact that an array is involved, and second, params arrays can really wreak havoc on overload resolution if you’re not careful with them. Assume we need to overload the MyStringFormat method to accept another string that will control some formatting options. We can’t tack the string on to the end of the parameter list because params arrays must appear last so we insert it at the front like this:

Note: I’m using string constants here for illustration purposes. A less contrived example would likely use an enum, thus avoiding the problem.

static class StringTransform
{
  public const string Uppercase = "Uppercase";
  public const string Lowercase = "Lowercase";
}

string MyStringFormat(string transformation, string format, params string[] tokens)
{
  var str = MyStringFormat(format, tokens);
  
  switch (transformation)
  {
    case StringTransform.Uppercase: return str.ToUpper();
    case StringTransform.Lowercase: return str.ToLower();
  }      

  return str;
}

Now we can invoke this new overload as follows:

var str = MyStringFormat(StringTransform.Uppercase, format, time, name);

…and the result would be as we would expect:

[12:30 AM] HELLO, GUEST.

But now that we have two overloads (each accepting an indeterminate number of strings) the compiler cannot always properly determine which overload to invoke. Let’s see what happens when we supply only three arguments as we did in the first example.

var str = MyStringFormat(format, time, name);

Now the result is:

12:30 AM

What happened? The compiler recognized that there are multiple candidate overloads so it took a greedy approach, selecting the overload with the most explicit parameters. As a result, each of the arguments were essentially shifted to the left of what we expected. In other words, what should have been the format parameter was treated as the transformation parameter, the first of the token values was treated as the format parameter, and so on. To force the compiler to use the correct overload, we can just be explicit with the array as we saw in the second example above:

var str = MyStringFormat(format, new [] { time, name });

So what does all of this have to do with params IEnumerable? Params IEnumerable is an extension of the core idea; rather than treating the last arguments as an array within the method, we’d treat them as a sequence. That is, in our MyStringFormat method, we’d define the final parameter as params IEnumerable<string> tokens rather than params string[] tokens.

This change makes sense from a language perspective especially since params arrays were implemented long before IEnumerable<T> was a central concept within the framework. But, as the May 21st design notes state, when the method is used as a params method (rather than by passing an explicit sequence), the compiler will still generate an array at the call site. For all other cases, passing a sequence will behave no differently than if the parameter had been defined without the params modifier.

Given that:

  • it’s so easy to define sequences inline
  • using params arrays can easily confuse the overload resolver
  • params IEnumerable will only hide the sequence’s details from the method implementation but otherwise have no effect on the code

…I don’t see myself ever using this feature. I’ll likely continue designing methods to accept IEnumerable<T> without including the params modifier to avoid the problems and be more specific about what the method is expected to do.

C# 6.0 – Semicolon Operator

I first read about the proposed semicolon operator a few weeks ago and, to be honest, I’m a bit surprised by the desire for it in C# if for no reason other than that C# isn’t an expression-based language. To me, this feature feels like another attempt to shoehorn functional approaches into an object-oriented language. If I understand the feature correctly, the idea is to allow variables to be defined within and scoped to an expression. The following snippet adapted from the language feature implementation status page shows the operator in action:

var result = (var x = Foo(); Write(x); x * x);

In this code, everything within the parentheses constitutes a single expression. The expression invokes Foo, assigns the result to x, passes x to the Write function, then returns the square of x, and ultimately assigns the square to result. Because x is scoped to the expression, it is not visible outside of the parenthesis. I think this seems a bit awkward in C# and what’s more, I don’t know what value it adds that functions don’t already give us. I haven’t really decided whether the above example is more readable or maintainable than if we’d defined a function called WriteAndSquare.

Interestingly, this capability already exists in F# (albeit in a slightly more verbose form) which isn’t really all that surprising since F# is an expression-based language.

let result =
  let x = Foo()
  printfn "%i" x
  x * x

Even in F# though, I think I’d still prefer factoring out the expression into a function.

C# 6.0 – Null Propagation Operator

[7/30/2015] This article was written against a pre-release version of C# 6.0 but is still relevant. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

One of the most common complaints about C# (especially among the F# crowd) is the amount of code required to properly deal with null values. Consider the following type definitions and invocation chain:

Type Definitions

class PriceBreak(int min, int max, double price)
{
  public int MinQuantity { get; } = min;
  public int MaxQuantity { get; } = max;
  public double Price { get; } = price;
}

class Product(IList<PriceBreak> priceBreaks)
{
  public IList<PriceBreak> PriceBreaks { get; } = priceBreaks;
}

Invocation Chain

var minPrice = product.PriceBreaks[0].Price;

As it’s written the preceding invocation chain is full of problems (we’ll ignore the potential ArgumentOutOfRangeException for this discussion). In fact, it can throw a NullReferenceException when any of the following values are null:

  • Product
  • Product.PriceBreaks
  • Product.PriceBreaks[0]

To properly avoid the exception we need to explicitly check for null. One possible approach would look like this:

double minPrice = 0;

if (product != null
    && product.PriceBreaks != null
    && product.PriceBreaks[0] != null)
{
  minPrice = product.PriceBreaks[0].Price;
}

Now we can be certain that we won’t encounter a NullReferenceException but we’ve greatly increased the complexity of the code. Rather than a single line, we have 5 that actually do something and of that, less than half are providing any value beyond making sure we don’t see an exception. C# 6.0’s null propagation operator (?) gives us the safety of checking for nulls while avoiding the verbose ceremony. The result is much cleaner and closely resembles the invocation chain shown earlier:

var minPrice = product?.PriceBreaks?[0]?.Price;

Introducing the null propagation operator allows us to chain each call while short-circuiting any nulls encountered along the way. In this case, the return type is double? (INullable) because anything preceding Price can be null. As such, we can either defer checking for null until we try to use the value or we can simply use the null coalescing operator with a default to coerce the type conversion as follows:

var minPrice = product?.PriceBreaks?[0]?.Price ?? 0;

One limitation of the null propagation operator is that it can’t work directly with delegate invocation. For instance, the following code is invalid:

var result = myDelegate?("someArgument");

Fortunately, there’s a workaround; rather than invoking the delegate directly as shown above, we can use invoke it via the Invoke method like this:

var result = myDelegate?.Invoke("someArgument");

The null propagation operator should eliminate a great deal of null reference checking code although I still believe F#’s approach of virtually eliminating null is superior. Honestly, my biggest concern about the null propagation operator is that it could encourage Law of Demeter violations but that’s a discussion for another day.

Enabling the C# 6.0 Features in the VS “14” CTP

If you’ve been following along with my C# 6.0 features series or have otherwise wanted to experiment with some of the new language features, you may have noticed that they’re not enabled by default. Fortunately, Anthony Green included instructions on how to enable them in a post on the C# FAQ MSDN blog.

To summarize the instructions, the language features are experimental so they must be enabled by manually adding the following to your project file:

<LangVersion>experimental</LangVersion>

This element should be placed within the appropriate PropertyGroup element(s) for your project. Once you’ve added the element, reload the project and enjoy the new features!

C# 6.0 – Exception Filters

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

I debated quite a bit with whether I’d write about C# 6.0’s exception filters because honestly, I was indifferent about them at first. What convinced me to include them in this blog series is that the language feature implementation status page lists the feature as done. After playing with the feature a bit, I have to admit that they’re actually pretty nice and do feel like a natural extension to the language as they’ve been implemented. As the CTP notes state, including exception filters with C# increases feature parity with VB and F# (although I still prefer F#’s exception pattern matching, of course).

Traditionally, whenever we’ve caught an exception we’ve had to handle it somehow or rethrow it. Rethrowing exceptions requires more overhead to handle them again and it also has a strong tendency to jack up the call stack as far as reporting goes. If we want to take a different action according to some condition, we need some kind of conditional structure inside the handler. The following code shows a traditional approach to conditionally handling an exception based on its Message property.

try
{
  throw new Exception("Forced Exception");
}
catch (Exception ex)
{
  if (ex.Message.Equals("Forced Exception", StringComparison.InvariantCultureIgnoreCase))
  {
    WriteLine("Filtered handler");
  }

  throw;
}

The preceding snippet is pretty simple but it’s easy to see how more complex filtering scenarios could complicate the handler code. Exception filters improve this story by catching exceptions only when some criteria is met. If the criteria isn’t met, the exception processing logic proceeds as normal, either moving on to the next handler definition or bubbling up. Here’s the above example revised to use exception filtering:

try
{
  throw new Exception("Forced Exception");
}
catch (Exception ex) if (ex.Message.Equals("Forced Exception", StringComparison.InvariantCultureIgnoreCase))
{
  WriteLine("Filtered handler");
}

Here you can see how the condition has been moved into the catch block itself via a contextual if statement. Now the handler body will execute if and only if the expression within the parenthesis evaluates to true. Now, at this point you might be thinking about ways to abuse this and you wouldn’t be alone. In fact, the CTP notes point out how a false returning function can be used as an exception filter to cause some side-effect (such as logging) related to the exception without actually handling the exception.