Accessing ui element in other thread wpf - c#

I need to access TextBoxes in my WPF application from another thread and I've got an exception. I know, there is a property Dispatcher in every UI control and a method BeginInvoke , but I don't know how to get values from TextBoxes.
So, here is the code:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
try
{
var task = new Task(() => TryConnect());
task.Start();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void TryConnect()
{
try
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text +
";Database=hospital;Uid=" + login.Text +
";Pwd=" + password.Text + ";";
using (MySqlConnection mcon = new MySqlConnection(con_str))
{
mcon.Open();
MessageBox.Show("Connection is OK!");
mcon.Close();
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ErrorCode.ToString() + " " + ex.Message);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

If you create a copy of the values you need, then you should be able to access them:
string username = login.Text, password = password.Text, ip = Ip.Text, port = Port.Text;
var task = new Task(() => TryConnect(username, password, ip, port));
And:
void TryConnect(string username, string password, string ip, string port)
{
// ...
}
Copying the values locally like this means you don't need to access UI elements from your background thread.

To answer your question, move the connection string build out of the task action:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
try
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text + ";Database=hospital;Uid=" + login.Text + ";Pwd=" + password.Text + ";";
var task = new Task(() => TryConnect(con_str));
task.Start();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void TryConnect(string con_str)
{
try
{
using (MySqlConnection mcon = new MySqlConnection(con_str))
{
mcon.Open();
MessageBox.Show("Connection is OK!");
mcon.Close();
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ErrorCode.ToString() + " " + ex.Message);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
But you have a lot of issues in this code.
Code behind in WPF is not "Best practice"
Try and have a look at this:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MessageBox on another thread can cause a lot of pain.
you are trying to catch an exception around the task creation, this will not catch exceptions thrown inside the action.
Try this instead:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text + ";Database=hospital;Uid=" + login.Text + ";Pwd=" + password.Text + ";";
var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
var task = new Task(() => TryConnect(con_str));
task.ContinueWith(task1 =>
{
//TODO Handle exception
System.Diagnostics.Trace.WriteLine(task1.Exception);
//or if you really want an messageBox, pass it back to the ui thread
dispatcher.Invoke(() => MessageBox.Show(task1.Exception.Message));
}, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
}

Related

Win Forms Global Exception Handling

i'm trying to do globalexceptionhandling, i've already tried 3 methods to do this but nothing caught an exception thrown somewhere in the program
static void Main()
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Catch);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(Catch);
try
{
Application.Instance.Start();
}
catch (Exception ex)
{
StackTrace st = new StackTrace(ex, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender sender = new SyslogUdpSender("localhost", 514);
sender.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
}
static void Catch(object sender, System.Threading.ThreadExceptionEventArgs e)
{
StackTrace st = new StackTrace(e.Exception, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender send = new SyslogUdpSender("localhost", 514);
send.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
static void Catch(object sender, UnhandledExceptionEventArgs e)
{
StackTrace st = new StackTrace((Exception)e.ExceptionObject, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender send = new SyslogUdpSender("localhost", 514);
send.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
this is what i've already tried, nothing caught the exception.
and i'm not using the standard application.run method, i'm using a singleton class to start from, where for every view(form) i have a presenter gets created in which the view gets created
does anyone know how to do globalexception handling with this setup?
also, sorry for my bad english
best regards
EDIT: MVCE
namespace Application
{
static class Program
{
static void Main()
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Catch);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(Catch);
try
{
Application.Instance.Start();
}
catch (Exception ex)
{
//do some catching
}
}
static void Catch(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//do some catching
}
static void Catch(object sender, UnhandledExceptionEventArgs e)
{
//do some catching
}
}
public class Application
{
private static Application _instance;
private Application()
{
}
public static Application Instance
{
get
{
return _instance ?? (_instance = new Application());
}
}
internal void Start()
{
StartOverviewWindow();
}
private void StartOverviewWindow()
{
throw new Exception();
}
}
}
As a quick answer (because I can't find duplicates for all of those), to handle
an exception thrown somewhere
you have to handle following events:
Application.ThreadException += ...
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += ...
// tasks exceptions, add in app.config:
// <runtime>
// <ThrowUnobservedTaskExceptions enabled="true"/>
// </runtime>
TaskScheduler.UnobservedTaskException += ...
For difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException see this.

How do I restart windows services if it is crashes because of internet outage

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);
}
}
}
}

Why is my web socket receiving data packets in the wrong order?

I have a C# desktop app that sends jpegs to my server at the rate of 10 per second.
Each jpeg has the time stamp as part of its header and is read by my server.
I am experiencing a disorderly arrival on my server.
the majority of the time the jpegs are received by my sever in the order they have been sent by my client.
But, every now and then the order becomes 'jumbled'.
Are TCP packets supposed to be guaranteed to be sent in order or is it subject to delays by the network/internet?
If the order is guaranteed then I will post my code.
Thanks
My Code:
On Client:
class WebSocketClient
{
static WebSocket websocket = null;
public static void Start()
{
try {
Console.WriteLine("Started At: " + DateTime.Now.ToString());
if (websocket != null)
{
websocket.Dispose();
}
websocket = new WebSocket("ws://a uri");
websocket.Opened += new EventHandler(webSocketClient_Opened);
websocket.Error += websocket_Error;
websocket.Closed += new EventHandler(webSocketClient_Closed);
websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
websocket.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#8");
}
}
private static bool TimeOutOccured = false;
private static DateTime stopped;
public static void Send(byte[] packet)
{
try
{
if (websocket.State == WebSocketState.Open)
{
if (packet != null)
{
websocket.Send(packet, 0, packet.Length);
}
TimeOutOccured = false;
}
else
{
if (TimeOutOccured)
{
Console.WriteLine("TimeOut At: " + DateTime.Now.ToString());
if ((DateTime.Now - stopped).TotalSeconds > 30)
{
websocket.Opened -= new EventHandler(webSocketClient_Opened);
websocket.Error -= websocket_Error;
websocket.Closed -= new EventHandler(webSocketClient_Closed);
websocket.MessageReceived -= new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
Start();
}
}
else
{
TimeOutOccured = true;
stopped = DateTime.Now;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#9");
}
}
static void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs ex)
{
try {
Console.WriteLine("Error At: " + DateTime.Now.ToString());
Shared.AddError("WebSocketClient.websocket_Error", ex.Exception);
}
catch (Exception x)
{
Console.WriteLine(x.ToString() + " DEBUG#10");
}
}
protected static void webSocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try {
var m_CurrentMessage = e.Message;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#11");
}
}
protected static void webSocketClient_Closed(object sender, EventArgs e)
{
try
{
Console.WriteLine("Closed At: " + DateTime.Now.ToString());
if (websocket.State == WebSocketState.Closed)
{
System.Threading.Thread.Sleep(1000);
Start();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#12");
}
}
protected static void webSocketClient_Opened(object sender, EventArgs e)
{
Console.WriteLine("Opened At: " + DateTime.Now.ToString());
}
}
My Server Code:
public void Start2()
{
try
{
var server = new WebSocketServer("my wan uri");
ILog logger = LogManager.GetLogger(typeof(FleckLog));
FleckLog.LogAction = (level, message, ex) =>
{
switch (level)
{
case LogLevel.Debug:
//gger.Debug(message, ex);
break;
case LogLevel.Error:
SocketMessage("3", message, ex);
break;
case LogLevel.Warn:
SocketMessage("4", message, ex);
break;
default:
SocketMessage("5", message, ex);
break;
}
};
server.Start(socket =>
{
socket.OnOpen = () => evStatusChanged("Open!");
socket.OnClose = () => evStatusChanged("Close!");
socket.OnError = error =>
{
Console.WriteLine("DEBUG:1 " + error.ToString());
};
socket.OnBinary = packetIn =>
{
try
{
//i check my timestamps in my headers here
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " ServerWebSocket.WebSocketServer_NewDataReceived.Catch3");
}
};
socket.OnMessage = message =>
{
};
});
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " ServerWebSocket.Start2");
}
}
I am using the WebSocket4Net for my client socket framework

How to log exception to file

I have been trying to log exceptions to a file. I can get the exception with all its details and when I step through the class the StreamWriter logWriter doesn't seem to do what I thought it would do.
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
StreamWriter logWriter;
if (File.Exists(logfile))
{
logWriter = File.AppendText(logfile);
}
else
{
logWriter = File.CreateText(logfile);
logWriter.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
logWriter.Close();
throw exception;
}
}
catch (Exception e)
{
throw;
}
}
I would of thought the logWriter would of written the exception details to the File.AppendText(logfile)but it doesn't and just jumps straight out the if statement. All the details of the exception are in the else statement, I have tried to put this in theif` condition but throws an exception!
How can I write the exception to the file. I got the code from CodeProject. Everything thing works fine except writing the exception to the file.
Try it correctly and throw the exception outside of the method:
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
if(File.Exists(logfile))
{
using(var writer = new StreamWriter(logfile, true))
{
writer.WriteLine(
"=>{0} An Error occurred: {1} Message: {2}{3}",
DateTime.Now,
exception.StackTrace,
exception.Message,
Environment.NewLine
);
}
}
}
catch(Exception e)
{
throw;
}
}
Throw it outside:
catch(Exception e)
{
Write(e);
throw;
}
This snippet works to write into a file
public static bool WriteResult(string result)
{
using (StreamWriter sr = File.AppendText("result.txt"))
{
sr.WriteLine(result);
sr.Flush();
return true;
}
return false;
}
For you, you have to adapt it a bit to meet your requirments :
public static void Write(Exception exception) {
try {
using(StreamWriter sr = File.AppendText("result.txt")) //new StreamWriter("result.txt", Encoding. ))
{
sr.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
sr.Flush();
}
catch (Exception e) {
throw;
}
}
A nice template method i wrote goes with every project.
private static void AddLog(string strMsg)
{
#region logfolder creation
if (!System.IO.Directory.Exists("C:\\appname"))
{
System.IO.Directory.CreateDirectory("C:\\appname");
if (!System.IO.Directory.Exists("C:\\appname\\Logs"))
{
System.IO.Directory.CreateDirectory("C:\\appname\\Logs");
}
}
#endregion
#region logfile creation
FileStream fsc;
logFileName = "C:\\appname\\Logs\\appnameLog_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
if (!System.IO.File.Exists(logFileName))
{
fsc = new FileStream(logFileName, FileMode.Create, FileAccess.Write);
fsc.Close();
}
#endregion
#region logging
using (FileStream fs = new FileStream(logFileName, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fs))
{
try
{
sr.WriteLine(strMsg);
}
catch (Exception exc)
{
EventLogEntry(exc.ToString().Trim(), EventLogEntryType.Error, 7700);
}
}
}
#endregion
}

FTP download backgroundworker

I have this code but it's not working...
The progressbar is not moving and the downloaded file size is 0kb.
I think I have some problem in my WHILE loop! How can I solve this problem? Please give me instructions!
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DirectoryInfo folder= new DirectoryInfo(#"C:\Cloud24");
try
{
{
long size= 0;
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(userid, userpass);
FileStream file = File.Create(folder+ "//" + downloadname);
byte[] filedata = request.DownloadData(ftpadress + "/" + downloadname);
while ((size= file.Read(filedata, 0, filedata.Length)) > 0)
{
file.Write(filedata, 0, filedata.Length);
size += (int)filedata.Length;
double dProgressPercentage = ((double)(size) / (double)filedata.Length);
backgroundWorker1.ReportProgress((int)(dProgressPercentage * 100));
}
file.Close();
MessageBox.Show(downloadname + " downloaded!" +
Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}
This should probably work, but I haven't actually tested it.
private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var folder = new DirectoryInfo(#"C:\Cloud24");
try
{
{
var manualResetEvent = new ManualResetEventSlim();
var client = new WebClient { Credentials = new NetworkCredential(userid, userpass) };
client.DownloadProgressChanged += (o, args) => backgroundWorker1.ReportProgress(args.ProgressPercentage);
client.DownloadDataCompleted += (o, args) => manualResetEvent.Set();
var filedata = client.DownloadDataAsync(ftpadress + "/" + downloadname);
manualResetEvent.Wait();
using (var stream = File.Create(folder + "//" + downloadname))
{
await stream.WriteAsync(filedata, 0, filedata.Length);
}
MessageBox.Show(downloadname + " downloaded!" + Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}

Categories

Resources