WPF app startup problems - wpf

My brain is all over the map trying to fully understand Unity right now. So I decided to just dive in and start adding it in a branch to see where it takes me. Surprisingly enough (or maybe not), I am stuck just getting my darn Application to load properly.
It seems like the right way to do this is to override OnStartup in App.cs. I've removed my StartupUri from App.xaml so it doesn't create my GUI XAML. My App.cs now looks something like this:
public partial class App : Application
{
private IUnityContainer container { get; set; }
protected override void OnStartup(StartupEventArgs e)
{
container = new UnityContainer();
GUI gui = new GUI();
gui.Show();
}
protected override void OnExit(ExitEventArgs e)
{
container.Dispose();
base.OnExit(e);
}
}
The problem is that nothing happens when I start the app! I put a breakpoint at the container assignment, and it never gets hit.
What am I missing? App.xaml is currently set to ApplicationDefinition, but I'd expect this to work because some sample Unity + WPF code I'm looking at (from Codeplex) does the exact same thing, except that it works!
I've also started the app by single-stepping, and it eventually hits the first line in App.xaml. When I step into this line, that's when the app just starts "running", but I don't see anything (and my breakpoint isn't hit). If I do the exact same thing in the sample application, stepping into App.xaml puts me right into OnStartup, which is what I'd expect to happen. Argh!
I've also just created a new WPF application from scratch, removed StartupUri, overrode OnStartup(), and it also works. WTH?
Is it a Bad Thing to just put the Unity construction in my GUI's Window_Loaded event handler? Does it really need to be at the App level?

Double check that the x:Class in App.xaml in the same namespace/class as in your App.xaml.cs. It's easy to copy/paste from another project and to forget to modify this.
If for any reason you don't manage to solve this, remove the App.xaml and add a Main() which does a new App().Run(). If this doesn't work either, there's something really odd here.

Your problem doesn't seem related to Unity at all... Make sure that :
the startup object is set to YourProject.App (in the project properties page)
the build action for App.xaml is set to "ApplicationDefinition"
Otherwise, I can't see any reason why it shouldn't work...
Update : just another idea... Try to set the StartupUri back to App.xaml, and call the base implementation in OnStartup :
protected override void OnStartup(StartupEventArgs e)
{
container = new UnityContainer();
base.OnStartup(e);
}

In my case, I hit the "something really odd" part that Julien Lebosquain referred to.
I kept checking and re-checking names, namespaces, event handlers etc and couldn't see anything wrong but still my WPF MainWindow.xaml kept opening first, bypassing the required startup method.
Eventually, I deleted MainWindow.xaml ... but STILL it popped up first. At which point, I cleaned the solution, deleted the binaries from disk (after altering the start-up project) and closed and re-opened the solution.
This 'fixed' my problem.

I had a similar problem -- My App constructor and OnStartup weren't being called (breakpoints not being hit). In case someone else runs across this thread, here's another thing that can go wrong.
I have a solution with several apps, one of which is just a utility I use to manage some XML files. It doesn't get used much, so I basically forgot about it. Originally, my builds were for "Any CPU", but recently I had to change them to "x86" due to a library I was using. Today, I needed to run this utility, but it was crashing and in the debugger nothing in the App class was being called. After checking namespaces (which were OK), I decided to clean the project (as suggested above). When I tried to run the app, I got an error that VS couldn't find the EXE. Apparently, VS was running an old "Any CPU" EXE it found in the output directory which was crashing, and then was deleted when I cleaned the project. I checked the Build | Configuration Manager, and sure enough, I hadn't selected the utility app for the "x86" build. Once I added it, everything worked great. Hope this helps.

Related

MVVM Application not Restoring State Correctly

I have built a class library that acts as a GUI framework that can be inherited by other projects. This application is based on projects Wild and Gemini.
My problem is that upon restoring Avalon Dock's layout using the standard serializer
var layoutSerializer = new XmlLayoutSerializer(manager);
where manager is type DockingManager. The manager restores and empty tab. My guess is that Caliburn Micro cannot find the stored ViewModel (named HomeViewModel). However, I am struggling to confirm this.
I believe my bootstrapper to be correct and that the MEF containers are being setup correctly to allow resolution of external types. I have debugged the project to a point where I think this issue is occurring and in the output window I can see Attach(Home) where the attach is occurring (note, "Home" is the display name of the HomeViewModel). However, I don't know what is wrong with the attach process as this is handled by MEF/Caliburn.
I am really stuck with debugging this an wondered if
Any one could offer any insightful advice as to how to proceed with the debugging process?
Anyone would be willing to take a look at the solution?
I have spent a hell of a lot of time debugging this without any luck and the problem is sufficiently esoteric and illusive as to render most posts here irrelevant to me.
Thanks for your time.
as discussed and after looking on the sample code provided, I understand that the following
HomeViewModel or can say LayoutItemBase is not supposed to be reopened as ShouldReopenOnStartup is set to false
if you close the application while leaving a document open for HomeViewModel it is restored on next start with blank view [Not OK]
Analysis
the SaveState method was correctly honoring ShouldReopenOnStartup value and was not emitting the state for the HomeViewModel but dock manager was still emitting an element for the document.
So upon next restart the LoadState does not find any stored state but a window was created as an element was present in the dock manager's layout state
<LayoutDocument Title="HomePP" IsSelected="True" IsLastFocusedDocument="True" ContentId="d716f824-cfff-4b54-8fd6-2d026a99369a" .../>
you did try to use e.Cancel property of Serialization callback to cancel the event, but seems like it is not supposed to prevent of loading a window but just simply to cancel the event if not needed.
Resolution
So the ideal approach is to close the documents which are not supposed to be restored before saving the layout
here is how I did
ShellViewmodel.cs : Line 279 method SaveState(string)
change the following code
if (!item.ShouldReopenOnStartup)
continue;
to
if (!item.ShouldReopenOnStartup)
{
//this item is not supposed to be restored so close the window before saving layout
IDocument doc = item as IDocument;
if (doc != null)
CloseDocument(doc);
continue;
}

How to resolve Design Time Static Resources in Embedded UserControls in Blend 4

The Short Version
How do you handle static resource look ups in UserControls that get embedded into other windows/user/custom controls? So that Blend 4 might render it properly # design time something Visual Studio already does for you.
The Long Version
As the question suggests, we have a window that has some embedded user controls and the window as well each as embedded user control all use static resource markup extensions to resolve references to resources found in a merged dictionary in the app.xaml file.
Blend has no problems loading and rendering any of my sample user controls that I made in the VS Designer Surface when opened individually. It has no problems resolving the countless static resource mark up extensions I employ pretty much everywhere.
Whenever I try to open my 'MainWindow.xml', (a window control) I noticed that I was getting 4 - Cannot Create Instance Of Type errors with Blend 4 nicely telling me on the ArtBoard that it has caught some design time exceptions. Digging further down into these exceptions by attaching the VS debugger instance to Blend I noticed that every single Static Resource I referenced, it complained it cannot find it.
As a comparison I looked at a custom control that I created, it did not employ any static resources at all they were local resources instead. This custom control when embedded into a UserControl I noticed worked pretty nicely. I think it is obvious why!
Does any one on SO, have any ideas how to get around this problem? I tried the whole 'Add a Design-Time Dictionary' <-- which works partially, embedded user controls still are not created at all !
Research
MVVM Light + Blend designer view error: Cannot find resource named 'Locator'
Theming using resources without Blend vomitting
UPDATE: Possible Solutions:
Employ a simialr approach presented here: GianlucaCucco Answer
Convert all static resource look ups to local resources for UserControls?
Convert all static resource look ups to dynamic resources instead.
Neither of these solutions are pretty. = (
I have several resources in a Converters.xaml file that Blend used to complain about. My workaround is to forcibly load that xaml file at design time.
using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Markup;
public static class DesignTimeSupport
{
public static void LoadCommonConvertersForBlend(this ResourceDictionary resourceDictionary)
{
if (resourceDictionary == null || !DesignerProperties.IsInDesignTool) return;
var convertersXamlUri = new Uri("Assets/Converters.xaml", UriKind.Relative);
var streamInfo = Application.GetResourceStream(convertersXamlUri);
using (var reader = new StreamReader(streamInfo.Stream))
{
var converters = (ResourceDictionary)XamlReader.Load(reader.ReadToEnd());
resourceDictionary.MergedDictionaries.Add(converters);
}
}
}
The ViewBase calls this method in the constructor.
public class ViewBase : Page
{
public ViewBase()
{
Resources.LoadCommonConvertersForBlend();
}
}
Classes that don't inherit from ViewBase make their own call.
Try this answer -- it sounds like a similar problem. I've not had occasion to use it yet so I'm curious to know whether or not it works for you. It's certainly less messy than the other solutions.
As strange as it may seem (and I cannot find a logical reason why), the error message showed the resource it couldn't find as "maindictionary.xaml", whereas the file and all references were "MainDictionary.xaml".
I opened the properties of the resource in the Solution Explorer, changed the FileName to manidictionary.xaml, then back again to MainDictionary.xaml and the five error messages I was getting... disappeared.
Hope this answer finds its way into the hands of someone else who may be struggling with the oesoteric problem and it helps.

Silverlight: how to not load MergedDictionaries from app.xaml at startup?

As a workaround for the way Silverlight loads resources, I implemented the solution posted here:
Silverlight Shared MergedDictionaries
This works fine, but it's annoying having to comment out the resource dictionaries in the app.xaml. I need to comment them to run the app, but uncommenting them lets me get a design view.
I am sure there's a way to get the app to not load these, but I'm not much of a dev. Can somebody point me to a tutorial or example? Some googling hasn't turned up anything. Thanks!
I found a simple answer: comment out InitializeComponent in App().
Looking at the code in App.g.i.cs:
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/SLPortalResources;component/App.xaml", System.UriKind.Relative));
}
Since this just loads what's in app.xaml, commenting it out works: the app runs and you get a design view.
Is there anything wrong with doing this?

WPF: How should I organize my code amongst the source files?

I see a Window1.xaml and its associated .cs file, which are the main window. Then there's also app.xaml and app.xaml.cs. First, what is the point of App? It seems to be empty.
I'm assuming I should put local variables to the Window on its cs file, and variables related to the whole program on App?
You should MVVM. Start early, win often.
App.xaml and its code file are used for application-wide resources and code that needs to run on startup. You shouldn't be putting anything in app.xaml.cs unless you need to.
App.xaml and App.xaml.cs is your applicaton's entry point. Main() is actually auto-generated and hidden in the partial App class. In the XAML, you can set the Window that will initially display, so you are not forced to use Window1.
In reality, you don't need App.xaml either. In some applications I have made, I have instead opted to create an App.cs, where I manually create the Main() entry point and start the initial Window. If you don't need such fine control over your Main() method, I'd recommend keeping the default XAML method of startup. You can still subscribe to events in App's constructor using the XAML method, for startup code and handling unhandled exceptions.
You should put local variables with the class that needs them. Global variables are bad, but it's be better to use static classes and variables instead of inserting the unnecessary code in App.xaml.cs.

What causes a window to not appear in the taskbar until it's Alt-Tabbed to in Vista?

When our app is started programatically (either through custom action in MSI installer or when starting a new instance) in Windows Vista (also happens in Windows 7 Beta) it won't appear in the taskbar and isn't focused. Alt-tabbing to it will make it appear in the taskbar properly and stay there.
What causes this? I've seen this in some other apps before as well, but not sure why. Out app is .NET WinForms app. Never see this happen in XP, only Vista and 7
Edit: Well, it seems like the only time this happens reproducibly is when it's run by the installer, I believe there's other times it occurs, but I might just be crazy. The launching code is a bit complex to post because we handle various command line launch parameters and it launches a signin form before actually launching the main app etc.
Has anyone had to deal with this scenario before and worked it out?
Try checking your main application form "Form Border" property.
If it's ToolWindow (Fixed or Sizable), try changing it to FixedDialog for example.
This solved the problem in my case.
The usual reason for this is that your main application window doesn't have the window styles that let Windows know it's a main application window (rather than a tool window or a dialog box). So Windows is having to guess based on how the app was started, etc.
Use Spy++ to complare the window styles (especially extended styles) if your window to that of some other window that doesn't have this problem. Are you missing the WS_EX_APPWINDOW style? Are any other styles/extended styles different from other top level windows?
G.So's answer made me find the solution for my problem, wich was caused by the fact that i had my form sizable from launch, but set to borderless in the load void.
If anyone is interested in how i managed to keep the switch to borderless and have it pop up as it should in the taskbar without any dirty hacks.. here it is..
Make a new event from the form on the form's "Shown" event, and put your line of code for switching to borderless in here. Problem solved :)
private void Form1_Shown(object sender, EventArgs e)
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
and for the lazy ones ;) >>>>
this.Shown += new EventHandler(Form1_Shown);
Thanks again G.So for clearing up what could cause this in the first place.
I stuggled with this issue as well, and found like a previous commenter said, you cannot have anything in the form's Load() event that changes that FormBorderStyle property. Move anything that changes it to the Shown() event.
Well, one solution is to use a hack like this. That's really not what it's for.
Usually the decision of whether a window will be in the taskbar or not is based on the border styles it uses. The article I linked to provides a bit more detail. The article's comment about the window having an owner or not is quite possible highly relevant to your issue, since the window might somehow be getting a different owner when launched by the installer.
That article is in VB but it's all based around API calls so the info it provides is pretty language independent.
Never see this happen in XP, only Vista and 7
Maybe it's a bug in Vista...?
What happens if you call SetForegroundWindow() (or equivalent in .Net)?
Edit
I did of course mean "BringWindowToTop()".
Or do both.
We had this same problem and fixed it by setting the form property showintaskbar property to true.
Weird that all windows os's dont run apps in the same way!
In our situation, this was tracked down to the form's text property being changed within the Load event.
After putting this inside a BeginInvoke, this odd behaviour no longer happened.
Hope this helps anyone else.
Example
private void Form_Load(object sender, EventArgs e)
{
...
...
...
// this needs to be inside a BeginInvoke otherwise it messes with the taskbar visibility
this.BeginInvoke(new Action(() =>
{
this.Text = "Something new";
}));
...
...
...
}
We encountered the same issue, also in Windows 8. Sometimes the form was receiving correctly the focus, but say just ~30% of the time.
We tried different solutions, but actually the one that worked was the following:
private void OnFormShown(object sender, EventArgs e)
{
// Tell Windows that the Form is a main application window
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
// Even if true, enforce the fact that we will the application on the taskbar
this.ShowInTaskbar = true;
// Put the window to the front and than back
this.BringToFront();
this.TopMost = true;
this.TopMost = false;
// 'Steal' the focus.
this.Activate();
}
Moreover, we ensure also not to set the title of the form during the Load event.

Resources