Newest Posts

Verbatim Identifiers and verbatim string literals in C#

Browsing through some of my old answers on StackOverflow, I came across this question I had answered regarding verbatim identifiers in the C# language. I want to take a moment to talk about this mysterious language feature, because it actually has multiple usages, one which is quite common, and you just might not be aware you are using it.

To start, I’ll describe to you what a verbatim identifier actually is by citing the C# language specification.

The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.

This text comes from section 2.4.2 of the language specification. It is also interesting to note that this language feature has been available since the first version of C#, specifically version 1.0 and 1.2, but it is not a feature that you would normally seek out as you learn a language. Good programmers generally try to find better names for variables than ‘object’ or ‘string’, especially since they conflict with existing type identifiers.

A valid usage of this language feature would be the following.

public string ToString(object @object)
{
    string @string = @object as string;

    if (@string != null)
        return @string;

    throw new ArgumentException("@object is not of type System.String.");
}

This is a terrible piece of code, but it does demonstrate the usage of the language feature correctly. But the language feature itself is a bit more flexible than that, but I don’t believe by design. We would of course have to ask the language designers, but let’s look at the code from the question I answered on StackOverflow.

_scale_id_regex = @ConfigurationSettings.AppSettings["some_setting"];

The gentlemen asked what the purpose of this symbol was in this piece of code. What I described earlier is pretty much the extent of what is outlined by the language specification, but the short answer is that it does not serve any real purpose. It is simply allowed by the language rules, and thus allowed by the compiler implementation. You can look at it a bit deeper however. Almost everything in code that has a name is considered an identifier, in this case ConfigurationSettings is the identifier, and verbatim identifiers are allowed by the language rules.

You’re hopefully wondering by now what this has to do with string literals, aha! String literals. A string literal in C# is identified by the usage of @ at the beginning of zero or more characters enclosed in double quotes, as in @"The fox jumped over the hole.". Again, we should reference the C# language specification to describe a string literal.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escaped-sequence. In particular, simple escape sequences, and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

We never really think about verbatim identifiers, and we don’t think about string literals as verbatim string literals as programmers. We just think of string literals, because that is the common terminology, but the usage of the @ symbol to specify something as verbatim dates back to C# 1.0 and 1.2 with verbatim identifiers and string literals. The language feature is still very much alive into C# 5.0 and while verbatim identifier usage is very rare (and should be), verbatim string literals are a daily routine for programmers.

Microsoft releases Visual Studio 2012 Update 2 CTP 2

I missed the punch (original source), but on January 30th Microsoft announced the release for Visual Studio Update 2 CTP 2, which brings four key areas of improvement.

  • Agile Planning
  • Quality Enablement
  • Line of Business Development
  • Developer Experience

Agile Planning


Work Item tagging.
You can tag work items, similar to tagging a post on StackOverflow or WordPress, to further categorize and filter work items.

You can also send work items via email now with Team Web Access.

Quality Enablement


Test Hub in Team Web Access. 
For the web access there is now a `Test` tab where you can enable manual testing for systems that don’t have Test Professional. You can view and edit test cases in a test plan and run them manually.

Line of Business Development

Improved SharePoint load testing. Building on the SharePoint load testing ability from Update 1, Microsoft has taken customer feedback and added additional support for InfoPath, Excel services, Office Web Companions, workflows, and more.

Office 2013. Microsoft has also added support for tooling for Office and SharePoint 2013 including development, Coded UI Testing, load testing, and even Intellitrace.

Developer Experience

Blend for Visual Studio 2012. Blend has been added back for Visual Studio 2012 and includes support for WPF, Silverlight, and Sketchflow.

CodeMap and Debugger Integration. Easily add a call stack to a CodeMap to explore code dependencies from your debugging session.

Visual Studio Blue Theme. Because of vast feedback and complaints (I’m putting those words in there because it’s true, and shows that Microsoft does in fact listen). They have added the Visual Studio 2010 Theme, now called Blue theme which was originally part of the color theme editor, as a new default theme available in Visual Studio 2012.

Profiler events timeline. For Windows Store HTML/JS applications.

Why I think Microsoft shouldn’t make observable properties part of the C# Language specification.

INotifyPropertyChanged, how I love you implement you in every object over and over. How I can’t make you a reusable base class because it causes me to break important inheritance hierarchies. I love it, but I hate it because it is one of the most repetitive things I do in programming. It’s absolutely vital for data-binding in various frameworks like Windows Forms and Windows Presentation Foundation, but I can’t help but think “why isn’t this a core part of the C# language?”.

My solution would to be to add a contextual keyword to the C# language specification, and call it observable. It would be used like this.

public observable class A
{
    public observable String PropertyName
    {
        get;
        set;
    }
}

And this is what I see the compiler generating.

public class A : INotifyPropertyChanged
{
    public String PropertyName
    {
        get
        {
            return propertyNameField;
        }
        set
        {
            propertyNameField = value;
            OnNotifyPropertyChanged("PropertyName");
        }
    }

    public PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

How this should work is that when you compile your class, the compiler sees the observable keyword on the class and implements INotifyPropertyChanged interface for the class. Next, it sees any properties that are also observable and injects a call to OnPropertyChanged with the appropriate parameters. Okay, so this is a pretty good argument for implementing this, but that isn’t the title of my post.

The problem with this, albeit requested or thought of by many programmers over the years, is you have zero control over this. I’ll list out some of the limitations.

  • You can’t put a lock in OnPropertyChanged(String)
  • You can’t put any custom code in OnPropertyChanged(String)
  • You can’t use this with .NET 4.5 caller attributes
  • You can’t control the accessibility of OnPropertyChanged(String)
  • You can’t control whether OnPropertyChanged(String)
  • can be overridden or not.

In general, this is a bad idea. You could potentially solve all of these problems with compiler flags, but I believe this creates language and compiler bloat, both of which I disagree with. I’m sure the C# language team has already visited this discussion, Anders himself has discussed it at one point. I think the real solution would be to think outside of the box and how to ease-the-pain of implementing the interface instead.

A PropertyHelper class for property setter validation.

A common practice is to do property-level validation in the property setter of an object like the following.

public String Name {
    get {
        return this.name;
    }
    set {
        if (value == null) {
            throw new System.ArgumentNullException("value");
        }
        if (value.Length == 0) {
            throw new System.ArgumentException("Name cannot be empty.", "value");
        }
        this.name = value;
    }
}

Most of the time though, this violates the DRY principle (Don’t Repeat Yourself), because you may need to do the same exact validation in a constructor for example.

public Customer(String name) {
    get {
        return this.name;
    }
    set {
        if (name == null) {
            throw new System.ArgumentNullException("name");
        }
        if (name.Length == 0) {
            throw new System.ArgumentException("Name cannot be empty.", "name");
        }
        this.name = value;
    }
}

Now you might be asking at this point, “Why are you not just using the Name property in the constructor, which would invoke the setter validation?”. Often times when writing POCO’s for Entity Framework, you will use virtual properties to enable proxy creation. Calling into a virtual property is a Microsoft Usage violation (CA2214:DoNotCallOverridableMethodsInConstructors), because if the property is overridden and the deriver does not call the base property, your setter is not invoked and your validation is ignored.

I started thinking, and I came up with an interesting idea to use a helper class with a fluent-api to do validation. Usually when I come up with ideas, I write code how I would like to write it, and then implement the API based on how I want it to look. I wrote this psuedo code.

public String Name {
    get {
        return this.name;
    }
    set {
        PropertyHelper.Validate<String>("Name", value)
            .ArgumentNullException()
            .ArgumentException(v => v.Length == 0)
            .ArgumentOutOfRangeException(v => v.Length > 32);
        this.name = value;
    }
}

Next, I started to actually write the implementation, which obviously had to start with PropertyHelper.

internal static class PropertyHelper
{
    internal static ? Validate<T>(String propertyName, T value) {
        ?
    }
}

At this point I was thinking about how a fluent-api is actually designed, and I had to figure out the following:

  • What does Validate<T> return?
  • How do I pass the property name and value correctly so it is known for each API call?

To solve these I answered each. First, each ‘fluent-api’ will really be a type of exception that can be thrown by some condition that represents the validation rule. Secondly, I would need to provide the property name and value to it, and it would have to provide that to the next call. I came up with this.

internal class PropertySetter<T>
{
    private string propertyName;
    private T value;

    public PropertySetter(String propertyName, T value) {
        this.propertyName = propertyName;
        this.value = value;
    }
}

This completes the two key questions in the prior method I wrote for PropertyHelper.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }
}

Now I needed to write the actual exception-api’s, so I started with the most simple ArgumentNullException.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }

    internal static PropertySetter<T> ArgumentNullException(Func<T, Boolean> predicate) {
        if (!predicate(value)) {
            throw new System.ArgumentNullException(propertyName);
        }
        else {
            return this;
        }
    }
}

This works well also. Each time a call is made to ArgumentNullException(), it will return itself to the caller, thus passing the property name and value along with it. The predicate is just a simple anonymous function that takes T which is the type of the value. This is the same predicate that is used for SingleOrDefault(Func<T, Boolean>) that is used with IEnumerable. Next, I can implement a few more methods.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }

    internal static PropertySetter<T> ArgumentNullException(Func<T, Boolean> predicate) {
        if (!predicate(value)) {
            throw new System.ArgumentNullException(propertyName);
        }
        else {
            return this;
        }
    }

    internal static PropertySetter<T> ArgumentException(Func<T, Boolean> predicate, String message) {
        if (!predicate(value)) {
            throw new System.ArgumentException(message, propertyName);
        }
        else {
            return this;
        }
    }
}

Because each one returns a PropertySetter<T> you can keep chaining them, and you can chain them in the order you want. Whichever predicate returns false first will throw that exception.

public Int32 Value {
    get {
        return this.value;
    }
    set {
        PropertyHelper
            .Validate<Int32>("Value", value)
            .ArgumentException(v => v == 1, "Value cannot be 1.");
        this.value = value;
    }
}

There is still some level of DRY here, but it is a lot cleaner and easier to maintain. It also allows you to abstract away the logic that throws the exceptions and checks the predicate, allowing you to write code that visibly focuses on the validation itself. Although I called it PropertyHelper, you could really use this almost anywhere. Properties, methods, and constructors. This also isn’t the best approach probably, but it was an interesting approach and a fun one to write. You can grab the full implementation below.

//-----------------------------------------------------------------------------
// <copyright file="PropertyHelper.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
//     Open Source. Personal and Commercial usage allowed.
// </copyright>
//-----------------------------------------------------------------------------

namespace Northwind.Data
{
    using System;
    using System.Globalization;
    using System.Linq;

    /// <devdoc>
    /// Helper methods for property setters.
    /// </devdoc>
    public static class PropertyHelper
    {
        /// <summary>
        /// Performs property validation for the property setter.
        /// </summary>
        /// <typeparam name="T">The type of property value.</typeparam>
        public static PropertySetter<T> Validate<T>(String propertyName, T value) {
            return new PropertySetter<T>(propertyName, value);
        }
    }

    /// <summary>
    /// Provides methods for the SetValue() method of a property.
    /// </summary>
    /// <typeparam name="T">The type of property value.</typeparam>
    public class PropertySetter<T>
    {
        private string propertyName;
        private T value;

        /// <summary>
        /// Initializes a new instance of the FaultTrack.Data.PropertyHelper class.
        /// </summary>
        public PropertySetter(String propertyName, T value) {
            this.propertyName = propertyName;
            this.value = value;
        }

        /// <summary>
        /// Throws a System.ArgumentNullException if the property value is null.
        /// </summary>
        public PropertySetter<T> ArgumentNullException() {
            if (value == null)
                throw new System.ArgumentNullException(propertyName);
            else
                return this;
        }

        /// <summary>
        /// Throws a System.ArgumentException if the property value causes the specified predicate to return false.
        /// </summary>
        public PropertySetter<T> ArgumentException(Func<T,bool> predicate, String message) {
            if (!predicate(value))
                throw new System.ArgumentException(message, propertyName);
            else
                return this;
        }

        /// <summary>
        /// Throws a System.ArgumentOutOfRangeException if the property value causes the specified predicate to return false.
        /// </summary>
        public PropertySetter<T> ArgumentOutOfRangeException(Func<T,bool> predicate, String message) {
            if (!predicate(value))
                throw new System.ArgumentOutOfRangeException(propertyName, message);
            else
                return this;
        }
    }
}

TF30172: Cannot create a TFS 2012 Team Project from Visual Studio 2010 Team Explorer.

If you have tried to create a new Team Project from Visual Studio 2010 against a TFS 2012 server, you have undoubtedly encountered this error message.

After doing some research, it’s quite apparent that some changes were made to Team Foundation Server that make project creation incompatible with older TFS Clients. The error message actually doesn’t have anything to do with permissions, and during the beta for TFS 11.0 the error message was inaccurate and vague. I came across a statement by Buck Hodges, the current Director of Development for Team Foundation Server:

You must use the Visual Studio Team Explorer 2012 (included in all Visual Studio editions or may be separately downloaded) to create a team project on a TFS 2012 server. If you use VS 2010, you will get an error about not having permission. The error message is very misleading, because it’s not a problem with your permissions.

A bug was even reported, but closed by Microsoft, so it appears there are no plans to resolve this. Unfortunately sometimes this is the cost of adding features and releasing new versions, and you can still use Visual Studio 2010 SP1 against TFS 2012, just don’t expect to be able to create projects. Something to consider when thinking about migrating to TFS 2012.

ZipFile class (System.IO.Compression.FileSystem)

I was excited that the base class library in .NET 4.5 now includes native support for working with Zip files, but in my excitement I overlooked System.IO.Compression.FileSystem. The name of the assembly is actually misleading, because the namespace is still just System.IO.Compression, and it only contains one type and that’s ZipFile. This is a separate assembly from System.IO.Compression.dll so you will need to add it as an additional reference.

The ZipFile class is actually static, but it contains some four methods for quickly creating and reading zip files.

ZipFile.CreateFromDirectory(String, String)
ZipFile.ExtractToDirectory(String, String)
ZipFile.Open(String, ZipArchiveMode)
ZipFile.OpenRead(String)

ZipFile.CreateFromDirectory(String, String) is useful for quickly archiving entire directories. I could backup my documents for instance.

ZipFile.CreateFromDirectory(@"c:\users\danderson\documents", @"c:\users\danderson\documents\backup.zip");

I could do the reverse to restore my documents.

ZipFile.ExtractToDirectory(@"c:\users\danderson\documents\backup.zip", @"c:\users\danderson\documents");

There are some limitations however. One is that these methods will throw exceptions if the target path already exists when creating an archive, or a target directory exists when extracting files. If an exception is thrown, it will remain partially extracted however many files and folders were previously successful.