UriFormatException : Invalid URI: Invalid port specified

Berryl picture Berryl · May 15, 2011 · Viewed 25.1k times · Source

The assembly qualified string used as a parameter below for a Uri works in XAML, but gives me the error shown when used in code.

I tried every kind of UriKind with the same result. How can I fix this?

[Test]
public void LargeImageSource_IsKnown()
{
var uri = new Uri(
        "pack://application:,,,/" + 
        "MyAssembly.Core.Presentation.Wpf;component/" + 
        "Images/Delete.png", UriKind.RelativeOrAbsolute);

Assert.That(
        _pickerActivityCollectionVm.DeleteActivityCommand.LargeImageSource,
        Is.EqualTo(uri));
}

System.UriFormatException : Invalid URI: Invalid port specified.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)

UPDATE

Based on Thomas' superb answer and my own comments about readability, I wound up using the following in my BaseTestFixture class. Hope this helps someone else.

    protected virtual void OnFixtureSetUp() {
        // logging, other one time setup stuff...

        const string scheme = "pack";
        if (!UriParser.IsKnownScheme(scheme)) {
            Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
        }
    }

Answer

Thomas Levesque picture Thomas Levesque · May 15, 2011

That's because you're executing this code while the pack:// scheme is not yet registered. This scheme is registered when you create the Application object. You can add this code in the setup of your test fixture:

[SetUp]
public void Setup()
{
    if (!UriParser.IsKnownScheme("pack"))
        new System.Windows.Application();
}

EDIT: actually it seems the pack:// scheme is registered in the type initializer of the PackUriHelper class (which happens to be used by the Application class). So actually you don't need to create an instance of Application, you only need to access a static member of PackUriHelper to ensure the type initializer has run:

[SetUp]
public void Setup()
{
    string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
}