I am using GCMlibrary in C#. I have implemented different handlers that check whether message is sent or not. How can I check handler that is for
ChannelException
ChannelDestroyed
ServiceException
How can I check when exception come in these events.
I have declared handler like this
static void ChannelException(object sender, IPushChannel channel, Exception exception)
{
CLogger.WriteLog(ELogLevel.INFO, "Channel Exception: " + sender + " -> " + exception);
// Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
}
static void ServiceException(object sender, Exception exception)
{
CLogger.WriteLog(ELogLevel.INFO, "Service Exception: " + sender + " -> " + exception);
string test= exception.Message;
// Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
}
static void ChannelDestroyed(object sender)
{
CLogger.WriteLog(ELogLevel.INFO, "Channel Destroyed for: " + sender);
// Console.WriteLine("Channel Destroyed for: " + sender);
}
To handle exceptions in events in C# use the sample from MSDN. Use the following events raise approach:
public class Pub
{
public event EventHandler OnChange = delegate { };
public void Raise()
{
var exceptions = new List<Exception>();
foreach (Delegate handler in OnChange.GetInvocationList())
{
try
{
handler.DynamicInvoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
}
Catch exceptions as mentioned:
public void CreateAndRaise()
{
Pub p = new Pub();
p.OnChange += (sender, e)
=> Console.WriteLine(“Subscriber 1 called”);
p.OnChange += (sender, e)
=> { throw new Exception(); };
p.OnChange += (sender, e)
=> Console.WriteLine(“Subscriber 3 called”);
try
{
p.Raise();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.InnerExceptions.Count);
}
// Displays
// Subscriber 1 called
// Subscriber 3 called
// 1
}
If you are unable to change existing event handlers, then:
Write your own event handler, which wraps existing, for example ChannelEventCustom.
In its raise method, wrap existing event execution (for example ChannelEvent) in try-catch block
That's all. Here is short guide how to create your own events
Related
I would like to catch unhandled exceptions in a windows service application in the class that inherits from ServiceBase class.
I have already tried incorporating the code:
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
var exception = (Exception)e.ExceptionObject;
Log.Error("Unhandled exception", exception);
};
But that doesn't work.
Try this:
// Starts the application.
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// Runs the application.
Application.Run(new ErrorHandlerForm());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
string errorMsg = "An application error occurred. Please contact the adminstrator " +
"with the following information:\n\n";
// Since we can't prevent the app from terminating, log this to the event log.
if (!EventLog.SourceExists("ThreadException"))
{
EventLog.CreateEventSource("ThreadException", "Application");
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "ThreadException";
myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
}
catch (Exception exc)
{
try
{
MessageBox.Show("Fatal Non-UI Error",
"Fatal Non-UI Error. Could not write the error to the event log. Reason: "
+ exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
}
You also can take a look at this example: https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
I am unable to get the reason for this Exception:
private void bwWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (Main.bolDebugMode)
MessageBox.Show("Function DoWork is called");
if (Main.ftpsync(Main.strUsername407, Main.strPassword407, sender as BackgroundWorker) == 0)
e.Result = e.Result + "No error in " + Main.strUsername407;
else
{
if (Main.bolDebugMode)
MessageBox.Show("Errors in " + Main.strUsername407);
e.Cancel = true;
e.Result = e.Result + "Errors in " + Main.strUsername407;
if (Main.bolDebugMode)
MessageBox.Show("Errors marked");
try
{
MessageBox.Show("Next step throws exception");
return;
}
catch (Exception error)
{
if (error.ToString() != null)
MessageBox.Show(error.InnerException.Message);
}
}
}
It throws this exception:An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
The target (to my limited understanding) is the backgroundworker's RunWorkerCompleted function:
private void bwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Main.bolDebugMode)
MessageBox.Show("DoWork Completed. Break: " + e.Cancelled + " Error: " + e.Error + " Result: " + e.Result);
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
lStatus.Text = e.Error.Message;
}
else if (e.Cancelled)
lStatus.Text = "Cancelled: " + e.Result.ToString();
}
else
{
lStatus.Text = "Done! " + e.Result;
Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
pbProgress.Value = 0;
lStatus.Text = "";
}
if (Main.bolDebugMode)
MessageBox.Show("Analysis completed");
// Enable the Start button.
btnStart.Enabled = true;
// Disable the Cancel button.
btnCancel.Enabled = false;
}
public class Main
{
#region Variables
// Variables - FTP Settings
// Reading tons of variables from a appconfig file like so:
private static string StrGlobalWaitTime = ConfigurationManager.AppSettings["program_globalWaitTime"];
private static bool BolDeleteRemoteFiles = Convert.ToBoolean(ConfigurationManager.AppSettings["program_deleteremotefiles"]);
// Configuring the variables to receive and write
public static string strGlobalWaitTime
{
get { return StrGlobalWaitTime; }
set { StrGlobalWaitTime = value; }
}
#endregion
#region Main function
public static int ftpsync(string strUsername, string strPassword, BackgroundWorker bwWorker)
{
if (Directory.EnumerateFiles(strWorkDirectory, "*.pdf").Any())
{
bwWorker.ReportProgress(0, "Files left! Upload not complete");
Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
return 1;
}
However, it doesn't even reach the first debugging message box. Thus it must be happening between the return and the beginning of the function. Is he background worker not handing over directly to the RunWorkerCompleted function? Can anyone tell me what I am missing or doing wrong?
This is my first question. I will try to provide as much information as possible. Google searches for the most obvious queries have been done.
The thing to look for whenever you encounter a TargetInvocationException is the InnerException property, which will have the "real" exception.
From the look of it, it will most likely have something to do with trying to access the GUI from inside the worker's thread. Remember that when using the DoWork handler, the code executes in a different thread from the main UI's. Therefore, calls to GUI components must be either done via Invoke calls or avoided all together.
We have a cloud service using a worker role to process messages it receives from a Topic set up on Azure Service Bus.
The message itself seems to arrive intact and is usually received and processed correctly. In some instances however, the message seems to stop processing (Logging abruptly ends and no more references to the message being processed are seen in our WadLogsTable). From my research, this might be happening due to the worker role keeping its connection open and idle for longer than seconds. How would I go about preventing these long-to-process messages from being abandoned?
The code for our worker role is below.
public class WorkerRole : RoleEntryPoint
{
private static StandardKernel _kernel;
private readonly ManualResetEvent _completedEvent = new ManualResetEvent(false);
private BaseRepository<CallData> _callDataRepository;
private BaseRepository<CallLog> _callLogRepository;
private SubscriptionClient _client;
private NamespaceManager _nManager;
private OnMessageOptions _options;
private BaseRepository<Site> _siteRepository;
public override void Run()
{
try
{
List<CallInformation> callInfo;
Trace.WriteLine("Starting processing of messages");
// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
_client.OnMessage(message =>
{
// Process message from subscription.
Trace.TraceInformation("Call Received. Ready to process message ");
message.RenewLock();
callInfo = message.GetBody<List<CallInformation>>();
writeCallData(callInfo);
Trace.TraceInformation("Call Processed. Clearing from topic.");
}, _options);
}
catch (Exception e)
{
Trace.TraceInformation("Error: " + e.Message + "---" + e.StackTrace);
}
}
private void writeCallData(List<CallInformation> callList)
{
try
{
Trace.TraceInformation("Calls received: " + callList.Count);
foreach (var callInfo in callList)
{
Trace.TraceInformation("Unwrapping call...");
var call = callInfo.CallLog.Unwrap();
Trace.TraceInformation("Begin Processing: Local Call " + call.ID + " with " + callInfo.DataPoints.Length + " datapoints");
Trace.TraceInformation("Inserting Call...");
_callLogRepository.ExecuteSqlCommand(/*SNIP: Insert call*/);
Trace.TraceInformation("Call entry written. Now building datapoint list...");
var datapoints = callInfo.DataPoints.Select(datapoint => datapoint.Unwrap()).ToList();
Trace.TraceInformation("datapoint list constructed. Processing datapoints...");
foreach (var data in datapoints)
{
/*SNIP: Long running code. Insert our datapoints one at a time. Sometimes our messages die in the middle of this foreach. */
}
Trace.TraceInformation("All datapoints written for call with dependable ID " + call.Call_ID);
Trace.TraceInformation("Call Processed successfully.");
}
}
catch (Exception e)
{
Trace.TraceInformation("Call Processing Failed. " + e.Message);
}
}
public override bool OnStart()
{
try
{
var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
_nManager = NamespaceManager.CreateFromConnectionString(connectionString);
_nManager.Settings.OperationTimeout = new TimeSpan(0,0,10,0);
var topic = new TopicDescription("MyTopic")
{
DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 0, 10, 0),
DefaultMessageTimeToLive = new TimeSpan(0, 0, 10, 0),
RequiresDuplicateDetection = true,
};
if (!_nManager.TopicExists("MyTopic"))
{
_nManager.CreateTopic(topic);
}
if (!_nManager.SubscriptionExists("MyTopic", "AllMessages"))
{
_nManager.CreateSubscription("MyTopic", "AllMessages");
}
_client = SubscriptionClient.CreateFromConnectionString(connectionString, "MyTopic", "AllMessages",
ReceiveMode.ReceiveAndDelete);
_options = new OnMessageOptions
{
AutoRenewTimeout = TimeSpan.FromMinutes(5),
};
_options.ExceptionReceived += LogErrors;
CreateKernel();
_callLogRepository.ExecuteSqlCommand(/*SNIP: Background processing*/);
}
catch (Exception e)
{
Trace.TraceInformation("Error on roleStart:" + e.Message + "---" + e.StackTrace);
}
return base.OnStart();
}
public override void OnStop()
{
// Close the connection to Service Bus Queue
_client.Close();
_completedEvent.Set();
}
void LogErrors(object sender, ExceptionReceivedEventArgs e)
{
if (e.Exception != null)
{
Trace.TraceInformation("Error: " + e.Exception.Message + "---" + e.Exception.StackTrace);
_client.Close();
}
}
public IKernel CreateKernel()
{
_kernel = new StandardKernel();
/*SNIP: Bind NInjectable repositories */
return _kernel;
}
}
Your Run method does not go on indefinitely. It should look like this:
public override void Run()
{
try
{
Trace.WriteLine("WorkerRole entrypoint called", "Information");
while (true)
{
// Add code here that runs in the role instance
}
}
catch (Exception e)
{
Trace.WriteLine("Exception during Run: " + e.ToString());
// Take other action as needed.
}
}
Taken from the docs:
The Run is considered the Main method for your application. Overriding
the Run method is not required; the default implementation never
returns. If you do override the Run method, your code should block
indefinitely. If the Run method returns, the role is automatically
recycled by raising the Stopping event and calling the OnStop method
so that your shutdown sequences may be executed before the role is
taken offline.
TheDude's response is very close to the correct answer! It turns out he's right that the run method needs to stay alive instead of returning immediately. With Azure Service Bus's message pump mechanism though, you can't place the _client.onMessage(...) inside a while loop, as this results in an error (The message pump has already been initialized).
What actually needs to happen is a a manual reset event needs to be created before the worker role begins executing, and then waited after the message pump code is executed. For documentation on ManualResetEvent, see https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.110).aspx. Additionally, the process is described here: http://www.acousticguitar.pro/questions/607359/using-queueclient-onmessage-in-an-azure-worker-role
My final worker role class looks like this:
public class WorkerRole : RoleEntryPoint
{
private static StandardKernel _kernel;
private readonly ManualResetEvent _completedEvent = new ManualResetEvent(false);
private BaseRepository<CallLog> _callLogRepository;
private SubscriptionClient _client;
private MessagingFactory _mFact;
private NamespaceManager _nManager;
private OnMessageOptions _options;
public override void Run()
{
ManualResetEvent CompletedEvent = new ManualResetEvent(false);
try
{
CallInformation callInfo;
// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
_client.OnMessage(message =>
{
// Process message from subscription.
Trace.TraceInformation("Call Received. Ready to process message " + message.MessageId);
callInfo = message.GetBody<CallInformation>();
WriteCallData(callInfo);
Trace.TraceInformation("Call Processed. Clearing from topic.");
}, _options);
}
catch (Exception e)
{
Trace.TraceInformation("Error: " + e.Message + "---" + e.StackTrace);
}
CompletedEvent.WaitOne();
}
private void writeCallData(List<CallInformation> callList)
{
try
{
Trace.TraceInformation("Calls received: " + callList.Count);
foreach (var callInfo in callList)
{
Trace.TraceInformation("Unwrapping call...");
var call = callInfo.CallLog.Unwrap();
Trace.TraceInformation("Begin Processing: Local Call " + call.ID + " with " + callInfo.DataPoints.Length + " datapoints");
Trace.TraceInformation("Inserting Call...");
_callLogRepository.ExecuteSqlCommand(/*SNIP: Insert call*/);
Trace.TraceInformation("Call entry written. Now building datapoint list...");
var datapoints = callInfo.DataPoints.Select(datapoint => datapoint.Unwrap()).ToList();
Trace.TraceInformation("datapoint list constructed. Processing datapoints...");
foreach (var data in datapoints)
{
/*SNIP: Long running code. Insert our datapoints one at a time. Sometimes our messages die in the middle of this foreach. */
}
Trace.TraceInformation("All datapoints written for call with dependable ID " + call.Call_ID);
Trace.TraceInformation("Call Processed successfully.");
}
}
catch (Exception e)
{
Trace.TraceInformation("Call Processing Failed. " + e.Message);
}
}
public override bool OnStart()
{
try
{
var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
_nManager = NamespaceManager.CreateFromConnectionString(connectionString);
_nManager.Settings.OperationTimeout = new TimeSpan(0,0,10,0);
var topic = new TopicDescription("MyTopic")
{
DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 0, 10, 0),
DefaultMessageTimeToLive = new TimeSpan(0, 0, 10, 0),
RequiresDuplicateDetection = true,
};
if (!_nManager.TopicExists("MyTopic"))
{
_nManager.CreateTopic(topic);
}
if (!_nManager.SubscriptionExists("MyTopic", "AllMessages"))
{
_nManager.CreateSubscription("MyTopic", "AllMessages");
}
_client = SubscriptionClient.CreateFromConnectionString(connectionString, "MyTopic", "AllMessages",
ReceiveMode.ReceiveAndDelete);
_options = new OnMessageOptions
{
AutoRenewTimeout = TimeSpan.FromMinutes(5),
};
_options.ExceptionReceived += LogErrors;
CreateKernel();
_callLogRepository.ExecuteSqlCommand(/*SNIP: Background processing*/);
}
catch (Exception e)
{
Trace.TraceInformation("Error on roleStart:" + e.Message + "---" + e.StackTrace);
}
return base.OnStart();
}
public override void OnStop()
{
// Close the connection to Service Bus Queue
_client.Close();
_completedEvent.Set();
}
void LogErrors(object sender, ExceptionReceivedEventArgs e)
{
if (e.Exception != null)
{
Trace.TraceInformation("Error: " + e.Exception.Message + "---" + e.Exception.StackTrace);
_client.Close();
}
}
public IKernel CreateKernel()
{
_kernel = new StandardKernel();
/*SNIP: Bind NInjectable repositories */
return _kernel;
}
}
You'll notice the presence of the ManualResetEvent and the invocation of WaitOne() at the end of my Run method. I hope someone finds this helpful!
I have a Windows service that exits or crashed because of internet outage. Is there a simple way to monitor it to make sure it gets restarted automatically if it crashes?
Update
Here is the exception that we often got from the service.
An error has occured with the myservice:
Exception Message: The operation has timed out
Inner Exception:
Date Time: 11/13/2015 8:03:09 PM
Stack Trace: at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at myservice.CrmSdk.CrmService.Delete(String entityName, Guid id)
at myservice.myservice.timer1_Elapsed(Object sender, ElapsedEventArgs e)
Here is what going on into the service.
public partial class myservice : ServiceBase
{
public myservice() {
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("myservice Source"))
{
System.Diagnostics.EventLog.CreateEventSource("myservice Source", "myservice Log");
}
eventLog1.Source = "myservice Source";
eventLog1.Log = "myservice Log";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("myservice service started on " + DateTime.Now.ToString());
//timer1.Interval = 60000;
//timer1.Start();
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
int intProcessHour = Convert.ToInt32(ProcessHour);
DateTime dtNow = DateTime.Now;
if (dtNow.Hour < intProcessHour){
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}else{
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}
}
protected override void OnStop(){
eventLog1.WriteEntry("myservice service stopped on " + DateTime.Now.ToString());
}
public string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
public int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
public string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
public bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
eventLog1.WriteEntry("myservice timer1_Elapsed begin on " + DateTime.Now.ToString());
/* Create audit if not exists*/
}
catch (Exception ex)
{
eventLog1.WriteEntry("myservice - Exception Notice.\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Stack Trace: " + ex.StackTrace);
eventLog1.WriteEntry("Exception. myservice timer1_Elapsed ended on " + DateTime.Now.ToString());
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
DateTime dtStartDateTime = DateTime.Today.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now.ToString() + "\n\n" +
"Stack Trace: " + ex.StackTrace);
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]);
client.Send(message);
}
}
private void eventLog1_EntryWritten(object sender, EntryWrittenEventArgs e)
{
}
}
If you have access to the source code of the service, you should try to fix the service by adding proper error handling etc. If you do not have access to the source, you may try this.
1) Go to services
2) Right click on the service
3) Goto recovery tab
4) Select "Restart service" for first failure, 2nd failure and subsequent failures. Then click apply/ok.
Rewrite your code like this;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Mail;
using System.ServiceProcess;
using System.Timers;
namespace WindowsService1
{
public partial class myservice : ServiceBase
{
private EventLog _eventLog1;
private Timer _timer1;
public myservice()
{
InitializeComponent();
}
private void InitialiseService()
{
try
{
const string source = "myservice Source";
const string name = "myservice Log";
_eventLog1 = new EventLog();
if (!EventLog.SourceExists(source))
{
EventLog.CreateEventSource(source, name);
}
_eventLog1.Source = source;
_eventLog1.Log = name;
WriteLog("myservice service started on " + DateTime.Now);
int intProcessHour;
string processHour = ConfigurationManager.AppSettings["ProcessHour"];
var interval = (int.TryParse(processHour, out intProcessHour) && intProcessHour > 0 &&
intProcessHour < 24
? intProcessHour
: 1) * 60 * 60 * 1000;
_timer1 = new Timer(interval);
_timer1.Elapsed +=timer1_Elapsed;
_timer1.Start();
// Process(); //enable this if you want to process immidiately. Else the timer will process when it elapsed.
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void Process()
{
try
{
GetParentAccountID("xxx");
GetAuditGrade("yyyy");
GetAuditID("tttt", "45354345");
AuditRecordExists("rrrr", DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
SendEmail(ex);
}
}
private string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
private int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
private string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
private bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
WriteLog("myservice timer1_Elapsed started at " + DateTime.Now);
Process();
WriteLog("myservice timer1_Elapsed finished at " + DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
private void SendEmail(Exception ex)
{
try
{
using (SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]))
{
using (MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now + "\n\n" +
"Stack Trace: " + ex.StackTrace))
{
client.Send(message);
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
private void WriteLog(string logEntry)
{
try
{
if (!string.IsNullOrEmpty(logEntry) && _eventLog1 != null)
_eventLog1.WriteEntry(logEntry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStart(string[] args)
{
try
{
InitialiseService();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStop()
{
try
{
_timer1.Stop();
_timer1.Elapsed -= timer1_Elapsed;
WriteLog("myservice service stopped on " + DateTime.Now);
_eventLog1.Close();
_eventLog1.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
I am trying to update the TextBox and ListView simultaneously. However, I cannot. The Listview is updating, but the TextBox is only updating sometimes.
private void updateGUI(ISynchronizeInvoke asyncInvoke, Action action)
{
try
{
if (!asyncInvoke.InvokeRequired)
action();
else
asyncInvoke.BeginInvoke(action, new object[] { });
}
catch (Exception ex)
{
Console.WriteLine("update gui error: " + ex.Message);
}
}
// CallBack for update GUI
private void onProgressChange(object source, DownloadEventArgs e)
{
// Update ListView and TextBox
this.updateGUI
(
this.lstDownloads,
() =>
{
this.downloadTotalSize += e.currentDlBytes;
this.lstDownloads.Items[e.downloadIndex].SubItems[1].Text = e.downloadBytes;
this.lstDownloads.Items[e.downloadIndex].SubItems[2].Text = e.downloadProgress + "%";
this.lblDownloadSize.Text = e.downloadBytes + " / " + this.downloadTotalSize
}
);
}
Can someone explain what I'm doing wrong? Sorry for typos. Regards.