Blog

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

Empty Pattern

This thread on Msdn was one I came across, and I felt it needed a much better answer. His question in short, is what is the difference between null, Empty, and “” in C#. I assume that you know what null and "" are, so I’m going to focus on the meat of the question. So the obvious question is what is Empty? Let’s look deeper into some existing types that use this pattern.

System.String
String value = String.Empty;

System.Drawing.Rectangle
Rectangle value = Rectangle.Empty

I could go on, but I will stop there. There are a few things that types using this pattern have in common.

  • They are types that have value semantics
  • Empty is a public static readonly field
  • Empty’s type is the same as its containing type

Okay.. but what does all this mean. Empty is a public static readonly field that represents the default value for an instantiated type that has value semantics. This pattern is useful for two reasons. One, for value types, because value types are not nullable, it is an easy way to have access to the default value of that type, and is equivelent to calling default(T). And secondly, it is useful to find out if an instance of a type has been modified from its default value. Let’s take a deeper look at how this pattern applies to Value Types and Reference Types, and we’ll start with a value type.

public struct Point {
    public static readonly Point Empty = default(Point);
    public int X { get; set; } 
    public int Y { get; set; } 
}

For value types, since they cannot be null, it is good practice to use default(T) for declaring the empty field, however new Point() works just as well. Remember that default(T) for structs will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

Point p1 = Point.Empty;    // {0,0}
Point p2 = new Point();    // {0,0}
Point p3 = default(Point); // {0,0}

All three lines of code are equivelent, except in regards to performance. Using Point.Empty we are not instantiating a new instance of Point, but the other two methods do. A minor detail, but important to note regardless.

Point p = Point.Empty;
p.X = 1;
p.Y = 1;

if (p != Point.Empty) {
    p.X = 0;
    p.Y = 0;
}

Now you can see how Empty is useful. Very easy to see if the point has been modified from its default value. We can see how useful this pattern is for structures, and how its used in existing types in .NET. What about reference types? The same practices apply, but there is a difference in how we should declare the static field, because reference types can be null, which is their default value.

public class Point {
    public static readonly Point Empty = new Point();
    public int X { get; set; } 
    public int Y { get; set; } 
}

In the above sample, we changed our Point from a value type to a reference type, but note line two. Instead of using default(T), we are using new Point(). This is because the default value for a reference type is null, which is great, but we don’t want the default value, we want its Empty value.

The next important change, is that we must make the type immutable. Using this pattern on a mutable reference type will have negative impact and wrong behaviors in your application. Remember that value types use copy semantics, reference types hold a reference to the underlying object in memory, so if we were to use the following code:

Point p = Point.Empty;
p.X = 2;

This would actually modify the value of Point.Empty to be {2,0}. For this pattern to be viable when using a reference type, it must be immutable.

public class Point {
    public Point(int x, int y) {
        X = x;
        Y = y;
    }
    public static readonly Point Empty = new Point();
    public int X { get; private set; } 
    public int Y { get; private set; } 
}

There’s not much else to say, hopefully by now you understand why this pattern exists, so let’s recap my DO’s and DO NOT’s for this pattern.

DO Implement an T.Empty field on types that have value semantics.
DO Make T.Empty public static readonly.
DO Use default(T) as the value for T.Empty when used with a struct.
DO NOT Use default(T) as the value for T.Empty when used with a class, use new T() instead.
DO NOT Use this pattern on mutable reference types. Use them on immutable reference types like System.String.
DO NOT Use this pattern on types where value semantics don’t make sense.

How Auto width Grid columns work with column spanning.

A friend of mine was wondering if he had encountered a bug in WPF today. What he was trying to do is have a Grid with four columns, each with a width of Auto, and have a TextBox fill the entire width of his Grid. Here was his Xaml.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="4" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

What he wants is for his TextBox to take up the remaining width in the Grid. The way Auto works for a GridColumn‘s width, is that it sizes itself to the maximum width of its content. So in this case, the width of each column is that of the width of each button. Now because there are only four columns defined in the Grid, the TextBox can only span a maximum of four columns. The remainder of the Grid is undefined space that fills the Window, because the default behavior of a Grid is to fill its parent container.

So how do we get the TextBox to fill the undefined space? You define it. Add a fifth column with a * width, which means it will fill the remainder of the Grid space, and then we can set the TextBox to span all five columns, instead of the first four.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="5" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

How to use Enum as an ItemsSource using a MarkupExtension.

There are a lot of different ways to use an Enum as a data source for some list, like a ComboBox. I’m going to demonstrate how to create a MarkupExtension that will make your life a lot easier in all your projects. To create a markup extension, create a class that derives from MarkupExtension and overrides ProvideValue(IServiceProvider). Next, add a constructor that takes a System.Type as a parameter, and a property called EnumType to store the type information.

namespace MarkupExtensionDemo.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Markup;
    
    [MarkupExtensionReturnType(typeof(System.Object[]))]
    internal class EnumExtension : MarkupExtension
    {
        public EnumExtension() {
        }

        public EnumExtension(Type enumType) {
            EnumType = enumType;
        }

        [ConstructorArgument("enumType")]
        public Type EnumType {
            get;
            set;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
 	        if (EnumType == null) {
                throw new System.ArgumentException("The enumeration's type is not set.");
            }

            return Enum.GetValues(EnumType);
        }
    }
}

The real work is done in the ProvideValue(IServiceProvider) method, which actually returns the collection of enumeration values. Now, in our Xaml, we can specify an Enum as an ItemsSource very easily. Let’s say we have the following Enum.

namespace MarkupExtensionDemo
{
    public enum Priority
    {
        Low,
        Medium,
        High
    }
}

We can use it in our Xaml like this.

<UserControl 
             x:Class="MarkupExtensionDemo.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:Extensions="clr-namespace:MarkupExtensionDemo.Extensions"
             xmlns:local="clr-namespace:MarkupExtensionDemo">

    <ComboBox ItemsSource="{Extensions:Enum local:Priority}" />

</UserControl>

It’s important to note that you need to include your namespaces so the types can be resolved. When the markup extension is reached, it executes the ProvideValue(IServiceProvider) method and returns the array of enumeration values to use as the items source.

Windows Communication Foundation

I recorded an hour and a half presentation on Windows Communication Foundation yesterday that you can view on YouTube here. The video is recorded in 1920×1080, and is uploaded at that quality. The presentation covers everything from what WCF is, to creating your first service and client, as well as a few other advanced subjects.

Resources
YouTube: http://www.youtube.com/watch?v=jaHc1Lbki-A&hd=1
PowerPoint: Windows Communication Foundation.pptx
Source Code: Routing Services.zip