Tag Archive: .net

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.

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

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.

Base Class Library finally has first class support for zip archives in .NET 4.5

I’m very excited about this. First off, I hate third-party dependencies. I always try to accomplish everything with the platform I use, in this case the BCL. A friend of mine was asking me to write a blog article on System.IO.Packaging and how to use types like GZipStream. After suggesting SharpZipLib and DotNetZip, I became a rather curious rhino and did a quick Object Browser search in the .NET 4.5 base class library for the term zip. Sure enough, my eyes did not deceive me and I immediately saw ZipArchive! You will need to add a reference to System.IO.Compression.dll to use these types.

Immediately I began to just experiment with the type. After I wrote my own code on how I figured it would be used, I checked Msdn and sure enough my code was virtually identical to the example code.

namespace ZipArchiveDemo
{
    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;

    class Program
    {
        static void Main(string[] args) {
            const string path = @"c:\users\danderson\my documents\archive.zip";

            using (FileStream fstream = new FileStream(path, FileMode.Create))
            using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Create)) 
            {
                ZipArchiveEntry entry = archive.CreateEntry("test.txt");
                
                using (StreamWriter writer = new StreamWriter(entry.Open())) {
                    writer.WriteLine("I'm just a curious little rhino!");
                }
            }

            if (!File.Exists(path)) {
                throw new System.IO.FileNotFoundException(String.Format("{0} was not found.", path));
            }

            using (FileStream fstream = new FileStream(path, FileMode.Open))
            using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Read)) 
            {
                ZipArchiveEntry entry = archive.Entries.FirstOrDefault();

                using (StreamReader reader = new StreamReader(entry.Open())) {
                    Console.WriteLine(entry.Name);
                    Console.WriteLine(reader.ReadToEnd());
                }
            }

            Console.ReadKey();
        }
    }
}

Pretty simple and not much else to it. The first two using blocks create the archive and then I just do a quick check if it was created, and throw an Exception otherwise. The last set opens the archive and grabs the first entry (since there’s only one) and writes it to the standard output stream.

I have to hand it to the BCL team on this one. THANK YOU.

What is WinRT and how does it affect .NET?

Apparently there is fuss going on about what WinRT (Windows Runtime) is and how it affects .NET. I’m going to talk about that based on my understanding of WinRT.

WinRT, or the Windows Runtime, is theoretically the successor to Win32. It’s not a true runtime in the sense of a virtual machine like the CLR either. The term is used rather loosely. I also say theoretically, because it’s just another layer over Win32 written in native code and COM-based API. It doesn’t actually replace Win32. What it does do however, is expose Win32 to virtually any programming language through what are called language projections. I’ll get to that in a moment. Right now WinRT supports native C++, JavaScript and HTML, C#, Visual Basic, and probably C++/CLI. You’re probably wondering how this is possible, and even further how it is now possible for a CLR language to call directly into WinRT API’s when it is purely a native implementation.

WinRT can be summarized by the following.

  • Win32
  • Pure native implementation
  • Patterns and practices
  • Metadata
  • Language projections

Patterns and practices. Remember how many string types there are in C++? Remember how horrid the type names are? In WinRT, they used .NET practices for naming types and API’s.

Metadata. The WinRT team could have chosen anything for storing metadata, even just xml. Instead, they chose to use .NET metadata. .NET metadata isn’t specific to managed code, and it’s really just a specification and format for storing meta information. There’s no need to re-invent the wheel and create yet-another-metadata-format. Because they chose .NET metadata, the type information is easily exposed to a CLR language and the experience is seamless.

Language Projections. A language projection in WinRT is a subsystem that handles conversions from one language into something WinRT understands. For example, if you are calling into a WinRT API from C# that takes a special type of string that C# doesn’t know about, the language projection layer will do the conversion for you. You don’t even know that the conversion is taking place from the perspective of C#, which is what makes this experience seamless. Another example is IEnumerable<T> in .NET. WinRT doesn’t have an IEnumerable<T>, but it does have IIterable<T> which is basically the same thing. But they’re different interfaces, so the language projection does the conversion for you. This also allows you to seamlessly iterate over WinRT collections from a CLR language. Language projections are the magic of supporting virtually any language.

Now up to this point, I haven’t really said anything specific about .NET. WinRT itself is purely native, but a subset of the .NET base class library is integrated into WinRT. This is why WinRT right now lacks most of what .NET has to offer, and WinRT is not currently supported in desktop applications or console applications. So how does “Metro”, or now known as Windows 8 UI play into all of this? It’s just the UI layer available in WinRT. That’s it. Just like Windows Forms or WPF is a subset in .NET, Windows 8 UI is a subset in WinRT. WinRT is separate from .NET, and it needs some way to display an interface and right now that’s Windows 8 UI. Windows 8 UI is basically for developing Windows Store applications. I personally call these glorified cell-phone apps, because there is no backwards compatibility, period. Windows Store apps will not run on any operating system except Windows 8, and I believe Windows Phone 8.

How does this affect .NET? If you want my honest answer here it is. It doesn’t. Yet. One of the WinRT team’s fears is they hope they didn’t create a parallel platform, but in my view that will be the future result. I’m going to summarize why it doesn’t affect .NET now, and why it will in the future.

Effect Now

  • Isn’t accessible to desktop, console, or web applications.
  • Integrates only a subset of the .NET base class library, so in comparison it is very limited.
  • It completely breaks backwards compatibility with everything prior to Windows 8.
  • WinRT apps can only be distributed through the Windows App Store.
  • WinRT only allows a single app to be open at a time.
  • WinRT forces apps to run in a limited, isolated/sandboxed environment.

Right now it isn’t changing anything about .NET -at all-, but that can change very quickly in the future. I think the affect WinRT can have towards .NET in the future heavily relies on a few factors. One, if it is made available to desktop, console, and web applications. And two, how much Microsoft invests in developing libraries for WinRT. Let’s assume for a moment that WinRT is eventually made available to desktop applications. It already eliminates the need for platform invoking down to the Win32 layer, so it deprecates that part of .NET. It brings all languages, even non-CLR languages to an equal playing field, and this is a huge achievement. Those two points alone are very powerful, but I think the third point would be if they ever include a desktop UI layer in WinRT, or allow Windows Store Apps to run in the desktop. That would probably be the final question, because WPF for example is huge, and managed. It would be a large undertaking to integrate that into WinRT.

I’m not sure what’s going to happen from here, but it can go in some very interesting directions. With the drastic change Microsoft made to the Windows desktop by removing the start button and implementing this new Windows 8 UI Start Screen, and with Windows Store apps, who knows what will change in the future.

IValueConverter Interface (System.Windows.Data.IValueConverter)

Probably the most common question I get from people new to WPF is how to bind the Visibility of a control based on a System.Boolean value. WPF provides IValueConverter in System.Windows.Data specifically for converting one type to another and back when binding. Let’s setup a very simple example.

/// <summary>
/// ViewModel for MainWindow
/// Assigned to MainWindow.DataContext in its class constructor
/// </summary>
internal class MainWindowDataContext : INotifyPropertyChanged
{
    private bool _visible;

    public bool Visible {
        get {
            return _visible;
        }
        set {
            _visible = value;

            PropertyChangedEventHandler handler = PropertyChanged;

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

    public event PropertyChangedEventHandler PropertyChanged;
}
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Visibility="{Binding Visible}" />
    </Grid>
</Window>

You should already know that line 7 doesn’t work. There isn’t a conversion from System.Boolean to System.Windows.Visibility. This is where IValueConverter comes in, so we will make a new class that implements the interface and call it BoolToVisibilityConverter.

internal class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is bool)) {
            throw new System.ArgumentException("value is not of type System.Boolean", "value");
        }
        return (bool)value ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is Visibility)) {
            throw new System.ArgumentException("value is not of type System.Windows.Visibility", "value");
        }
        switch ((Visibility)value) {
            case Visibility.Visible:
                return true;
            default:
                return false;
        }
    }
}

The implementation is simple. When the binding gets the value from MainWindow.DataContext (eg. MainWindowDataContext.Visible) it is passed to the value parameter of object Convert. Then it’s up to the convert method to return the appropriate value based on the parameter. In this case, we do a simple check to make sure the parameter is in fact a System.Boolean value, and if it is we return the appropriate Visibility enumeration value. Obviously, ConvertBack does exactly the opposite when the value of the binding is set, and is propagated down to the data context. It takes a Visibility value and converts it to a System.Boolean value, which is assigned to MainWindowDataContext.Visible.

Now we need to update our Xaml to use the converter. This is done by including it as a resource and specifying the Converter attribute on the binding.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverterResourceKey"/>
        </Grid.Resources>
        <Button Visibility="{Binding Visible, Converter={StaticResource BoolToVisibilityConverterResourceKey}}" />
    </Grid>
</Window>

You can implement IValueConverter any time you need to convert one type to another and back in a binding.

Persistence Ignorant Architecture with Entity Framework ORM.

I finished the screencast and have uploaded it to YouTube here. I also have attached the source code to this blog post, but I wanted to comment on a few post-video changes I have made.

providerConnectionString = String.Empty;

if (String.IsNullOrWhiteSpace(providerConnectionString)) {
    throw new System.NotImplementedException(Properties.Resources.ConnectionStringNotSet);
}

I removed App.config from the project (which was never needed). You will need to set the connection string yourself, and I added the code to throw an exception with a reminder in case you forget. You should be able to use the Create Database from Model feature in the Entity Designer, but I was having troubles in the screencast so I created the tables manually.

Screencast Demo Code
Visual Studio 2010
Download PI-Entity-Demo.zip