GetProcessesByName stops my events in outlook - c#

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

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.

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

windows service exception and stop my service

My Service read from com port and save the info in DB.It works perfectly fine for a while,but sometimes the error window is appeared for getting an exception,and if I don't click 'no' buttun , it doesn't read from com port.When I check in event viewer,I see some exception number 7034,7031 on my service.I log every where in my code and I use try,catch .I don't have ant catch in my log file,so I can't understand what is the problem?
public partial class Service1 : ServiceBase
{
string _fileName = #"c:\logSensor\log.ini";
internal delegate void StringDelegate(string data);
ArrayList lines = new ArrayList();
BL.EnterDatas eData = new BL.EnterDatas();
private class Line
{
public string Str;
public Line(string str)
{
Str = str;
}
}
public Service1()
{
InitializeComponent();
CommPort com = CommPort.Instance;
com.Open();
com.StatusChanged += OnStatusChanged;
com.DataReceived += OnDataReceived;
timer1.Enabled = true;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() +
" . " + "Step1:Load ");
writer.Flush();
}
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "timer1_Elapsed:Stop Timer ");
writer.Flush();
}
ReadLog();
StreamReader sr = new StreamReader(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\path.txt");
string _logPath = sr.ReadLine();
FileStream fs = new FileStream(_logPath, FileMode.Open);
fs.SetLength(0);
fs.Close();
}
catch (Exception ex)
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "Catch:timer1_Elapsed " + ex.Message);
writer.Flush();
}
}
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "final:timer1_Elapsed ");
writer.Flush();
}
timer1.Start();
}
#region Functions...
...
}

Login and Logoff details

I am working in a C# application.How can i get the log-of and log-in details of each users logging into a system as windows service using c#? Now I am getting only the login and logoff details while system shutdown and startup.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using System.Management;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Web;
using System.Runtime.InteropServices;
using System.Windows.Forms;
//using System.Configuration;
namespace WinServiceAcc
{
public partial class WinServiceAcc : ServiceBase
{`
[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);
System.Timers.Timer timer = new System.Timers.Timer();
public String UserName { get; set; }
public String Password { get; set; }
public WinServiceAcc()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
//DirectoryEntry dir = new DirectoryEntry("LDAP://production");
//base.OnStart(args);
//UserName = args[0];
//Password = args[1];
Startup();
// Password = (string)collection.Cast<ManagementBaseObject>().First()["Password"]; }
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private void Startup()
{
timer.Enabled = true;
timer.Interval = 60000;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
UserName = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
timer.Elapsed += new ElapsedEventHandler(onElapsedTime);
TraceService("Service started");
}
protected override void OnStop()
{
timer.Enabled = false;
TraceService("Service stoped");
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
//TraceService("Logout Uname: " + UserName + " on " + DateTime.Now.ToString("dd/MM/yyyy") + " at " + DateTime.Now.ToString("hh:mm tt"));
//timer.Enabled = false;
}
protected override void OnPause()
{
ExitWindowsEx(0, 0);
Application.SetSuspendState(PowerState.Hibernate, true, true);
TraceService("Logout Uname: " + UserName + " on " + DateTime.Now.ToString("dd/MM/yyyy") + " at " + DateTime.Now.ToString("hh:mm tt"));
timer.Enabled = false;
}
protected override void OnContinue()
{
ExitWindowsEx(2, 0);
TraceService("Login Uname: " + UserName + " on " + DateTime.Now.ToString("dd/MM/yyyy") + " at " + DateTime.Now.ToString("hh:mm tt"));
timer.Enabled = false;
}
protected override void OnShutdown()
{
ExitWindowsEx(1, 0);
TraceService("Logout Uname: " + UserName + " on " + DateTime.Now.ToString("dd/MM/yyyy") + " at " + DateTime.Now.ToString("hh:mm tt"));
timer.Enabled = false;
}
private void onElapsedTime(object sender, ElapsedEventArgs e)
{
TraceService("Login as Uname: " + UserName + " on " + DateTime.Now.ToString("dd/MM/yyyy") + " at " + DateTime.Now.ToString("hh:mm tt"));
timer.Enabled = false;
}
private void TraceService(string content)
{
FileStream fs = new FileStream(#"c:\ServicesList.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
}
}

Categories

Resources