Newest Posts

Visual Studio 2012 RC is now available, and color changes in RTM.

Otherwise known as Visual Studio 11 during the beta period, you can now download the release candidate from Microsoft. The primary complaint during the beta was that the new light and dark themes had no color, they were purely monochrome style themes. Microsoft did listen, and they did add some color to the interface.

Visual Studio 11 Release Candidate

Visual Studio 11 Release Candidate

You can also see that they did change the all-caps titles on the tool windows, however they did seem to just move the all-caps to the main application menu, which most people still disagree with. Overall though its still the same great development environment, so download it and give a good run through.

It also appears that some of the changes didn’t make it into RC, specifically for the dark theme.

Visual Studio 11 RTM Dark Theme

Visual Studio 11 RTM Dark Theme

How to delete or drop all tables from a SQL Server database using just a SQL query.

The following SQL will delete all the tables and their associated information from a database.

USE [database]
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

The only downside to this is that you cannot perform a rollback, so you need to make sure this is what you want to do. Otherwise, that’s all there is to it. Just run this in a New Query Window in SQL Server Management Studio (SSMS) and you’re done.

Fixing the SyntaxHighlighter Evolved WordPress plugin’s font-size issues with Fluid-Blue theme.

For WordPress, Fluid-Blue is a popular theme amongst the technical community because its intrinsically great for writing technical articles. For posting code, I use the SyntaxHighlighter Evolved plugin. The problem is that the CSS for the Fluid-Blue theme conflicts with the CSS for the plugin.

There are two main conflicts with the theme and plugin.

  1. The syntax highlighter’s font size is too small
  2. The syntax highlighter’s lines in the left gutter and code don’t line up

I came across this blog post by Matthew Turland, which talks about fixing the font-size, and it does, but it does not fix the second issue with the lines matching up. After looking into the problem, it turns out that there are other elements of the syntax highlighter that need their font sizes adjusted as well.

You can modify the theme stylesheet directly, but instead we are going to create a child theme. The reason for this is to abstract our changes away from the original theme so we don’t have to deal with so much CSS.

To do this, go to your WordPress themes folder on your FTP (wordpress_root/wp-content/themes/) where wordpress_root is your domain and root path to your WordPress directory. Create a new folder and call it fluid-blue-syntaxhighlighter. You can actually call this whatever you want, but the idea is to be consistent with naming where fluid-blue is the name of the theme we want to derive from, and syntaxhighlighter is just the name of the child theme.

Next, create a new css file named style.css and use the following code.

/*Theme Name: 
  Fluid Blue (Custom)
  Template: fluid-blue
*/ 

@import url("../fluid-blue/style.css");

The CSS comment actually is a configuration section that does one simple thing; it tells WordPress the parent theme we are deriving from. Now we can apply the style fixes for the syntax highlighter plugin.

body .syntaxhighlighter a,
body .syntaxhighlighter div,
body .syntaxhighlighter code,
body .syntaxhighlighter table,
body .syntaxhighlighter table td,
body .syntaxhighlighter table tr,
body .syntaxhighlighter table tbody,
body .syntaxhighlighter table thead,
body .syntaxhighlighter table caption,
body .syntaxhighlighter textarea,
body .syntaxhighlighter .gutter {
    font-size: 12px !important;
    line-height: 13px !important;
}

Set the font-size to whatever you want it to be, and set the line-height to be either the same, or one pixel larger. I found that the alignment seemed to look the best with it increased by one pixel.

Now upload style.css to your child theme you created earlier.

The last step is to actually activate the theme. Go to your WordPress Appearance section, and click ‘Activate’ on your child theme. If your child theme does not appear, then you may not have created it in the correct location on your FTP.

Working with the WPF TextBlock control.

Introduction
Setting a TextBlock’s Content
Formatting Text
Using Controls with Formatted Text

Introduction

In WPF there are two very similar controls Label and TextBlock, and I’m going to cover TextBlock and why its so useful. First, what is the TextBlock control? A first look at the Msdn documentation.

Provides a lightweight control for displaying small amounts of flow content.

Well, that doesn’t tell that much about the control. A more accurate description would be that its a lightweight control for displaying various forms of formatted text and controls in a flow layout. Specifically, the TextBlock control can contain other controls, and arbitrary text that you can format with different font styles, colors, and brushes. Because it can contain other controls, it is actually much more than a `Text`Block, and I’m not sure why they named it TextBlock considering.

Setting a TextBlock’s Content

For demonstration, I will start with a small WPF Windows Application that contains just a TextBlock control containing the text Hello World!.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top"> 
            Hello World!
        </TextBlock>
    </Grid>
</Window>
TextBlockDemo_HelloWorld

An empty window with a TextBlock

There are two ways you can set text for a TextBlock. The first is the most obvious, and that is to set the Text property.

<TextBlock Text="Hello World!" HorizontalAlignment="Stretch" VerticalAlignment="Top">

The second is by setting the inner value of the control like I did in the demo application. Both methods give the same result for displaying Hello World!, but only setting the inner value of the TextBlock control gives us access to the true potential of the control. The Text property itself can only be used to display an arbitrary System.String. Shown below is the source code from the TextBlock metadata of its Text property.

//
// Summary:
//     Gets or sets the text contents of a System.Windows.Controls.TextBlock.
//
// Returns:
//     The text contents of this System.Windows.Controls.TextBlock. Note that all
//     non-text content is stripped out, resulting in a plain text representation
//     of the System.Windows.Controls.TextBlock contents. The default is System.String.Empty.
[Localizability(LocalizationCategory.Text)]
public string Text { get; set; }

Because the TextBlock can contain multiple controls by using its inner value, we can add things like buttons or other controls.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            Hello World!
            <Button Content="Click me!" />
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing text along with a Button control.

One of the most common questions from those just entering the WPF world is why doesn’t the button display on a new line even though in the Xaml the Button element is on its own line? Placing elements on a new line doesn’t necessarily do anything, and for a TextBlock control, adding a new line is actually done using the LineBreak element.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            Hello World!
            <LineBreak />
            <Button Content="Click me!" />
        </TextBlock>
    </Grid>
</Window>

A TextBlock control with text, a button, and a line break.

I won’t cover any more about nested controls in the TextBlock. Once you understand that a control can contain other controls, the rest depends on your understanding of understanding the layout and styling mechanisms of WPF. The usefulness of truly comes from the ability to format strings of text without using multiple controls.

Formatting Text

Formatting text is done using an element called a Run which is defined as a inline-level flow content element intended to contain a run of formatted or unformatted text. Using a Run, you can style seperate segments of text using colors, brushes, and styles.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Foreground="Red">Hello</Run>
            <Run Foreground="Blue">World!</Run>
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing the text 'Hello World!' split into two runs, one red and one blue.

You can see that it was very easy to style the text to be red and blue. Now let’s add a LinearGradientBrush to the second run and give it a larger font with a bold style.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Foreground="Red">Hello</Run>
            
            <LineBreak />
            
            <Run Text="World!" FontSize="24pt" FontWeight="Bold">
                <Run.Foreground>
                    <LinearGradientBrush StartPoint="0,1" EndPoint="0,0">
                        <GradientStop Offset="0" Color="Navy" />
                        <GradientStop Offset="1" Color="DodgerBlue" />
                    </LinearGradientBrush>
                </Run.Foreground>
            </Run>
        </TextBlock>
    </Grid>
</Window>

A TextBlock run with its Foreground set to a LinearGradientBrush

Just like the TextBlock, a Run can contain its text in either its Text property, or its inner value. Since we want to use its inner value to set some text effects, it was moved from the inner value to the Text property. The FontSize and FontWeight properties were also added, along with our Run.Foreground element that contains our linear gradient effect.

Using Controls with Formatted Text

Often times you may want to do something like have a piece of text actually contain a link to some resource. I had a need for this myself in one of my dialogs in my licensing modules; I need it to display a link to a product page. A TextBlock can contain both controls and runs, which makes for great flexibility. A Run however, cannot contain a control so its important to make note of that.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Text="This is some text containing a " />
            <Hyperlink NavigateUri="http://danderson.io/">link to a page.</Hyperlink>
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing a HyperLink.

The cool thing about this is that because a HyperLink is its own control, it can contain its own styling and behaviors.

There’s not much else to say about the TextBlock because it really is a simple control. It’s just really flexible and when used correctly can be a very easy way to display lots of formatted text to a user. The ability to contain controls that can also have their own styles and behaviors is really cool, but I still think the WPF team should have chosen a better name than TextBlock, because its much more than just arbitrary text.

Visual Studio 11 RC User Interface Updates, Developer Experience, and Color changes.

The Visual Studio team has posted some updates on the Visual Studio blog regarding the feedback we have all been providing them about the beta.

Personally, I don’t mind the new Visual Studio themes (the light and dark themes), but the thing I don’t like is that Microsoft has seemed to forget that UX guidelines exist (including their own UX guidelines). The community of developers provided their feedback how they disliked the all-caps docking window titles, and Microsoft did listen and fix it, but it seems like that didn’t matter because they went and changed the main menu’s to all-caps instead. Instead of really fixing the problem, they really just moved it to a different part of the UI. I really hope this changes in the RC, and I really hope it gets fixed before RTM.

Visual Studio 11 Beta

Visual Studio 11 Beta

Visual Studio 11 Release Candidate

Visual Studio 11 Release Candidate

The two images above are a comparison between the two interfaces from beta to release candidate, and there isn’t that much change. Color was added, but it is minimal. For anyone who has done graphics in Photoshop, looking at the images you know that the amount of work that went into the color changes was almost none. We’ll have to wait and see what will become of Visual Studio 11 by RTM based on the communities feedback.

In my own opinion, it really seems like Microsoft is promoting the idea of Metro into all their products. And again in my opinion, I really dislike the Metro ideology. From a developer standpoint, it seems like going back to Windows 3.1 with interfaces dumbed down and restricted for non-power users, and from a customer standpoint its threatening the desktop business environment. It seems that the industry might be headed in the wrong direction with UX patterns. The stuff going on under the hood and all the plumbing written by developers is still some of the most amazing work we’ve seen in the industry to date, but the way all that hard work is being portrayed as display is worrisome.

There are lots of mixed feelings and opinions from developers about Windows 8, Metro, Visual Studio 11, and even the new Microsoft Office in the works, but I hope that the majority developer feedback takes precedence and that Microsoft listens to its oldest, most valuable customers: software developers.

Avoiding a deadlock when creating a STA thread and using Dispatcher.

I have always been pretty articulate and careful when writing multi-threading code, but today I wrote my first deadlock that had me baffled for a few minutes. I’m working on a licensing dll that handles a lot of processing, and it also handles some user interface display using WPF Windows. I cannot guaruntee whether or not the calling thread will be a single-threaded apartment, because the assembly that implements it might be a console or a window, but the assembly doesn’t know which, or which threading model it uses. The good news is that System.Threading provides very rich types to be able to check for this as well as handle it.

First lets take a look at actually checking for the threading model, and creating an STA thread if needed.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    Thread thread = new Thread(() => {
        // ...
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

You can see that the code to check for the current threading apartment isn’t anything hard, and neither is setting the apartment state. Now my requirement was that the WPF Window be shown modal by calling Window.ShowDialog so I could consume the DialogResult and continue processing in the licensing service. To do this I created the Window in the newly created STA thread.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    ActivateWindowController controller = new ActivateWindowController();
    ActivateWindow window = null;

    bool? dialogResult = null;

    Thread thread = new Thread(() => {
        window = new ActivateWindow(controller);
        dialogResult = window.ShowDialog();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

There’s nothing too exciting about any of this either. I’m using the Model-View-Controller (MVC) pattern so I have a ActivateWindowController that gets passed to the ActivateWindow constructor. Because we need the Window to run in a single-threaded apartment, I do the actual instantiation in the new Thread. Then I make a call to ShowDialog() and consume the result. The last bit is adding thread.Join(); so the calling thread is blocked until the new thread terminates, which is when the dialog is closed.

Now I’ll try to explain what ActivateWindowController does as best as I can. When ActivateWindow is loaded, the WPF stack invokes the Loaded event handler. The code isn’t anything special, so I’ll just show it.

public partial class ActivateWindow : Window
{
    /// <summary>
    /// Initializes a new instance of the DCOMProductions.Licensing.Windows.LicenseWindow class.
    /// </summary>
    public ActivateWindow(ActivateWindowController controller) {
        InitializeComponent();
        _controller = controller;
    }

    #region Controller Members

    private ActivateWindowController _controller;

    private void Window_Loaded(object sender, RoutedEventArgs e) {
        _controller.ActivateComplete += ActivateComplete;
        _controller.Activate();
    }

    private void ActivateComplete(object sender, ActivateWindowController.ActivateEventArgs e) {
        DialogResult = e.Result == ActivationResult.Passed ? true : false;
    }

    #endregion
}

When the Loaded event handler is invoked, a call to ActivateWindowController.Activate() is made. What this method does is spin off a new Task by calling Task.Factory.StartNew(...) and consumes a WCF service. In short, it means another thread. When the task completes, it invokes Task.ContinueWith(...) which is responsible for wrapping up the result and delegating everything to the proper thread.

.ContinueWith((task) => {
    CloseDialogCallback method = new CloseDialogCallback(() => {
        OnActivateComplete(new ActivateEventArgs(result));
    });
    _Dispatcher.BeginInvoke(method, null);
});

Now it is important to note here that _Dispatcher is a private instance that was initialized in the constructor of ActivateWindowController. In short, the dispatcher lives on the UI thread of the Window. The dispatcher is required to delegate calls to the correct thread, in this case we want to delegate the callback method to the UI thread. And remember, the UI thread is the STA thread I created earlier.

I highlighted the last line, because this is where the deadlock is introduced. When _Dispatcher.BeginInvoke(method, null); is called, it schedules asynchronously the callback to be executed on the thread that the dispatcher was created on. And remember, the thread that _Dispatcher was created on is the same thread that the ActivateWindowController instance was created on. Let’s double check that.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    ActivateWindowController controller = new ActivateWindowController();
    ActivateWindow window = null;

    bool? dialogResult = null;

    Thread thread = new Thread(() => {
        window = new ActivateWindow(controller);
        dialogResult = window.ShowDialog();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

Well, hopefully by now you realize the problem and why there is a deadlock. ActivateWindowController is not being instantiated on our STA thread. So what’s happening here is when _Dispatcher.BeginInvoke is called, it is scheduling the callback to execute on the same thread we told to block by calling thread.Join(). Because that thread is blocked and the dialog can’t return until the callback is executed by the dispatcher, I have a blocked thread and a scheduled callback that will never run; eg. a deadlock.

The fix is to instantiate ActivateWindowController on the STA thread I created which is where we want the dispatcher to delegate the callback to anyway. This resolves the deadlock problem. It’s important to watch out for little quirks like this. It didn’t take me long to realize what created the deadlock, but I think on most days it would have taken me much longer to figure it out. The most important thing to remember is that this is not specific to a Dispatcher, and that it applies to multi-threading regardless.

Showing a splash screen in WPF from an external assembly or class library.

This isn’t anything special, but the documentation on Msdn for System.Windows.SplashScreen is lacking. Basically I am writing a licensing system and during debugging the WPF stack can take many seconds to load. When making changes to this system sometimes it may result in a failure, but I may not see it for a few seconds. I wanted something to display during this time period so I know at least something is going on.

I knew that WPF has built-in support for splash screens by setting the Build Action of an image in my project to Splash Screen in the properties window, but the problem is that this only works for the project the image is embedded into, and only if its a WPF Application project. My requirements are that I can display the splash screen from my licensing dll (class library) when my licensing service is invoked. This means that the licensing dll would contain the image to display, and contain the logic to show the splash.

Luckily, SplashScreen exposes a SplashScreen(Assembly, String) constructor which allows you to do just this. To accomplish this task, all you need to do is add your image to your class library project, set its build action to Splash Screen, and then write three lines of code.

Assembly asm = Assembly.GetAssembly(GetType());
SplashScreen splash = new SplashScreen(asm, "SplashScreen.png");
splash.Show(true);

The first line is simple; we are just getting the assembly that contains the splash resource (in this case my licensing library). The second line takes the assembly as an argument, and we pass in the name of the image. Next we simply call splash.Show(true); which actually displays the image, and because we passed in true as the argument, it will automatically be closed by the WPF stack once the first window is constructed, loaded, and displayed.

Make sure that you add your image to the root of your project, so that the WPF stack can find it.

I haven’t looked into it because I don’t want to spend a lot of time on a task that doesn’t mean much, but placing the image at other hierarchical locations in your project structure can cause the embedded resource path string to change, and it may not be found by the WPF stack internally. It’s probably possible to specify a qualified path using the second constructor parameter, but I was not able to get it to work using a fully qualified resource path string.

Getting a stream to a resource without copying the contents into memory.

If you have ever added a resource file to your project through the Project Properties > Resources tab, then you have used a ResourceManager. The resource manager allows you to access resources in your application simply through a static resource manager. This line of code should look familiar.

string message = Properties.Resources.MyDialogText;

This is not just convenient, it’s just plain easy. The problem is that when something is just plain easy, there are often tradoffs, and here there is a big one. Let’s assume we have a binary resource (a file) that is 7764480 bytes (7.40 megabytes) called ‘Bootstrapper.exe’. Now normally you would get the resource just by doing byte[] bytes = Properties.Resources.Bootstrapper. What happens here is you are invoking an instance of ResourceManager that returns the bytes to our Bootstrapper.exe file. The tradoff of such an easy way of getting the resource, is that it just created a copy of the data into memory, adding 7.40 megabytes to our application’s Working Set memory. Let’s look at a bare-bone sample application.

namespace ResourceManagerSample
{
    using System;

    internal static class Program
    {
        public static void Main(string[] args) {
            Byte[] bytes = Properties.Resources.Bootstrapper;
        }
    }
}

Stepping through this code and stopping on line 11, just before the statement is executed, the application’s working set is 47,964 bytes. Execute the statement by stepping to the end of the method body, and the working set just increased from 47,964 bytes to 63,364 bytes. What happened is the ResourceManager just returned us a copy of the binary resource contents. If you were working with a binary resource that was say, a gigabyte in size, your application’s working set memory would have just increased by a gigabyte.

Let’s take a look at why this happens by looking at the internals of the ResourceManager class. The two main methods we are interested in are Object GetObject(String, CultureInfo, Boolean) and UnmanagedMemoryStream GetStream(String, CultureInfo).

private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMemStream) {
    ...
    Object value = rs.GetObject(name, _ignoreCase);
    ... 
}

I stripped the method down to the important line, which is rs.GetObject(name, _ignoreCase);. What happens here is the ResourceManager makes a call to ResourceSet.GetObject, which is what actually gets the resource as a System.Object. The internals of the ResourceSet are not that interesting either, because all it does is get the object from a HashTable.

public virtual Object GetObject(String name, bool ignoreCase)
{
    Hashtable copyOfTable = Table;  // Avoid a race with Dispose
    if (copyOfTable == null) 
        throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
    if (name==null) 
        throw new ArgumentNullException("name"); 

    Object obj = copyOfTable[name]; 
    ...
    return caseTable[name];
}

As you can see, the public call in ResourceManager simply calls into ResourceSet which returns the actual resource as an object. Because its returning the actual object, memory is allocated for the resource, thus increasing our working set. I won’t show the internals of ResourceManager.GetStream because all that does is actually make a call to GetObject as well, so it boils down to the same thing. The difference is that GetObject can return just an object (a System.String for example), or it can return an UnmanagedMemoryStream. GetStream obviously only returns a stream.

Intrinsically the problem is that ResourceManager creates a heavy memory footprint, and it isn’t flexible enough to grab only a pointer to the resource instead of an actual instance copy. We can get around this problem by using embedded resources.

Embedded resources are embedded into the assembly manifest at compile-time and accessible directly through the assembly. Working with ResX resource files, resources are still embedded but are accessible through a ResourceManager which I already discussed. ResX resources are not available directly through the assembly such as calling Assembly.GetManifestResourceNames. In either case, resources still get embedded to the assembly at compile-time, but each is accessible in a different way.

With avoiding using a ResX resource file and ResourceManager, you can set the Build Action of the resource by right-clicking the file, and setting Build Action in the properties Window to Embedded Resource.

It’s important that you do not use a ResX resource file and set the resource to embedded. This will result in you having the same resource embedded twice, increasing the size of your assembly 2x.

With embedded resources, we can access them by using the Assembly class, and calling Assembly.GetManifestResourceNames() and Assembly.GetManifestResourceStream(String).

private static UnmanagedMemoryStream GetResourceStream(String name) {
    Assembly assembly = Assembly.GetExecutingAssembly();

    string[] resources = assembly.GetManifestResourceNames();
    string resource = resources.SingleOrDefault(r => r.EndsWith(name, StringComparison.CurrentCultureIgnoreCase));

    if (resource == null) {
        throw new System.ArgumentException("The specified resource does not exist in the assembly manifest.", "name");
    }

    return (UnmanagedMemoryStream)assembly.GetManifestResourceStream(resource);
}

It’s important to note how embedded resource names are stored in the manifest. When you set the build action on a file in your project to Embedded Resource, a resource name is created in the manifest that uniquely identifies the resource. The name will take on the project and foldier hierarchy and is in the format of a namespace. If the Bootstrapper.exe resource is in the root directory of the project named RresourceManagerSample, the resource identifier will be ResourceManagerSample.Bootstrapper.exe. And if you had it in a subfolder of the project called Resources it would be ResourceManagerSample.Resources.Bootstrapper.exe.

In the example method I wrote it takes a System.String name parameter, and checks the end of each resource string for a match, and throws a System.ArgumentException if the resource does not exist. The rest of the method is simple, because it just returns an UnmanagedMemoryStream by calling assembly.GetManifestResourceStream().

The whole point of this is that by using embedded resources and reflection, we get the resource as an UnmanagedMemoryStream without having the entire resource copied into memory. Before when using a ResourceManager remember that it would copy the entire resource into memory. This method does not do that, and looking at the internals of Assembly.GetManifestResourceStream() tells us why.

internal unsafe virtual Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) 
{ 
    ulong length = 0;
    byte* pbInMemoryResource = GetResource(name, out length, ref stackMark, skipSecurityCheck); 

    if (pbInMemoryResource != null) {
        if (length > Int64.MaxValue) 
            throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63"));
        return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read, true); 
    }

    return null; 
}

You can immediately see that instead of obtaining an instance copy of the resource, you get a nice pointer to the resource instead. Looking further into the implementation you can see that the call to GetResource actually makes a call to an external method called _GetResource.

[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe extern byte* _GetResource(String resourceName, out ulong length,
                                        ref StackCrawlMark stackMark, 
                                        bool skipSecurityCheck);

If you don’t know what extern does, it is easily explained in 10.6.7 of the C# specification.

When a method declaration includes an extern modifier, that method is said to be an external method. External methods are implemented externally, typically using a language other than C#.

Unfortunately this means I cannot show you the source to _GetResource, but its likely to be in native C++. The most important aspect of GetManifestResourceStream() is that it returns a pointer to the resource, rather than a instance copy like ResourceManager does. Because of this, the contents of our Bootstrapper.exe resource need not be fully loaded and the magic happens in some external C++ code.

Thanks to such magic under the hood, we can now call our method just as easily as using a ResourceManager.

namespace ResourceManagerSample
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    internal static class Program
    {
        private static UnmanagedMemoryStream GetResourceStream(String name) {
            Assembly assembly = Assembly.GetExecutingAssembly();

            string[] resources = assembly.GetManifestResourceNames();
            string resource = resources.SingleOrDefault(r => r.EndsWith(name, StringComparison.CurrentCultureIgnoreCase));

            if (resource == null) {
                throw new System.ArgumentException("The specified resource does not exist in the assembly manifest.", "name");
            }

            return (UnmanagedMemoryStream)assembly.GetManifestResourceStream(resource);
        }

        public static void Main(string[] args) {
            UnmanagedMemoryStream stream = GetResourceStream("Bootstrapper.exe");
        }
    }
}

Except now stepping through the code, you can step through to the end of the method body and see that the UnmanagedMemoryStream is instantiated and to the appropriate size, but our working set memory has not allocated anything extra. How we can allocate memory by reading data from our stream as needed.

public static void Main(string[] args) {
    UnmanagedMemoryStream stream = GetResourceStream("Bootstrapper.exe");

    byte[] buffer = new byte[stream.Length];

    stream.Read(buffer, 0, buffer.Length);
}

Stepping through the code and stopping at stream.Read(buffer, 0, buffer.Length); just before the statement executes will show that our working set has remained the same. Executing the statement reads the contents into our buffer allocating memory as its read. Only reading from the stream will increase our working set as we need the resource bytes. This is much more efficient than using a ResourceManager, and not hard to implement.

The question now is when to use a ResourceManager with ResX files, and when to use embedded resources. I’ve not benchmarked one or the other in terms of speed performance, but the whole point was about memory footprint. You should definitely use a ResourceManager if your resources are small, short lived, and you need the ease of being able to access them directly through the ResourceManager class, and by calling GetObject and GetStream. If your resources are very large and your application’s working set memory might be an issue, you will want to use embedded resources and reflection.

Generally in a project you will use one or the other, and seldom both types of resources, but there isn’t anything wrong with using both types. It all depends on your requirements, and neither or solves every problem. The trick is picking which one is best for your requirements, just like picking an appropriate programming language to solve a problem.

When is it appropriate to override ToString?

Microsoft .NET

This question was asked on StackOverflow. Because my answer was upvoted well, I decided include it as a blog post.

First, let’s talk about what ToString actually is. The ToString method lives in System.Object, and because System.Object is the base class for all objects in C#, all objects have the ToString method. Some objects expose ToString overloads that accept parameters like CultureInfo, or formatting options, but for the most part most objects will have the default overload that accepts no parameters.

ToString was designed to do one thing: display a representation of an objects state. This is explicitly why it lives in System.Object. That is the only use for ToString, and it should be used. It should not be used to do anything else like change an objects state or apply behaviors.

These are the official guidelines from the .NET Development Series from Microsoft, specifically included in the Framework Design Guidelines book. I highly recommend you buy and read it in full, multiple times.

AVOID throwing exceptions from ToString

CONSIDER returning a unique string associated with the instance.

CONSIDER having the output of ToString be a valid input for any parsing methods on this type.

DO ensure that ToString has no observable side effects.

DO report security-sensitive information through an override of ToString only after demanding an appropriate permission. If the permission demand fails, return a string excluding security-sensitive information.

The Object.ToString method is intended to be used for general display and debugging purposes. The default implementation simply provides the object type name. The default implementation is not very useful, and it is recommended that the method be overridden.

DO override ToString whenever an interesting human-readable string can be returned. The default implementation is not very useful, and a custom implementation can almost always provide more value.

DO prefer a friendly name over a unique but not readable ID.

DO try to keep the string returned from ToString short. The debugger uses ToString to get a textual representation of an object to be shown to the developer. If the string is longer than the debugger can display, the debugging experience is hindered.

DO string formatting based on the current thread culture when returning culture-dependent information.

DO provide overload ToString(string format), or implement IFormattable, if the string return from ToString is culture-sensitive or there are various ways to format the string. For example, DateTime provides the overload and implements IFormattable.

DO NOT return an empty string or null from ToString

Understanding types passed by value or by reference, and what it means to pass a reference type by reference.

Microsoft .NET

Overview. The goal of this article is to explain the mechanisms of passing structures and classes around in code. It will cover areas such as what it means to pass by value, pass by reference, as well as the unique behaviors that structures and classes present. It is recommended that you have at least a basic understanding that a structure is a value type, and a class is a reference type, and what each of those means. A brief definition of each is provided in the next section for terminology, but does not go into much detail.

Terminology. I will try to use these terms precisely and consistantly to prevent as much confusion as possible.

(1) Types. When speaking about structures and references (eg. value types and reference types) both collectively, I will refer to them as types. This will mean that the context applies to both a value type (struct) and a reference type (class).

(2) Value Type. A value type is a struct in C#. Value types directly store their data, and modifying a value type affects only the copy in which you are modifying.

(3) Reference Type. A reference type is a class in C#. Unlike value types, reference types do not directly store their data. Instead, they store a reference to their data, and modifying a reference type modifies the data that it references. Other reference types that reference the same data in memory will also reflect the change.

(4) Pass/Passing by Reference. Refers to passing in a variable as an argument to a method parameter using the ref and out keywords.

Types are passed by value by default. In C# by default, types are passed into method parameters by value. This means that instead of using a pointer that points to the original storage location in memory, a copy of the type is made in a new storage location.

It is important to understand that value types and reference types have different symantics when passed into a method by value.

(1) Value Type. When a value type is passed by value, a copy of the type is created and any changes to the copy only affect the copy itself; the original type passed in is preserved.

namespace CSharpDemo
{
    using System.Diagnostics;

    /// <summary>
    /// Simple mutable xy value type
    /// </summary>
    internal struct Point
    {
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        private int x;
        private int y;

        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }

    internal class Program
    {
        public static void Main(string[] args) {
            int x = 0;
            int y = 0;

            Point p = new Point(x, y);

            OffsetByOne(p);

            Debug.WriteLine(p.X);
            Debug.WriteLine(p.Y);
        }

        private static void OffsetByOne(Point point) {
            point.X++;
            point.Y++;
        }
    }
}

In the example above, we are creating an instance of our value type with x and y values of 0 and passing it as an argument to the OffsetByOne(Point) method. Because the default parameter passing mechanism is by value in C#, a copy of our value type is created. The method will increment both X and Y by one, but it is only modifying the copy; the original point we passed in as an argument is preserved. Because of this behavior, printing the contents p.X and p.Y in the Main(string[]) method will both print 0.

(2) Reference Type. A reference type is simply a reference to a underlying type in memory. Unlike a value type, a reference type does not store its own value, rather it is a pointer to the actual value in memory.

namespace CSharpDemo
{
    using System.Diagnostics;

    /// <summary>
    /// Simple mutable xy reference type
    /// </summary>
    internal class Point
    {
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        private int x;
        private int y;

        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }

    internal class Program
    {
        public static void Main(string[] args) {
            int x = 0;
            int y = 0;

            Point p = new Point(x, y);

            OffsetByOne(p);

            Debug.WriteLine(p.X);
            Debug.WriteLine(p.Y);
        }

        private static void OffsetByOne(Point point) {
            point.X++;
            point.Y++;
        }
    }
}

In the example above note it is the same as the previous example, except that we changed our Point definition from a struct (value type) to a class (reference type). We are creating an instance of our reference type with x and y values of 0 and passing it as an argument to the OffsetByOne(Point) method.

Because the default parameter passing mechanism is by value in C#, a copy of our reference type is created. The method will increment both X and Y by one, and because the copy references the same underlying data in memory as the original type passed in, both references will reflect the change. Because of this behavior, printing the contents p.X and p.Y in the Main(string[]) method will both print 1.

This is where a lot of confusion comes from if you don’t quite understand the symantics of a reference type. A type being a reference type does not mean you are passing by reference, you are still passing by value, and it is important to recognize the difference.

Passing types by reference. Passing types by references can be done two ways. The first method is using the ref keyword, and the second is using the out keyword. It is crucial to know that out is actually identical to ref, but with stronger rules. The out keyword actually gets mapped to the ref keyword in the CLR, but with special metadata for the rules it has.

Both the ref and out keywords do not create new storage locations. Instead, they represent the same storage location as the type given as the argument in the function member. It is important to understand that this is actually a pointer.

Because using ref and out means you are actually using a pointer parameter, it is important to know that when passing a reference type by reference, you are actually creating a double pointer, pointer to pointer, or double indirection. This is because a reference type itself is a pointer to a storage location in memory. It is highly recommended to have some knowledge and understanding of how pointers work before deciding whether passing a type, especially a reference type by reference is actually necessary.

(1) ref. A reference type must be definitely assigned before it can be passed as a reference parameter. Because of this rule, a reference parameter is always considered initially assigned within a function.

namespace CSharpDemo
{
    using System.Diagnostics;

    /// <summary>
    /// Simple mutable xy value type
    /// </summary>
    internal struct Point
    {
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        private int x;
        private int y;

        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }

    internal class Program
    {
        public static void Main(string[] args) {
            int x = 0;
            int y = 0;

            Point p = new Point(x, y);

            OffsetByOne(ref p);

            Debug.WriteLine(p.X);
            Debug.WriteLine(p.Y);
        }

        private static void OffsetByOne(ref Point point) {
            point.X++;
            point.Y++;
        }
    }
}

Make note that in the example above we are working with a value type again, and that there are two key changes. The first change is that we added a reference parameter to our OffsetByOne(Point) method, which changes the signature to OffsetByOne(ref Point). The second change is our calling syntax has changed by also adding the ref keyword. This convention is that of passing a type by reference using the ref keyword.

For a value type, passing by reference means that you get reference type symantics. By passing our value type by reference, OffsetByOne(ref Point) will actually modify the value of the original type passed in. The behavior of this is that printing the contents of p.X and p.Y in Main(string[]) will now both print the value of 1.

Now because passing a reference type by reference means using a double pointer, pointer to pointer, or double indirection, I will cover passing a reference type by reference later in the article.

(2) out. As I stated earlier, the rules for out are much stronger. A type does not need to be definitely assigned before it can be passed as an argument.

It’s important to note here that if you do assign your type before passing it as an argument using the out keyword, don’t expect your value to be retained.

I urge the point above because when using the out keyword, it is required that the type passed in as an argument be definitely assigned before the method returns normally. This means that no matter what, the type that you passed in will be assigned a new value, overwriting any old value that was there.

Parameters passed in via out, are actually considered output parameters. These should be treated as additional return values, so treat it with return type symantics.

namespace CSharpDemo
{
    using System.Diagnostics;

    /// <summary>
    /// Simple mutable xy value type
    /// </summary>
    internal struct Point
    {
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        private int x;
        private int y;

        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }

    internal class Program
    {
        public static void Main(string[] args) {
            int x = 0;
            int y = 0;

            Point p = new Point(x, y);

            OffsetByOne(out p);

            Debug.WriteLine(p.X);
            Debug.WriteLine(p.Y);
        }

        private static void OffsetByOne(out Point point) {
            int x = 1;
            int y = 1;

            point = new Point(x, y);

            point.X++;
            point.Y++;
        }
    }
}

The only difference between this example and the ref example, is that we are using the out keyword and I have updated the OffsetByOne(out Point) method body. Note that because we must definitely assign the parameter named point before the method returns, we are assigning it a new Point with a XY values of 1. Because when passing a value type by reference we get reference type symantics, printing the value of our type in Main(string[]) will yield XY values of 2.

Again, out and ref are the same, but out should be treated as an extra return value. With ref you can always expect your value to either be changed, or unchanged, but with out you should expect a completely new value each time just as if you were consuming a normal return value from a method.

Passing a reference type by reference. Hopefully by the time you get to this part you already have an idea of what I’m about to say. It’s not complicated. The importance here is that you simply understand the symantics of a reference type itself, and that passing a reference type does not automatically mean passing by reference.

At any rate, I hope you enjoyed the article and that it provided some insight.