WPF unit test DirectoryNotFoundException - wpf

I am having trouble instantiating a view model wich loads an image from Resources.
The line that fails in the assembly I'm testing is:
get { return new ImageSourceConverter().ConvertFromString("pack://application:,,,/Resources/Icons/Commands/DisabledNewSessionIcon.png") as ImageSource; }
the exception is:
Unable to create instance of class
GPAnalysisSuite.Tests.View_Models.Session_Controller.SessionControllerViewModel_NonDefaultConstructorTester.
Error:
System.IO.DirectoryNotFoundException:
Could not find a part of the path
'C:\TGP\GP Analysis
Suite\Application\Tests\TestResults\Paul_PAUL-GP
2011-03-17
11_27_28\Out\Resources\Icons\Commands\DisabledNewSessionIcon.png'..
I have already found a solution to a simular problem and included the following to the TestClass:
[AssemblyInitialize]
public static void InitialisePackageUriHelper(TestContext context)
{
PackUriHelper.Create(new Uri("reliable://0"));
new FrameworkElement();
System.Windows.Application.ResourceAssembly = typeof(App).Assembly;
}
I can see that I need to preserve the Uri of the assembly I'm testing but have no idea how to do it, can anyone help?

I appear to have solved the problem by changing the resource build action from Content to Resource.
Although I have to rebuild the solution everytime I want to run the unit tests this is now workable at least.

Related

Nancyfx localization

I'm testing localization in Nancy and able to get it to work using EMBEDDED resource files but the issue is I don't want embedded resource files because I want them to be allowed to be edited via the GUI or using the file (if I go the DB route or setting the resource file as "content").
According to the doucmentation you should be able to override it to support using a database but I'm unable to get this to work (https://github.com/NancyFx/Nancy/wiki/Localization):
public class ResourceManager : ResourceBasedTextResource
{
public ResourceManager(IResourceAssemblyProvider resourceAssemblyProvider) : base(resourceAssemblyProvider)
{
}
public new string this[string key, NancyContext context]
{
get
{
return "HELO!";
}
}
}
This was just me messing around but I was hoping in the Razor view when I did #Text.Localization. it should return "HELO!" for everything... however it is not working
There really isn't a question in your post so I'm going to have to guess a bit and assume that you're not getting any exception but rather you're not seeing the "HELO!" in your view
Simply implementing a new ResourceBasedTextResource class is not enough. This is a core component and as such you are going to explicitly have to tell Nancy to use it. You do this by overriding the InternalConfiguration property of your Bootstrapper and tell Nancy to use your implementation instead
You can see it in the DemoBootstrapper of the demo that is linked from that wiki page https://github.com/NancyFx/Nancy/blob/8970ac9d6c7cf46e6060f0b83117c19fa18085c2/src/Nancy.Demo.Razor.Localization/DemoBootstrapper.cs#L11
Also, if you are not going to use resource files, then you should look into inheriting from ITextResource interface instead. It's a simple interface so it should be straight forward.
HTH

WPF MessageBox in App.xaml.cs stops MainWindow initialisation so app never appears but is (apparently) running correctly

There's no error message and no indication why it is not displaying the window. The app initialises App.xaml.cs: App() {} and I can step through the App.xaml file. It gets the startup uri and then... silence. No output in the Output window and no unhandled exception and no window, I can't find where to put a breakpoint to debug as it isn't hitting the start of MainWindow.xaml.cs.
Really confused.
This was working 20m ago.
In that time all I did was add Windows.Office.Interop.Outlook reference. I removed the reference and rebuilt but still the same. Would that cause this problem? Has anyone seen this before? Google isn't helping!
EDIT :
App.xaml.cs:
public App()
{
using (var dbContext = new DBEntities())
{
if (!db.Exists())
{
try
{
db.Database.Create();
MessageBox.Show("Database created"); // this is the problem!!
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
I've added App.xaml.cs, I found that the problem was using a MessageBox to give info (this is still in development!). I'd been meaning to get rid of it and eventually did and my problem went away. This meant I could find relevent Goolge results:
MSDN query and answer for exactly my problem
I will be adding an 'loading window' in between app load and main window load eventually in which I will be able to feedback information using Bindings etc.
Fixed error by removing the MessageBox.Show(..) call. The selected answer from the MSDN URL given in the question states:
"I performed a test based on your description, the applicationi stop at the method : USER32!GetMessageW+0x33, calling USER32!NtUserGetMessage"
I assume this is what was occurring in my case, although I didn't test it.
What happens if you create a new window and set that as the StartupUri?
You also might want to create a new project and make sure that the namespaces referenced in the App.xaml in your existing app haven't somehow been inadvertently edited.

Recomposition issue with a Modular Silverlight application

I'm working with a Silverlight 4 application and we use Prism/MEF to build modules.
Each module is created as a Silverlight application. We then use a ModulesCatalog.xaml file to control how the modules are loaded.
We had 6 modules and everything was working perfect.
This week we're adding a 7th module and we just have the new Silverlight application created. We setup the module class as follows.
[ModuleExport(typeof(InsightModule))]
public class InsightModule : IModule
{
}
Then we added an entry to our ModulesCatalog file.
Now when we run the application we start getting all types of recomposition errors. The stack shows this.
at System.ComponentModel.Composition.CompositionResult.ThrowOnErrors(AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.OnExportsChanging(ExportsChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.OnCatalogChanging(Object sender, ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.OnChanging(Object sender, ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.AggregateCatalog.OnChanging(ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.RaiseChangingEvent(Lazy`1 addedDefinitions, Lazy`1 removedDefinitions, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.Add(ComposablePartCatalog item)
at Microsoft.Practices.Prism.MefExtensions.Modularity.MefModuleInitializer.CreateModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Prism.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
Then you get the standard output.
The exception message was: The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 57 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.
1) Change in exports prevented by non-recomposable import 'EyeCue.Common.AboutEyeCueView.ViewModel (ContractName="EyeCue.Common.AboutEyeCueVM")' on part 'EyeCue.Common.AboutEyeCueView'.
WHat's puzzling is why none of the other 6 modules caused this problem but now all of a sudden, this new module without anything going on in it is causing a recomposition of the catalogue. It makes no sense.
Plus I have ctor's that import in some cases and that's they what I had to do to get things to work, so this is not as simple as going to setting the Allow Recomposition attribut.
I've downloaded the VisualMFX but this line of code throws an Object Not initialized exception.
this.compositionInfo = new CompositionInfo(_aggregateCatalog, _container);
Both _aggregateCatalog & _container are not null when this happens.
In summary, why would a 7th module all of a sudden start causing recomposition? Especially when the module isn't even defining any exports or imports at this time? That leads to how do we stop it to address this problem?
The issue turned out to be a reference to an assembly which had Copy Local set to true.
Making sure all references which are also set in the main application assembly were set to Copy Local = false seems to resolved the problem.

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));
}
}
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;
}
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.
If you're seeing this error in a Windows Store / WinRT project:
I wasn't able to use the "pack://" syntax at all when trying to load a resource in my C# app. What worked was ms-appx:// syntax of this kind:
ms-appx://[project folder]/[resource path]
For example, I wanted to load a resource dictionary named "styles.xaml" from a folder "core". This URI ended up working for me:
dictionary.Source = new System.Uri("ms-appx:///core/styles.xaml");
Even though the question specified WPF, the problem seemed extremely similar but ended up having a completely different solution, which took a while to find, and existing answers didn't help at all.
Again, this solution does not apply to WPF

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources