Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UriFormatException : Invalid URI: Invalid port specified

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));         }     } 
like image 784
Berryl Avatar asked May 14 '11 23:05

Berryl


2 Answers

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; } 
like image 77
Thomas Levesque Avatar answered Sep 28 '22 01:09

Thomas Levesque


It appears that accessing PackUriHelper.UriSchemePack only registers the pack scheme, not the application scheme, which I needed to use the pack://application:,,,/ syntax in my unit tests. I therefore had to use the new Application() approach, which worked fine for registering both schemes.

like image 31
Mathieu Frenette Avatar answered Sep 28 '22 01:09

Mathieu Frenette