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...
...
}
Related
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...
I'm writing a windows service (C#) that does a task repetitively. I'm using a thread to complete my requirement. Now I need to maintain a log file that keeps logs regarding the operation.
My service class is as follow
public partial class CPEService : ServiceBase
{
static ServiceBot bot = new ServiceBot();
static ProgramLog logger = new ProgramLog();//ProgramLog Object
private static bool state = true;
//private static int count = 1;
//private System.Timers.Timer timer;
public CPEService()
{
InitializeComponent();
}
internal void TestStartupAndStop()
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
protected override void OnStart(string[] args)
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
private void loopTrough()
{
logger.log("Thread fired");
while (state)
{
logger.log("Thread fired"); //This is not Working
bot.start();
Thread.Sleep(180000);
}
}
protected override void OnStop()
{
state = false;
}
}
I have a separate class call "ProgramLog" to handle all the log related operations.This is that class.
public class ProgramLog
{
string fileName = "";//Global variable to store file name
#region method to handle usual log records
public void log(string text)//create normal Log text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory+fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine(text);
tw.Flush();
tw.Close();
fs.Close();
}
}
else
{
createFolder();
log(text);
}
}
#endregion
#region log Error record
public void logError(string text, string className,int LineNumber, string Stacktrace)//create error text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("**************************ERROR****************************");
tw.WriteLine(text);
tw.WriteLine("In Class :{0}", className);
tw.WriteLine("In Line :{0}", LineNumber);
tw.WriteLine("ERROR :{0}",Stacktrace);
tw.WriteLine("***********************************************************");
}
}
else
{
createFolder();
logError(text,className,LineNumber,Stacktrace);
}
}
#endregion
#region create folder to store log files
public void createFolder()//create a folder for Log files
{
try
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log"))
{
string folderName = "Log";
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + folderName);
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
#endregion
}
According to the above class, When I start the service it needs to create folder call "Log" where it does not exists, then it creates a text file inside that folder and lastly it starts to create the log entries.
Even though the thread is working correctly it never touches the "ProgramLog" methods. I checked by directly calling the method "loopTrough". then its working fine.
Please help me to resolve this bug.
Thank you
You declare a Thread workerThread = new Thread(loopTrough);, but you don't start this Thread. Just call workerThread.Start().
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
}
I am working on this GUI for serial port application. I recently added stop and wait protocols to the application. Surprisingly my disconnect button stopped working. I have thought through the logic and I have not been able to find the problem.
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public bool packetreceived = false;
private SerialPort sp = null; //<---- serial port at form level
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//delegate variable to disconnect
public AddDataDelegate disconnectDelegate = null;
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
}
/**
* Takes byte array and returns a string representation
*
*/
public String parseUARTData(byte[] data)
{
if (data.Length == 11)
{
String rv = "";
DataFields d = new DataFields();
if (!packetreceived)
{
d = mainLogic.parseData(data);
packetreceived = true;
}
//TODO
System.Threading.Thread.Sleep(5000);
if (d.sequence == 0)
{
sp.Write("1\r\n");
}
else
{
sp.Write("0\r\n");
}
packetreceived = false;
//now display it as a string
rv += STR_OPCODE + " = " + d.opcode + "\n";
rv += STR_CRC + " = " + d.crc + "\n";
rv += STR_SEQ + " = " + d.sequence + "\n";
rv += STR_FLAGS + " = " + d.flags + "\n";
rv += STR_TEMP + " = " + d.temperature + "\n";
rv += STR_HUMID + " = " + d.humidity + "\n";
rv += STR_PH + " = " + d.ph + "\n";
return rv + "\n\n";
}
else
{
return Encoding.ASCII.GetString(data);
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s = sp.ReadExisting();
if (disconnectDelegate != null)
{
disconnectDelegate.Invoke(s);
}
richTextBox1.Invoke(this.myDelegate, new Object[] { parseUARTData(Encoding.ASCII.GetBytes(s)) });
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
//sp.PortName = this.comboBox1.SelectedItem.ToString();
sp.Open();
}
// send data to port
sp.Write("####,###########\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (sp.IsOpen)
{
// send data to port
sp.Write("+++\r\n");
//add the delegate
disconnectDelegate = new AddDataDelegate(onDisconnect);
//sp.WriteTimeout = 500;
// sp.Write("####,0\r\n");
}
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (string port in ports)
//{
// comboBoxSerialPorts.Items.Add(port);
//}
}
private void onDisconnect(string msg)
{
string trimmedMsg = msg.Trim();
if (trimmedMsg.Equals("OK"))
{
//send the second time
sp.Write("##,0\r\n");
//null the object
disconnectDelegate = null;
}
}
private void comPort_Click(object sender, EventArgs e)
{
try
{
if (sp.IsOpen)
{
//send data to port
sp.Write("1\r\n");
MessageBox.Show("bluetooth is transmitting data...");
//message box telling user that you are asking for data.
}
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
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();
}
}
}