Win Forms Global Exception Handling - c#

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.

Related

GetProcessesByName stops my events in outlook

I wrote a program which syncs my Outlook calendar. So good so far the program works fine. But if Outlook crashes or gets restarted my program does need to fire "ThisAddin_Startup()" again to link to the new outlook instance. I tried so solve this by monitoring the running processes. But then it didn't work any more. If I call "Process.GetProcessesByName" in the loop nothing works it its commented then it does work.
Does anyone know why?
bool monitoring = false;
while (true)
{
if (!monitoring) //Start monitoring or restart monitoring
{
Debug.WriteLine("start");
ThisAddIn_Startup();
monitoring = true;
}
Process[] outlook;
outlook = Process.GetProcessesByName("blabla");
Thread.Sleep(1000);
}
private void ThisAddIn_Startup()
{
_OutlookApplication = new Outlook.Application();
//Link Inbodx Events
_olFolderInbox.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Change);
//Link Calendar Events
_olFolderCalendar.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Add);
_olFolderCalendar.Items.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(Item_Calendar_Change);
_olFolderCalendar.Items.ItemRemove += new Outlook.ItemsEvents_ItemRemoveEventHandler(Item_Calendar_Deleted);
}
EDIT:
Simplified the hole code still nothing works:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
namespace OAddIn
{
public partial class Form1 : Form
{
Outlook.Application _OutlookApplication;
Outlook.MAPIFolder _olFolderInbox;
Outlook.MAPIFolder _olFolderCalendar;
Outlook.MAPIFolder _olFolderCalendar_AddOnCalendar;
Outlook.MAPIFolder _olFolderDeletedItems;
public Form1()
{
InitializeComponent();
Thread osThread = new Thread(ThisAddIn_Startup);
osThread.Start();
Thread osThread2 = new Thread(CheckIfProcessIsRunning);
osThread2.Start();
}
private void ThisAddIn_Startup()
{
_OutlookApplication = new Outlook.Application();
InitCalendars();
InitMailBox();
Debug.WriteLine("Start Now Monitoring");
//Link Inbodx Events
_olFolderInbox.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Change);
//Link Calendar Events
_olFolderCalendar.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Add);
_olFolderCalendar.Items.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(Item_Calendar_Change);
_olFolderCalendar.Items.ItemRemove += new Outlook.ItemsEvents_ItemRemoveEventHandler(Item_Calendar_Deleted);
}
void CheckIfProcessIsRunning()
{
while (true)
{
int returnValue = 0;
Process[] o = Process.GetProcessesByName("OUTLOOK");
Debug.WriteLine("FSSFSSGSFSFSFSFSFSF: " + returnValue);
Thread.Sleep(3000);
}
}
private void InitCalendars()
{
Outlook.MAPIFolder calendars = (Outlook.MAPIFolder)_OutlookApplication.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
try
{
_olFolderCalendar_AddOnCalendar = calendars.Folders["AddOnCalendar"]; //AddOn calendar
}
catch
{
_olFolderCalendar_AddOnCalendar = calendars.Folders.Add("AddOnCalendar");
}
_olFolderCalendar = calendars; //Standard calendar
}
private void InitMailBox()
{
_olFolderInbox = (Outlook.MAPIFolder)_OutlookApplication.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
_olFolderDeletedItems = (Outlook.MAPIFolder)_OutlookApplication.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems);
}
void Item_Calendar_Add(object item)
{
Debug.WriteLine("");
Debug.WriteLine("------ Item_Calendar_Add() ----------------------------------------------");
PrintImportantInfo(item);
}
public void Item_Calendar_Change(object item)
{
Debug.WriteLine("");
Debug.WriteLine("------ Item_Calendar_Change() ----------------------------------------------");
PrintImportantInfo(item);
}
void Item_Calendar_Deleted()
{
Debug.WriteLine("");
Debug.WriteLine("------ Item_Calendar_Deleted() ---------------------------------------------");
object item = _olFolderDeletedItems.Items.GetLast();
PrintImportantInfo(item);
}
void PrintImportantInfo(object item)
{
try
{
Outlook.AppointmentItem appointment = item as Outlook.AppointmentItem;
if (appointment != null)
{
Debug.WriteLine("APPOINTMENTINFO_________________________________________________________");
Debug.WriteLine(" A_Subject: " + appointment.Subject.ToString());
Debug.WriteLine(" A_MeetingStatus: " + appointment.MeetingStatus.ToString());
Debug.WriteLine(" A_ResponseStatus: " + appointment.ResponseStatus.ToString());
Debug.WriteLine(" A_GlobalAppointmentID: " + appointment.GlobalAppointmentID.ToString());
Debug.WriteLine(" A_Time: " + appointment.Start.ToString() + " - " + appointment.End.ToString());
Debug.WriteLine(" A_Organizer: " + appointment.GetOrganizer().Address.ToString());
Debug.WriteLine(" A_Organizer: " + appointment.Organizer);
if (appointment.Location != null)
Debug.WriteLine(" A_Location: " + appointment.Location.ToString());
}
Outlook.MeetingItem meeting = item as Outlook.MeetingItem;
if (meeting != null)
{
Debug.WriteLine("MEETINGINFO_____________________________________________________________");
Debug.WriteLine(" M_Subject: " + meeting.Subject.ToString());
Debug.WriteLine(" M_MessageClass: " + meeting.MessageClass.ToString());
Debug.WriteLine(" M_SenderEmailAddress: " + meeting.SenderEmailAddress.ToString());
appointment = meeting.GetAssociatedAppointment(false);
if (appointment != null)
{
Debug.WriteLine("APPOINTMENTINFO_________________________________________________________");
appointment.Save();
Debug.WriteLine(" A_Subject: " + appointment.Subject.ToString());
Debug.WriteLine(" A_MeetingStatus: " + appointment.MeetingStatus.ToString());
Debug.WriteLine(" A_ResponseStatus: " + appointment.ResponseStatus.ToString());
Debug.WriteLine(" A_GlobalAppointmentID: " + appointment.GlobalAppointmentID.ToString());
Debug.WriteLine(" A_Time: " + appointment.Start.ToString() + " - " + appointment.End.ToString());
Debug.WriteLine(" A_Organizer: " + appointment.GetOrganizer().Address.ToString());
Debug.WriteLine(" A_Organizer: " + appointment.Organizer.ToString());
if (appointment.Location != null)
Debug.WriteLine(" A_Location: " + appointment.Location.ToString());
}
}
}
catch { }
}
}
}
Have you tried doing each action within a separate thread?
bool monitoring = false;
while (true)
{
if (!monitoring) //Start monitoring or restart monitoring
{
Debug.WriteLine("start");
ThisAddIn_Startup();
monitoring = true;
}
Process[] outlook;
new Thread(() => {
outlook = Process.GetProcessesByName("blabla");
}.Start();
Thread.Sleep(1000);
}
private void ThisAddIn_Startup()
{
_OutlookApplication = new Outlook.Application();
//Link Inbodx Events
_olFolderInbox.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Change);
//Link Calendar Events
_olFolderCalendar.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Item_Calendar_Add);
_olFolderCalendar.Items.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(Item_Calendar_Change);
_olFolderCalendar.Items.ItemRemove += new Outlook.ItemsEvents_ItemRemoveEventHandler(Item_Calendar_Deleted);
}

C#, WPF-application, many tcpclients connect a tcplistener(server)

TcpServer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Server
{
public class TcpServer
{
static ServerGUI serverGUI;
private const Int32 PORT = 13000;
private const String ADDRESS = "127.0.0.1";
private IPAddress localAddress;
public TcpListener tcpServer;
private static Byte[] bytes;
private static String data;
static DateTime localDate;
static String cultureName = "de-DE";
static CultureInfo cultureInfo;
private static int clientCount = 0;
private const char SEPERATOR = '|';
static NetworkStream stream;
public TcpServer()
{
serverGUI = new ServerGUI();
serverGUI.Show();
cultureInfo = new CultureInfo(cultureName);
BackgroundWorker worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(Worker1_DoWork);
worker1.RunWorkerAsync();
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
localAddress = IPAddress.Parse(ADDRESS);
tcpServer = new TcpListener(localAddress, PORT);
localDate = DateTime.Now;
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") chatserver has started.\n");
tcpServer.Start();
while (true)
{
TcpClient client = await tcpServer.AcceptTcpClientAsync();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
}));
}
catch (SocketException socketEx)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(socketEx.Message + "\n");
}));
}
catch (Exception ex)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(ex.Message + "\n");
}));
}
finally
{
if (tcpServer != null)
{
tcpServer.Stop();
}
}
}
private static async void ThreadProc(object obj)
{
await serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(async delegate ()
{
var client = (TcpClient)obj;
bytes = new Byte[256];
data = null;
// Get a stream object for reading and writing
stream = client.GetStream();
int i = 0;
while (true)
{
if (stream.CanRead)
{
i = await stream.ReadAsync(bytes, 0, bytes.Length);
}
localDate = DateTime.Now;
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] receivedStr = data.Split(SEPERATOR);
byte[] msg = null;
if (receivedStr != null && receivedStr[0] == "new")
{
clientCount++;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Welcome, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") new client recognized!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
}
else if (receivedStr != null && receivedStr[0] == "close")
{
clientCount--;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Goodbye, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") client disconnected!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
client.Close();
break;
}
else
{
msg = System.Text.Encoding.ASCII.GetBytes(data);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
}
}));
}
}
}
(Client)MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Client
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Int32 port = 13000;
private String hostname = "127.0.0.1";
public TcpClient tcpClient;
DateTime localDate;
String cultureName = "de-DE";
CultureInfo cultureInfo;
BackgroundWorker worker1;
NetworkStream stream;
bool work = false;
private const char SEPERATOR = '|';
public MainWindow()
{
InitializeComponent();
buttonDisconnect.IsEnabled = false;
textBoxServerIP.Text = "127.0.0.1:13000";
textBoxNickname.Text = "User";
cultureInfo = new CultureInfo(cultureName);
worker1 = new BackgroundWorker();
worker1.DoWork += Worker1_DoWork;
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
try
{
while (work)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hallo");
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = 0;
if (stream.CanRead)
{
bytes = await stream.ReadAsync(data, 0, data.Length);
}
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
string[] receivedStr = responseData.Split(SEPERATOR);
if (receivedStr != null && receivedStr[0] == "chatserver")
{
textBoxChatRoom.Text += receivedStr[0] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[1] + "\n\n";
}
else if (receivedStr != null && receivedStr[0] == "msg")
{
textBoxChatRoom.Text += receivedStr[1] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[2] + "\n";
}
else
{
textBoxChatRoom.Text += responseData + "\n\n";
}
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}));
}
private async void buttonConnect_Click(object sender, RoutedEventArgs e)
{
string[] connectionStr = { "" };
if (!textBoxServerIP.Text.Equals(null) && textBoxServerIP.Text != "")
{
connectionStr = textBoxServerIP.Text.Split(':');
try
{
hostname = connectionStr[0];
port = Int32.Parse(connectionStr[1]);
tcpClient = new TcpClient(connectionStr[0], Int32.Parse(connectionStr[1]));
//localDate = DateTime.Now;
textBoxChatRoom.Text += "Connecting to server " + connectionStr[0] + "...\n";
if (tcpClient.Connected)
{
textBoxChatRoom.Text += "Connected!\n";
textBoxServerIP.IsEnabled = false;
textBoxNickname.IsEnabled = false;
buttonConnect.IsEnabled = false;
buttonDisconnect.IsEnabled = true;
localDate = DateTime.Now;
stream = tcpClient.GetStream();
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("new" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
work = true;
worker1.RunWorkerAsync();
}
else
{
textBoxChatRoom.Text += "not connected!\n";
}
}
catch (ArgumentNullException argumentNullExceptionEx)
{
textBoxChatRoom.Text += argumentNullExceptionEx.Message + "\n";
}
catch (ArgumentOutOfRangeException argumentOutOfRangeEx)
{
textBoxChatRoom.Text += argumentOutOfRangeEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (FormatException formatEx)
{
textBoxChatRoom.Text += formatEx.Message + "\n";
}
catch (OverflowException overflowEx)
{
textBoxChatRoom.Text += overflowEx.Message + "\n";
}
catch (CultureNotFoundException cultureNotFoundEx)
{
textBoxChatRoom.Text += cultureNotFoundEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
else
{
textBoxChatRoom.Text += "Please enter serverip!\n";
}
}
private async void buttonDisconnect_Click(object sender, RoutedEventArgs e)
{
work = false;
buttonConnect.IsEnabled = true;
textBoxServerIP.IsEnabled = true;
textBoxNickname.IsEnabled = true;
buttonDisconnect.IsEnabled = false;
byte[] msg = System.Text.Encoding.ASCII.GetBytes("close" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
private void buttonExit_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private async void buttonSend_Click(object sender, RoutedEventArgs e)
{
try
{
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("msg" + SEPERATOR + textBoxNickname.Text.ToString() + SEPERATOR + textBoxSend.Text);
stream = tcpClient.GetStream();
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
}
}
The connection between server and clients functions but if I send something into the networkstream with one client, the other clients don't receive anything. This should be a little chatroom-WPF-application
I have a problem, that i couldn't receive and send between multiple clients and I don't know what I am doing wrong...
Please can somebody help...

Multithread using backgroundworker and event handler

I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response

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

Accessing ui element in other thread wpf

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

Categories

Resources