handle "The operation completed successfully" error - c#

I have a vast application running WPF and I occasionally get the
The operation completed successfully
error randomly, could be a whole host of things.
Is there any way to trap this code and just restart the app.
I'm already using
#region "Error Checking"
void OnAppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
HandleError("OnAppDomainUnhandledException", e.ExceptionObject.ToString(), e.ExceptionObject.ToString());
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string error = string.Empty;
if (e.Exception.InnerException != null)
error = e.Exception.InnerException.Message;
HandleError("OnDispatcherUnhandledException", e.Exception.Message.ToString(),error);
e.Handled = true;
}
#endregion
but this does not appear to catch/handle the error

When I Google it seems that it has something to do with SplashScreens...
Maybe this may help you, or this.

Related

How to write to a file in C#

I am trying to make a program that, at the same time, displays text that the user inputted and writes to a text file of that same user input data. I've tried wrapping the the code with Task.Run:
private void button_Click(object sender, RoutedEventArgs e)
{
show.Text = inputText.Text;
//Debug.WriteLine(check1_cont.ToString());
//Debug.WriteLine(check2_cont.ToString());
if (check1_cont && check2_cont == true )
{
show2.Text = inputText.Text;
Task.Run(() => File.WriteAllText(#"A:\temp\name.txt", inputText.Text));
}
}
But I get an exception error after the second text (the one in the if statement) when I press the button:
An exception of type 'System.Exception' occurred in normieap.exe but
was not handled in user code
Additional information: The application called an interface that was
marshalled for a different thread. (Exception from HRESULT: 0x8001010E
(RPC_E_WRONG_THREAD))
I try using StreamWriter:
private void button_Click(object sender, RoutedEventArgs e)
{
show.Text = inputText.Text;
//Debug.WriteLine(check1_cont.ToString());
//Debug.WriteLine(check2_cont.ToString());
if (check1_cont && check2_cont == true )
{
show2.Text = inputText.Text;
using (StreamWriter writer = new StreamWriter(#"A:\temp\name.txt"))
{
writer.WriteLine(inputText.Text);
}
}
}
But I get an error on the line:
using (StreamWriter writer = new StreamWriter(#"A:\temp\name.txt"))
Because '#"A:\temp\name.txt"' cannot convert from 'string' to 'System.IO.Stream'
And when I try just the normal way without any wrappers I get a synchronous error. Any solutions to this problem would be much appreciated.
When you run a task asyncrounously, it isn't guaranteed to run on the UI thread. Take your first example and try this:
private void button_Click(object sender, RoutedEventArgs e)
{
show.Text = inputText.Text;
//Debug.WriteLine(check1_cont.ToString());
//Debug.WriteLine(check2_cont.ToString());
if (check1_cont && check2_cont == true )
{
show2.Text = inputText.Text;
// Copy the text to output
string outputToWrite = inputText.Text;
// use the copied text
Task.Run(() => File.WriteAllText(#"A:\temp\name.txt", outputToWrite));
}
}
What's going on here is that a background thread is trying to access a GUI element. That's generally not allowed in singled threaded UI libraries like Windows Forms, so you need to copy the data out of the control before sending it back to the background thread, otherwise the code will fail as you have seen.

C# InvokeScript gives error 80020006

I have the piece of code as follows.
webBrowser.IsScriptEnabled = true;
webBrowser.InvokeScript("eval", "alert('hey')");
It gives An unknown error has occurred. Error: 80020006. Could you guide how to rectify this error.
There is no built-in browser window.alert in Windows Phone, but you can bind one as follows to call WebBrowser.ScriptNotify
//inside the page
window.alert = function (__msg) { window.external.notify(' + __msg + '); };
// in your C# code
this.webBrowser.ScriptNotify += new EventHandler<NotifyEventArgs>(Browser_ScriptNotify);
void Browser_ScriptNotify(object sender, NotifyEventArgs e)
{
MessageBox.Show(e.Value);
}
//later
this.CordovaView.Browser.IsScriptEnabled = true;
this.CordovaView.Browser.InvokeScript("alert", "ok");
On Cordova, there is also a Notification Plugin that you can plug by
window.alert = navigator.notification.alert;
Just be sure to enable Notification Plugin in config.xml
<feature name="Notification">
<param name="wp-package" value="Notification"/>
</feature>
It is caused by race condition. What we need to do is
this.CordovaView.Browser.LoadCompleted += Browser_LoadCompleted;
then
void Browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
this.CordovaView.Browser.IsScriptEnabled = true;
this.CordovaView.CordovaBrowser.IsScriptEnabled = true;
this.CordovaView.Browser.InvokeScript("setPushToken", push_uri);
}

NavigationService.navigate not working

At a login page, I checked for the validity and I made a simple condition:
if (everything is good)
{
this.NavigationService.Navigate(new Uri("/implementationPage.xaml", UriKind.Relative));
}
Then comes an error that points to this method:
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
MessageBox.Show(string.Format("page {0} failed, error: {1}", e.Uri.ToString(), e.Exception.StackTrace));
e.Handled = true;
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
Has anybody any idea why am I getting error?
Thank you Carlos,
After a lot of searching on the materials online
http://dotnetslackers.com/articles/silverlight/Windows-Phone-7-Silverlight-Programming-Navigation-between-Pages.aspx
This came in very handy. I didn't quite utilize the onNavigatedTo function apparently

'index was outside the bounds of the array' exception handling error

I am using the below code to find the base address of a running process. It's within a timer control for other purposes. If the target process is not running I want to display "Process is not running" in the label text, but keep checking for the running process and when/if found continue with the next code block. I have tried a few ways I thought would work, such as a 'try' with exception handling, but the form I am using to hold the label just freezes, I am quit new to c#. Here is the code,
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
int Base = test[0].MainModule.BaseAddress.ToInt32();
#endregion
//Other code
}
The exception when run is: "IndexOutOfRange exception was unhandled" - Index was outside the bounds of the array. Hopefully someone can help. Thanks.
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
if (test.Length > 0)
{
int Base = test[0].MainModule.BaseAddress.ToInt32();
}
else
{
myLabel.Text = "Process is not running";
}
#endregion
//Other code
}
Rather than use a try–catch block to handle the error, you should check whether the process was found before trying to access it:
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
if (test.Any())
{
// Process is running.
int Base = test[0].MainModule.BaseAddress.ToInt32();
// Perform any processing you require on the "Base" address here.
}
else
{
// Process is not running.
// Display "Process is not running" in the label text.
}
#endregion
//Other code
}
I think that the Process with the name "process" does not exist. You need to give a real processname. So the array does not contain any elements. Try debugging to see if the array contains any elements and add error handling or a verification that the array length is higher than 0 before doing the second line of your code.

C# Exception handling in classes

C# 2008
I have developed the class below. I have to get the balance from the web server. Once that is done it will call back into my main app with the result.
However, sometime the web server fails for some unknown reason. Could be high volume of traffic or something else. However, I haven't implemented any exception handling in my class. As the app that uses this handles the exception.
However, the client has confirmed that when the web server does fail it displays a unhandled exception dialog box. Then they have to click continue to keep using my application.
So below I am not sure if I should implement the exception handling in my class. However, I am confused as to why the exception was not caught in my app that as below.
Many thanks for any suggestions, or if you see anything else wrong,
private void OnGetBalanceCompleted(object sender, SIPPhoneLibraryEventArgs e)
{
try
{
//If the balance starts with 'null' there has been an error trying to get the balance.
if (e.Balance.StartsWith("null"))
{
statusDisplay1.CurrentBalance = CATWinSIP_MsgStrings.BalanceError;
}
else
{
// Display the current balance and round to 2 decimal places.
statusDisplay1.CurrentBalance = Math.Round(Convert.ToDecimal(e.Balance), 2).ToString();
//If the balance is zero display in the status message
if (decimal.Parse(e.Balance) == 0)
{
this.statusDisplay1.CallStatus = "Zero Balance";
}
}
//Remove the event as no longer needed
siplibrary.GetBalanceCompletedEvent -= new EventHandler<SIPPhoneLibraryEventArgs>(OnGetBalanceCompleted);
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Control library for all importing functions
public class Balance : IDisposable
{
//Constructor
WebClient wc;
public Balance()
{
using (wc = new WebClient())
{
//Create event handler for the progress changed and download completed events
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
}
~Balance()
{
this.Dispose(false);
}
//Event handler and the method that handlers the event
public EventHandler<SIPPhoneLibraryEventArgs> GetBalanceCompletedEvent;
//The method that raises the event
public void OnGetBalanceCompleted(SIPPhoneLibraryEventArgs e)
{
if (GetBalanceCompletedEvent != null)
{
GetBalanceCompletedEvent(this, e);
}
}
//Get the current balance for the user that is logged in.
//If the balance returned from the server is NULL display error to the user.
//Null could occur if the DB has been stopped or the server is down.
public void GetBalance(string sipUsername)
{
//Remove the underscore ( _ ) from the username, as this is not needed to get the balance.
sipUsername = sipUsername.Remove(0, 1);
string strURL = string.Format("http://xxx.xxx.xx.xx:xx/voipbilling/servlet/advcomm.voipbilling.GetBalance?CustomerID={0}", sipUsername);
//Download only when the webclient is not busy.
if (!wc.IsBusy)
{
// Sleep for 1/2 second to give the server time to update the balance.
System.Threading.Thread.Sleep(500);
// Download the current balance.
wc.DownloadStringAsync(new Uri(strURL));
}
else
{
System.Windows.Forms.MessageBox.Show("Busy please try again");
}
}
//return and display the balance after the download has fully completed
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Pass the result to the event handler
this.OnGetBalanceCompleted(new SIPPhoneLibraryEventArgs(e.Result));
}
//Progress state of balance.
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//Write the details to the screen.
Console.WriteLine(e.TotalBytesToReceive);
Console.WriteLine(e.BytesReceived);
Console.WriteLine(e.ProgressPercentage);
}
//Dispose of the balance object
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//Remove the event handlers
private bool isDisposed = false;
private void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.Dispose();
}
isDisposed = true;
}
}
}
It seems that you are catching the exception on the OnGetBalanceCompleted event only, instead on the process of fetching the balance.
When there is any error on the fetching, the OnGetBalanceCompleted is not even called, that's why your exception handler is not called.
There is more information in the exception than just its Message property. You are throwing all of that information away by only displaying the Message property. Use ex.ToString() instead.
Is the code you posted part of the user interface? If not, then it has no business knowing anything about the user interface. In particular, it should not be using MessageBox.Show.
I'd remove all the UI stuff, and instead raise an event. The caller would listen to the event and do any UI work.

Categories

Resources