Debugging IIS Express website from a HyperV Virtual Machine

Recently, I had to investigate a performance bug on a website when using Internet Explorer 8. Although we are fortunate to have access to BrowserStack for testing, I have not found it particularly efficient for performance investigations, so instead I used an HyperV virtual machine (VM) from modern.IE.

I had started the site under test from Visual Studio 2013 using IIS Express. Unfortunately, HyperV VMs are not able to see such a site out-of-the-box. Three things must be reconfigured first: the VM network adapter, the Windows Firewall of the host machine, and IIS Express.

HyperV VM Network Adapter

HyperV Virtual Switch Manager
HyperV Virtual Switch Manager

In HyperV, select Virtual Switch Manager… from the Actions list on the right-hand side. In the dialog that appears, select New virtual network switch on the left, then Internal on the right, then click Create Virtual Switch. This creates a virtual network switch that allows your VM to see your local machine and vice versa. You can then name the switch anything you want; I called mine LocalDebugNet.

New virtual network switch
New virtual network switch

To ensure the VM uses the newly created virtual switch, select the VM and choose Settings… (either from the context menu or the lower-right pane). Choose Add Hardware in the left-hand pane and add a new Network Adapter, then drop down the virtual switch list on the right, choose the switch you created earlier, and click OK to accept the changes and close the dialog.

Add network adapter
Add network adapter
Set virtual switch on network adapter
Set virtual switch on network adapter

Now the VM is setup and should be able to see its host machine on its network. Unfortunately, it still cannot see the website under test. Next, we have to configure IIS Express.

IIS Express

Open up a command prompt on your machine (the host machine, not the VM) and run ipconfig /all . Look in the output for the virtual switch that you created earlier and write down the corresponding IP address1.

Command prompt showing ipconfig
Command prompt showing ipconfig

Open the IIS Express applicationhost.config file in your favourite text editor. This file is usually found under your user profile.

notepad %USERPROFILE%\documents\iisexpress\config\applicationhost.config

Find the website that you are testing and add a binding for the IP address you wrote down earlier and the port that the site is running on. You can usually just copy the localhost binding and change localhost to the IP address or your machine name.

You will also need to run this command as an administrator to add an http access rule, where <ipaddress>  should be replaced with the IP you wrote down or your machine name, and <port>  should be replaced with the port on which IIS Express hosts your website.

netsh http add urlacl url=http://<ipaddress>:<port>/ user=everyone

At this point, you might be in luck. Try restarting IIS Express and navigating to your site from inside the HyperV VM. If it works, you are all set; if not, you will need to add a rule to the Windows Firewall (or whatever firewall software you have running).

Windows Firewall

The VM can see your machine and IIS Express is binding to the appropriate IP address and port, but the firewall is preventing traffic on that port. To fix this, we can add an inbound firewall rule. To do this, open up Windows Firewall from Control Panel and click Advanced Settings or search Windows for Windows Firewall with Advanced Security and launch that.

Inbound rules in Windows Firewall
Inbound rules in Windows Firewall

Select Inbound Rules on the left, then New Rule… on the right and set up a new rule to allow connections the port where your site is hosted by IIS Express. I have shown an example here in the following screen grabs, but use your own discretion and make sure not to give too much access to your machine.

New inbound port rule
New inbound port rule
Specifying rule port
Specifying rule port
Setting rule to allow the connection
Setting rule to allow the connection
Inbound rule application
Inbound rule application
Naming the rule
Naming the rule

Once you have set up a rule to allow access via the appropriate port, you should be able to see your IIS Express hosted site from inside your VM of choice.

As always, if you have any feedback, please leave a comment.

  1. You can also try using the name of your machine for the following steps instead of the IP []

Analogue Trello using dry erase magnetic labels

My wife and I are terrible at chores. We are terrible at planning for them, balancing them (with other tasks and each other), and performing them. We have been terrible for a long time and we have finally accepted it. To mitigate our ineffectiveness, we tried Trello, but all that did was create a new chore, Check Trello, that we promptly forgot to do.

What we wanted was an analogue approach to Trello that would sit on our wall and scream "Do your chores!" at us in a way that we could not ignore. So Chrissy drew up a simple chart on a dry erase board in our kitchen using a list of chores we had created together. This was great. We were finally remembering to get things done, but it was not perfect. We often needed to rearrange chores to adjust for various scheduling conflicts, but erasing them just to rewrite them elsewhere on the board was tedious. Especially so if it meant reorganizing other chores to make things fit.

Our implementation of Trello was flawed.

As a fix for this organisational deficiency, the blank equivalent of poetry fridge magnets came to mind. Dry erase magnets that could be edited and rearranged with ease. I found some ready made solutions on the Internet, but I was not sure that they would fit exactly what we needed, so I went hunting around the local office supply stores. Eventually, thanks to the helpful manager of our local OfficeMax, I came up with a plan to make my own using business card sized magnets and some dry erase tape.

Equipment for creating analogue Trello
Equipment for creating analogue Trello

To make them, I carefully peeled the backing from the business card magnets a little to reveal the adhesive. I then peeled the backing off the dry erase tape a little and lined up the tape with the card, adhesive to adhesive. I then applied the tape to the cards, carefully avoiding any bubbles (usually) and trimming the tape to size.

A business card magnet with backing
A business card magnet with backing
The backing partly peeled back from the magnet
The magnet backing partly peeled back to reveal the adhesive
Applying the dry erase tape
Applying the dry erase tape
A magnet with dry erase tape applied
A magnet with dry erase tape applied

Once I had applied the tape to all of the magnets, Chrissy divided them up into a range of sizes1.

The finished dry erase magnets
The finished dry erase magnets

Then, with all the magnets backed by dry erase tape and cut to the sizes we wanted, Chrissy set up our new chore board.

Our finished chore board
Our finished chore board
  1. We had tried to trim some of the magnets to useful sizes and to remove any exposed adhesive, but we never found a way to do this well []

Resolving XML references from embedded resources

Recently, I wanted to validate some XML via an XSD schema. Due to some product constraints and intentions regarding versioning, the schema is an embedded resource and is referenced via the noNamespaceSchemaLocation attribute.

When loading XML in .NET, you can specify an XmlResolver via the XmlReaderSettings . As stated in MSDN, the default uses a new XmlUrlResolver without credentials. This works great when the file is local on disk, but not when it is squirreled away inside my resources.

What I needed was a special version of XmlResolver that understood how to find my embedded schemas. So I created a derivation, XmlEmbeddedResourceResolver, to do just that.

public class XmlEmbeddedResourceResolver : XmlUrlResolver
{
	public XmlEmbeddedResourceResolver( Assembly resourceAssembly )
	{
		_resourceAssembly = resourceAssembly;
	}

	public override object GetEntity( Uri absoluteUri, string role, Type ofObjectToReturn )
	{
		if ( absoluteUri == null ) throw new ArgumentNullException( "absoluteUri", "Must provide a URI" );

		if ( ShouldAttemptResourceLoad( absoluteUri, ofObjectToReturn ) )
		{
			var resourceStream = GetSchemaStreamFromEmbeddedResources( absoluteUri.AbsolutePath );
			if ( resourceStream != null )
			{
				return resourceStream;
			}
		}
		return base.GetEntity( absoluteUri, role, ofObjectToReturn );
	}

	public override async Task<object> GetEntityAsync( Uri absoluteUri, string role, Type ofObjectToReturn )
	{
		if ( absoluteUri == null ) throw new ArgumentNullException( "absoluteUri", "Must provide a URI" );

		if ( ShouldAttemptResourceLoad( absoluteUri, ofObjectToReturn ) )
		{
			var resourceStream = await GetSchemaStreamFromEmbeddedResourcesAsync( absoluteUri.AbsolutePath );
			if ( resourceStream != null )
			{
				return resourceStream;
			}
		}

		return await base.GetEntityAsync( absoluteUri, role, ofObjectToReturn );
	}

	private static bool ShouldAttemptResourceLoad( Uri absoluteUri, Type ofObjectToReturn )
	{
		return ( absoluteUri.Scheme == Uri.UriSchemeFile && ofObjectToReturn == null || ofObjectToReturn == typeof( Stream ) || ofObjectToReturn == typeof( object ) );
	}

	private Stream GetSchemaStreamFromEmbeddedResources( string uriPath )
	{
		var schemaFileName = Path.GetFileName( uriPath );
		var schemaResourceName = _resourceAssembly.GetManifestResourceNames().FirstOrDefault( n => n.EndsWith( schemaFileName ) );
		if ( schemaResourceName != null )
		{
			return _resourceAssembly.GetManifestResourceStream( schemaResourceName );
		}
		return null;
	}

	private Task<object> GetSchemaStreamFromEmbeddedResourcesAsync( string uriPath )
	{
		return Task.Run( () => (object)GetSchemaStreamFromEmbeddedResources( uriPath ) );
	}

	private readonly Assembly _resourceAssembly;
}

When asked to find a file-based reference, this steps in and looks in embedded resources first for a file of the same name. Since the file could be namespaced anywhere in the resources, I opted to look for any resource in any namespace with the same file name. If it is there, it loads it, otherwise it defers to the base implementation. This means there is no easy way to override the embedded file with a local one; however, that could be redressed by calling the base implementation first and then only searching embedded resources if that failed.

Note that I also implemented the async methods. I am certain my implementation is a little naive, but it generally works. Just be careful if you allow this to be used asynchronously as I discovered you can very easily create a deadlock when used in conjunction with locks. This is not necessarily a caveat of my implementation, but of asynchronous programming in general.

Hopefully, others will find this useful. Let me know in the comments if you use this or something similar.

Unsplash: Completely free images for whatever you want

I recently made the decision to have a featured image for each of my blog entries. The intention was to make things more consistent and easier on the eye. Sometimes, the image to use was immediately obvious and I would get it from my personal photos, at other times, it was not so easy.

Thankfully, my good friend and exceptional designer, Terrance Robb came to the rescue by introducing me to Unsplash. Unsplash is a service that posts ten stock images every ten days. These are high resolution images licensed under Creative Commons Zero, and as such, are completely free to use as you see fit.

Unsplash | Free Stock Photos

Why use Unsplash? Well, when someone puts professional, copyrighted images on the Internet without the permission of the owner, it directly impacts that owner's ability to make money from that work.  I like Unsplash because it encourages people to do the right thing with regards to copyright. Rather than resort to stealing copyrighted images with a right-click, Save As…1, Unsplash provides a free source of images for those who cannot afford professional alternatives. Not only that, but the licensing terms are completely unambiguous. There is no hunting for the appropriate attribution information or license information, you know exactly what your getting with these images.

So, next time you need inspiration or want an image for your presentation or blog and don't have the budget to pay for a professional stock (or custom) photo, don't steal; check out Unsplash.

  1. come on, you know you have done it []

Caching with LINQPad.Extensions.Cache

One of the tools that I absolutely adore during my day-to-day development is LINQPad . If you are not familiar with this tool and you are a .NET developer, you should go to www.linqpad.net right now and install it. The basic version is free and feature-packed, though I recommend upgrading to the professional version. Not only is it inexpensive, but it also adds some great features like Intellisense1 and Nuget package support.

I generally use LINQPad as a simple coding environment for poking around my data sources, crafting quick coding experiments, and debugging. Because LINQPad does not have the overhead of a solution or project, like a development-oriented tool such as Visual Studio, it is easy to get stuck into a task. I no longer write throwaway console or WinForms apps; instead I just throw together a quick LinqPad query. I could continue on the virtues of this tool2, but I would like to touch on one of its utility features.

As part of LINQPad , you get some useful methods and types for extending LINQPad , dumping information to LINQPad's output window, and more. Two of these methods are LINQPad.Extensions.Cache and Utils.Cache. Using either Cache method, you can execute some code and cache the result locally, then use the cached value for all subsequent runs of that query. This is incredibly useful for caching the results of an expensive database query or computationally-intensive calculation. To cache an IEnumerable<T>  or IObservable<T>  you can do something like this:

var thingThatTakesALongTime = from x in myDB.Thingymabobs
                              where x.Whatsit == "thingy"
                              select x;
var myThing = LINQPad.Extensions.Cache(thingThatTakesALongTime);

Or, since it's an extension method,

var myThing = thingThatTakesALongTime.Cache();

For other types, Util.Cache  will cache the result of an expression.

var x = Util.Cache(()=> { /* Something expensive */ });

The first time I run my LINQPad code, my lazily evaluated query or the expression is executed by the Cache method and the result is cached. From then on, each subsequent run of the code uses the cached value. Both Cache methods also take an optional name for the cached item, in case you want to differentiate items that might otherwise be indistinguishable (such as caching a loop computation).

This is, as I alluded earlier, one of many utilities provided within LINQPad that make it a joy to use. What tools do you find invaluable? Do you already use LINQPad ? What makes it a must have tool for you? I would love to hear your responses in the comments.

Updated to correct casing of LINQPad, draw attention to Cache being an extension method for some uses, and adding note of Util.Cache3.

  1. including for imported data types from your data sources []
  2. such as its support for F#, C#, SQL, etc. or its built-in IL disassembly []
  3. because, apparently, I am not observant to this stuff the first time around. SMH []