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

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.

Related

Can't debug Task in Visual Studio 2015 Win-forms

This is Windows Forms application.
As in title, I can't debug Task in Visual Studio 2015. If I will check breakpoint at line var a = costam(); it will be hit, but if then I will press step into, or continue, execution will not be continued. This works fine in Console Application. For now i checked, that error appears when I'am trying to run my own method in Task, or if I'am invoking something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Task.Run(() =>
{
var a = costam();
});
}
string costam()
{
return "s";
}
}
I would suggest changing the settings to break on any exception in the debug menu, not only uncaught ones. This option is called breaking when the exception is "thrown". Unfortunately the 2015 exceptions menu I'm not familiar with so I can't help you out with that.
There are certain exceptions that are caught and suppressed behind the scenes, especially with WinForms--constructors / load events are particularly shielded. It's likely that it doesn't like spawning a new thread in the UI thread which is why it's throwing an exception in your WinForms application but not the console application. This also explains why "stepping in" "doesn't work"--it steps in but the exception means the next breakpoint isn't hit.
Update 1 to VS2015 seems to solve this issue.

Is it a Bad Thing to put WPF Main function inside Try/Catch block?

I want to circunscribe this question to the specific context of WPF aplications.
The accepted answer says
"You should only to catch exceptions that you can actually do something about"
and also
"Note that if you're simply trying to catch any unhandled exceptions that might occur for the purposes of logging or error reporting, you should be using the AppDomain.UnhandledException event"
Well, all would be good and well EXCEPT (pun intended) that I had a very serious problem while deploying a WPF application which would crash right at application startup, with the dreaded IOException error in PresentationFramework.
I tried the Application.Current.DispatcherUnhandledException, but the crash apparently happended outside its grasp. I tried Windbg but the error messages were still elusive.
Then I followed advice from this post (changing app.xaml Build Action property from "Application Definition" to "Page" and putting Main() function inside App.xaml.cs itself), putting a try/catch with a MessageBox (it could be a logging call, whatever), and the message displayed immediately led me to the solution.
So the question is:
Considering WPF has its own esoterical bugs, is there any actual problem in putting Main() function body inside a try/catch?
Here is my current code:
public partial class App : System.Windows.Application {
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main() {
try {
var v3d = new App();
v3d.InitializeComponent();
var shellview = new ShellView();
v3d.Run(shellview);
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
}
And for the record, I was getting "Cannot locate resource 'app.xaml'" caused by some culture mismatch, the problem happened in only one of two similar machines apparently because one OS (Win7) is English and other is Portuguese. I solved it with this answer.

WPF unit test DirectoryNotFoundException

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.

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.

Silverlight 3: No change but now I am getting "Page Not Found"

Had a page that was working fine. Only change I made was to add a datagrid to the page (which also added the xmlns) and all of the sudden I'm getting Page Not Found. Checked the UriMappings. Tried the default nav link. No joy.
Ideas?
UPDATE: The answer was that I had a mock class that was not initializing a collection. See Byrant's answer for a way to save yourself some time.
To see what the issue is you need to make one change to your MainPage.xaml.cs:
// If an error occurs during navigation, show an error window
private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
Exception ex = e.Exception;
while (ex.InnerException != null)
{
ex = ex.InnerException;
}
e.Handled = true;
ChildWindow errorWin = new ErrorWindow(ex);
errorWin.Show();
}
Once you've made that change when you start the application you should see the exception instead of the page where the exception occurred.
Firebug is always a good friend to see which kind of requests are called ...
Often the devServer is not closed properly , have a look at the taskbar

Resources