I am working on an app that uses location services. If I am debugging, the app works fine. If I start without debugging, on the first run (after rebuild), it crashes when asking for authorization to use location services. What happens is that if you let it sit, with the messagebox showing long enough (5-10 seconds), it crashes. If I start without debugging again, it works fine (though it doesn't show the messagebox again, because somehow it gets past that line to the next line AFTER the conditional statement, where it sets first run false (I assume, because it doesn't show again).
Again, if I am debugging, no problems. If I start without debugging, it dies. This is the case when building in either the Debug or Release modes.
If I comment this block of code out, it executes without a problem. If I click OK quickly, it executes without a problem.
if (settings.FirstRunLocationPermission)
{
string message = "Do you wish to use location services to see your location on the map? Your location is not being tracked. You can change this authorization in the settings.";
//if (MessageBox.Show(message,"authorization",MessageBoxButton.OKCancel) == MessageBoxResult.OK)
//{
// settings.AllowLocation = true;
//}
settings.FirstRunLocationPermission = false;
}
I would greatly appreciate it if anyone can explain to me why a simple messagebox checking for ok would cause a problem like this. Thanks!
Most likely you are showing the MessageBox in OnNavigatedTo. If that is the case, this SO answer should help. The problem is that if the user does not press a button your app will crash since the framework thinks that navigation has failed.
And yes, this behaviour occurs to me only when debugger is not attached.
If you look at the MSDN Documentation for the method, the reasons for the possible Exceptions is fairly clear:
MDSN - MessageBox.Show Method
The other possibility is that there is some code running in the setter for the settings.AllowLocation property that is throwing the Exception. It would help if you included the actual Exception being thrown.
I use it this way, and it works :
var msg = MessageBox.Show("Do you .... ?", "Title", MessageBoxButton.OKCancel);
if(msg == MessageBoxResult.OK)
{
//Do something;
}
Good luck
Related
Just wondering if anyone might be able to point me in the right direction here.
user = await App.MobileService.LoginAsync(provider)
this is the line of code in question. The problem is; this works fine on 2/3 test machines (All Windows 10), the dialog is displayed and the program operates as expected. on the third machine however, the dialog does not display. I have wrapped the function in a try catch block and I am catching all exceptions that I then route to a MessageDialog to display on the screen. the messages are never shown, as though the try succeeded, but the function exits on that line exactly and throws no exceptions. I am using MobileServiceAuthenticationProvider.MicrosoftAccount as my provider.
Code redacted to highlight the error, the full code returns a boolean value for success/failure. All traces past the failing line do not appear, so the function is definitely exiting at the specified line.
try
{
//This line fails on a single machine out of three
user = await App.MobileService.LoginAsync(provider)
}
catch(Exception e)
{
//when it fails, this does not trigger, and no traces after this point
//appear until outside the function
MessageDialog msg = new MessageDialog(e.ToString());
await msg.ShowAsync();
}
and just to make things really weird...message dialogs prior to this point in the code work just fine...
I suspect that the security of the machine in question is blocking the login (windows defender), but I really have no idea where to look for this, or even how to test the problem further. Any ideas as to what would prevent this single machine from displaying the Microsoft login window, or ideas on further debugging would be appreciated.
You are not awaiting the response from the Async reply. This means that you will have an ordering and concurrency issue - sometimes it will work, and sometimes it won't and it's all in the timing.
You need:
var user = await client.LoginAsync(provider);
A strange behavior is occuring when running my application.
If I stop the code in debug mode before a specific line is reached, that line will be executed and everything is normal... but if i let the code run without debugging, of stop the code after, it will not run the line...
This is the code
if (SelectedProducts == null)
{
Global_Image.Product_Types = null;
Global_Image.Product_Types = new List<Prod_Product_Type>();
return;
}
I'm trying to make Global_Image.Product_Types count go to 0 by making the List null and creating a new list for it... but if I stop the code in the return none of them worked... If I stop before, they run and it works fine... can someone explain this behavior?
The function is not awaited, so no sync problem here, I think... The App is in azurewebsites...
please help
I have a method that stops a service(s) but I also need to delete the logs. Usually this is not a problem but the process can take a little bit of time before closing. Again, although the service appears stopped, the process does take additional time to close properly. Since the process is still running, I cannot delete the logs so I need to find a way to monitor the .exe to know when its safe to delete the logs.
so far my best option is a do while loop, unfortunately the first iteration of the delete statement throws an exception and stops the program.
do
{
// delete logs
}
while (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0);
Im sure there is a simple solution but my lack of experience is the real problem.
This is probably not the best answer either, but you could invert the loop to:
while (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0)
{
// delete log files.
}
I would suppose this would evalutate the condition of the loop before executing the contents. But according to your statements, this will not execute the code until the process has exited.
A hackish way around this is to perform a loop, and break out manually once the conditions:
bool CloseProcessOperation = true; // Control variable incase you want to abort the loop
while (CloseProcessOperation)
{
if (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0) { break; }
// break if no logs exist
// break for some other condition
// etc
// delete logs
}
I have the following code in a C# windows form application.
if (myGrid.Rows.Count != 0)
{
// do something
}
else
{
MessageBox.Show("Test");
}
The message box shows up in Debug mode but not in release mode. Any idea why?
I am having similar issues with other code as well
For instance
if (!myParameter)
this.mycheckBox.Enabled = false;
else
this.mycheckBox.Enabled = true;
The above code works in debug mode not in release. Not sure why.
Thanks
In release mode myGrid.Rows.Count != 0 must be true, try putting another MessageBox.Show there.
Probably because your if statement is true in release mode.
Remove the if and keep the MessageBox.Show("Test"); and that should work just fine
EDIT
You can even go a step further by putting a breakpoint at the if statement and seeing what value is being returned. This would work for both sections of code.
Try putting messageboxes or breakpoints before all your if statements. What is the value of the parameter you are about to test?
If this does not shed any light, make a new, empty winForms project, and put in a messagebox with no conditions. If that works, start adding your old code to it piece by piece and watch to see where it breaks.
Or not!
I have a fairly simple application timer program. The program will launch a user selected (from file dialog) executable and then terminate the process after the user specified number of minutes. During testing I found that a crash occurs when I call the Process.Kill() method and the application is minimized to the system tray.
The executable in question is Frap.exe which I use frequently and is the reason I wrote the app timer in the first place. I always minimize fraps to the tray, and this is when the crash occurs.
My use of Kill() is straight forward enough...
while (true)
{
//keep checking if timer expired or app closed externally (ie. by user)
if (dtEndTime <= DateTime.Now || p.HasExited)
{
if (!p.HasExited)
p.Kill();
break;
}
System.Threading.Thread.Sleep(500);
}
In searching for alternatives methods to close an external application programmatically, I found only Close() and Kill() (CloseMainWindow is not helpful to me at all). I tried using Close(), which works providing the application is minimized the tray. If the app is minimized, Close() doesn't cause a crash but the app remains open and active.
One thing I noticed in a few posts posts regarding closing external applications was the comment: "Personally I'd try to find a more graceful way of shutting it down though." made in THIS thread found here at stack flow (no offense to John). Thing is, I ran across comments like that on a few sites, with no attempt at what a graceful or elegant (or crash-free!!) method might be.
Any suggestions?
The crash experienced is not consistant and I've little to offer as to details. I am unable to debug using VS2008 as I get message - cant debug crashing application (or something similar), and depending on what other programs I have running at the time, when the Kill() is called some of them also crash (also programs only running in the tray) so I'm thinking this is some sort of problem specifically related to the system tray.
Is it possible that your code is being executed in a way such that the Kill() statement could sometimes be called twice? In the docs for Process.Kill(), it says that the Kill executes asynchronously. So, when you call Kill(), execution continues on your main thread. Further, the docs state that Kill will throw a Win32Exception if you call it on an app that is already in the process of closing. The docs state that you can use WaitForExit() to wait for the process to exit. What happens if you put a call to WaitForExit() immediately following the call to Kill(). The loop looks ok (with the break statement). Is it possible that you have code entering that loop twice?
If that's not the problem, maybe there is another way to catch that exception:
Try hooking the AppDomain.CurrentDomain.UnhandledException event
(currentDomain is a static member)
The problem is that Kill runs asynchronously, so if it's throwing an exception, it's occurring on a different thread. That's why your exception handler doesn't catch it. Further (I think) that an unhandled async exception (which is what I believe you have) will cause an immediate unload of your application (which is what is happening).
Edit: Example code for hooking the UnhandledExceptionEvent
Here is a simple console application that demonstrates the use of AppDomain.UnhandledException:
using System;
public class MyClass
{
public static void Main()
{
System.AppDomain.CurrentDomain.UnhandledException += MyExceptionHandler;
System.Threading.ThreadPool.QueueUserWorkItem(DoWork);
Console.ReadLine();
}
private static void DoWork(object state)
{
throw new ApplicationException("Test");
}
private static void MyExceptionHandler(object sender, System.UnhandledExceptionEventArgs e)
{
// get the message
System.Exception exception = e.ExceptionObject as System.Exception;
Console.WriteLine("Unhandled Exception Detected");
if(exception != null)
Console.WriteLine("Message: {0}", exception.Message);
// for this console app, hold the window open until I press enter
Console.ReadLine();
}
}
My first thought is to put a try/catch block around the Kill() call and log the exception you get, if there is one. It might give you a clue what's wrong. Something like:
try
{
if(!p.HasExited)
{
p.Kill();
}
break;
}
catch(Exception ex)
{
System.Diagnostics.Trace.WriteLine(String.Format("Could not kill process {0}, exception {1}", p.ToString(), ex.ToString()));
}
I dont think I should claim this to be "THE ANSWER" but its a decent 'work around'. Adding the following to lines of code...
p.WaitForInputIdle(10000);
am.hWnd = p.MainWindowHandle;
...stopped the crashing issue. These lines were placed immediately after the Process.Start() statement. Both lines are required and in using them I opened the door to a few other questions that I will be investigating over the next few days. The first line is just an up-to 10 second wait for the started process to go 'idle' (ie. finish starting). am.hWnd is a property in my AppManagement class of type IntPtr and this is the only usage of both sides of the assignment. For lack of better explaination, these two lines are analguous to a debouncing method.
I modified the while loop only slightly to allow for a call to CloseMainWindow() which seems to be the better route to take - though if it fails I then Kill() the app:
while (true)
{
//keep checking if timer expired or app closed externally (ie. by user)
if (dtEndTime <= DateTime.Now || p.HasExited) {
try {
if (!p.HasExited) // if the app hasn't already exitted...
{
if (!p.CloseMainWindow()) // did message get sent?
{
if (!p.HasExited) //has app closed yet?
{
p.Kill(); // force app to exit
p.WaitForExit(2000); // a few moments for app to shut down
}
}
p.Close(); // free resources
}
}
catch { // blah blah }
break;
}
System.Threading.Thread.Sleep(500);
}
My initial intention for getting the MainWindowHandle was to maximize/restore an app if minimized and I might implement that in the near future. I decided to see if other programs that run like Fraps (ie, a UI but mostly run in the system tray (like messanger services such as Yahoo et al.)). I tested with XFire and nothing I could do would return a value for the MainWindowHandle. Anyways, this is a serperate issue but one I found interesting.
PS. A bit of credit to JMarsch as it was his suggestion RE: Win32Exception that actually lead me to finding this work around - as unlikely as it seems it true.