Running the windows service for every 5 Min - c#

I had created a windows service & Done with successful installation.
I had observed that even though the installation was done, but the service is not showing in the list of services.msc also How could I make the service the to run for every 5 min of interval.
Worked upto the part of installation of the service.
public partial class FeedbcakSMSToDCService : ServiceBase
{
DBBase obj = new DBBase();
Thread threadPRSender;
string fileName = "D:\\FeedbackSMSlog.txt";
System.Timers.Timer timer = new System.Timers.Timer();
System.Timers.Timer TimerObj = new System.Timers.Timer();
FeedBackSMSToDCHandler feedbackSmstoDcHandler = null;
EventLog m_EventLog = new EventLog();
ThreadStart threadSender = null;
FeedBackSMSToDCHandler FB = new FeedBackSMSToDCHandler();
public FeedbcakSMSToDCService()
{
InitializeComponent();
feedbackSmstoDcHandler = new FeedBackSMSToDCHandler();
threadSender = new ThreadStart(ProcessSMSToDC);
threadPRSender = new Thread(threadSender);
}
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new FeedbcakSMSToDCService()
};
ServiceBase.Run(ServicesToRun);
}
protected override void OnStart(string[] args)
{
try
{
System.Diagnostics.Debugger.Launch();
if (File.Exists(fileName))
{
File.AppendAllText(#"D:\FeedbackSMSlog.txt", "Service started on : " + DateTime.Now.ToString() + Environment.NewLine);
}
else
{
FileStream fs= File.Create(fileName);
fs.Close();
File.AppendAllText(#"D:\FeedbackSMSlog.txt", "Service started on : " + DateTime.Now.ToString() + Environment.NewLine);
}
//FB.ProcessSMS();
//SetTimeInterval();
//timer.Interval =Convert.ToDouble(ConfigurationManager.AppSettings["TimerInterval"].ToString());
timer = new System.Timers.Timer(5 * 60 * 1000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
timer.Start();
}
catch (Exception ex)
{
ex.Source = "On Service Start";
OASIS.Utility.ExceptionManager.HandleException(ex);
}
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Stop();
FB.ProcessSMS();
timer.Start();
}
protected override void OnStop()
{
File.AppendAllText(#"D:\FeedbackSMSlog.txt", "Service stopped on : " + DateTime.Now.ToString() + Environment.NewLine);
//TimerObj.Enabled = false;
timer.Stop();
threadPRSender = null;
}
private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer.Stop();
if (threadPRSender.ThreadState == System.Threading.ThreadState.Running)
{
return;
}
if (threadPRSender.ThreadState == System.Threading.ThreadState.Unstarted
|| threadPRSender.ThreadState == System.Threading.ThreadState.Stopped
|| threadPRSender.ThreadState == System.Threading.ThreadState.Aborted
|| !threadPRSender.IsAlive)
{
threadSender = new ThreadStart(ProcessSMSToDC);
threadPRSender = new Thread(threadSender);
threadPRSender.Start();
}
}
catch (Exception ex)
{
File.AppendAllText(#"C:\ERP\Live\Background Service\Calendar\AttendanceLog.txt", "timer_Tick error : " + ex.StackTrace.ToString() + Environment.NewLine);
ex.Source = "Timer Tick error";
OASIS.Utility.ExceptionManager.HandleException(ex);
}
}
public void ProcessSMSToDC()
{
try
{
feedbackSmstoDcHandler = new FeedBackSMSToDCHandler();
feedbackSmstoDcHandler.ProcessSMS();
}
catch (Exception ex)
{
ex.Source = "SMS Sent To DC";
OASIS.Utility.ExceptionManager.HandleException(ex);
File.AppendAllText(#"C:\ERP\Live\Background Service\Feedback\SmsSendToDC.txt", "Error while ProcessSMS : " + ex.StackTrace.ToString() + Environment.NewLine);
}
}
private void SetTimeInterval()
{
try
{
timer.Start();
}
catch (Exception ex)
{
File.AppendAllText(#"C:\ERP\Live\Background Service\Feedback\SMSToDCLog.txt", "Error while setting time interval : " + ex.StackTrace.ToString() + Environment.NewLine);
}
}
}

Related

C# WUApiLib: Failing to Install Updates with 0x80240024 Even Though Updates are Found

I have followed instructions found on this site, which was found when I researched Stack Overflow and found this question. However, I can't seem to figure out why my code is hitting the catch block. I have a break at the IInstallationResult line, which the code hits but then goes to the catch, stating 0x80240024 (There are no updates), even though there are certainly updates available and I list them in the text box.
What am I missing here?
using System;
using System.Windows.Forms;
using WUApiLib;
namespace TEST.DetectWindowsUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetUpdates(bool downloadUpdates, bool installUpdates)
{
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
UpdateCollection updatesToInstall = new UpdateCollection();
UpdateDownloader downloader = uSession.CreateUpdateDownloader();
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
uSearcher.Online = true;
try
{
ISearchResult sResult = uSearcher.Search("IsInstalled=0 And Type='Software'");
lblUpdateCount.Text = sResult.Updates.Count.ToString();
foreach (IUpdate update in sResult.Updates)
{
txtUpdatesList.AppendText("Title: " + update.Title + Environment.NewLine);
txtUpdatesList.AppendText("IsInstalled: " + update.IsInstalled.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("Downloaded: " + update.IsDownloaded.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("IsMandatory: " + update.IsMandatory.ToString() + Environment.NewLine);
txtUpdatesList.AppendText(Environment.NewLine);
if (downloadUpdates)
{
if (update.IsDownloaded == false)
{
do
{
downloader.Updates.Add(update);
downloader.Download();
}
while (update.IsDownloaded == false);
if (update.IsDownloaded == true)
{
updatesToInstall.Add(update);
}
}
else
{
updatesToInstall.Add(update);
}
}
if (installUpdates)
{
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
for (int i = 0; i < updatesToInstall.Count; i++)
{
txtUpdatesList.AppendText("Installing " + updatesToInstall[i].Title + "...");
if (installationRes.GetUpdateResult(i).HResult == 0)
{
txtUpdatesList.AppendText("INSTALL SUCCESS FOR " + updatesToInstall[i].Title);
}
else
{
txtUpdatesList.AppendText("INSTALL FAIL FOR " + updatesToInstall[i].Title);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message + ": " + ex.HelpLink);
}
}
private void btnGetUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(false, false);
}
private void btnInstallUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(true, true );
}
}
}
Turns out it was an issue with privileges. I ran as administrator and it functioned appropriately.

How to fix 'broken pipe' error when trying to write from NamedPipeClientStream to NamedPipeServerStream

I have a program, that has to comunicate with another program that is called from the first.
I have managed to send the required data from the first to the second program using NamedPipes.
When the second program closes, i need to send some data back to the first program. I set up a NamedPipeServerStream in the first program and from the Closing event of the second program a NamedPipeClientStream. Now when i try to write from ClientStream i get a broken pipe error.
This is the code from the first program:
private void CreateOverlay(object sender, EventArgs e)
{
if (oinstallfolder != null)
{
string processfilename = oinstallfolder.ToString() + "\\SecondProgram.exe";*/
string processfilename = "SecondProgram.exe";
if (File.Exists(processfilename))
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("SecondProgram"))
{
this.threadHandleOverlayBounds = new Thread(new ThreadStart(this.ExchangeMapOverlayBoundsServer));
this.threadHandleOverlayBounds.Start();
this.threadHandleOverlayFile = new Thread(new ThreadStart(this.ExchangeMapOverlayFileServer));
this.threadHandleOverlayFile.Start();
ShowWindow(clsProcess.MainWindowHandle, SW_SHOWNORMAL);
SetForegroundWindow(clsProcess.MainWindowHandle);
return;
}
}
try
{
this.threadHandleOverlayBounds = new Thread(new ThreadStart(this.ExchangeMapOverlayBoundsServer));
this.threadHandleOverlayBounds.Start();
Logger.Logger.Write("Log.txt", "Starting Filethread serverside");
this.threadHandleOverlayFile = new Thread(new ThreadStart(this.ExchangeMapOverlayFileServer));
this.threadHandleOverlayFile.Start();
Process.Start(processfilename);
}
catch { }
}
}
}
private void ExchangeMapOverlayFileServer()
{
try
{
using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("OverlayFilePipe", PipeDirection.In, 1, PipeTransmissionMode.Byte))
{
string line;
namedPipeServer.WaitForConnection();
StreamReader sr = new StreamReader(namedPipeServer);
line = sr.ReadLine();
namedPipeServer.Disconnect();
namedPipeServer.Close();
}
}
catch(Exception e)
{
Logger.Logger.Write("OverlayGenerator.txt", "namedPipeServer exception: " + e.Message + "\n" + e.StackTrace);
}
}
this is the code from the second program
this.Closing += (s, a) =>
{
Logger.Logger.Write("Log.txt", "Window Closing");
this.threadHandleOverlayFile = new Thread(new ThreadStart(this.HandleWindowClosing));
this.threadHandleOverlayFile.Start();
while (!done)
{
Thread.Sleep(100);
}
};
private void HandleWindowClosing()
{
if (!String.IsNullOrEmpty(this.latestSavedOverlayPath))
{
try
{
using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(".", "OverlayFilePipe", PipeDirection.Out))
{
namedPipeClient.Connect();
StreamWriter sw = new StreamWriter(namedPipeClient);
sw.AutoFlush = true;
sw.WriteLine("testphrase");
namedPipeClient.Close();
this.done = true;
}
}
catch (Exception e) { Logger.Logger.Write("OverlayGenerator.txt", "Exception in Client: " + e.Message + "\n" + e.StackTrace); }
}
else
{
Logger.Logger.Write("OverlayGenerator.txt", "Latest saved OverlayPath = " + this.latestSavedOverlayPath);
}
}
I tried this with Autoflush=true and without. With it, i get a broken pipe exception at the line
sw.WriteLine("testphrase");
and without it, the client side just runs to the end and nothing happens at all.
Where is my mistake?
Thank you.
EDIT
OK, i just don't get it. I made a test program, that is build the same way as the actual one. Two applications, the first starting the second. I start the pipe server in a thread in the first application and the client, also in a thread, in the second. The only difference is, that i run this test project in debug mode, which i can't do for the actual program. Now, in the test program, this matter is realy simple and it works. When i use the exact same approach in the actual program, it doesn't work.
In the testprogram i need to use flush on the streamwriter and i don't get an exception. The syncronization of the threads gets handled by the pipe itself, as it should be if i understood this correctly.
The Master looks like this:
private const string CLIENTPROC = "C:\\Users\\Maik\\Source\\Repos\\PipeTest\\PipeClient\\obj\\x86\\Release\\PipeClient.exe";
private ManualResetEvent threadResetEvent;
private Thread threadHandlePipeSendLast;
private Process procClient;
private string msgPipeSend;
private volatile bool bMsgPipeSend;
public MainWindow()
{
InitializeComponent();
this.threadResetEvent = new ManualResetEvent(false);
System.Diagnostics.Debug.WriteLine("### starting thread");
this.threadHandlePipeSendLast = new Thread(new ThreadStart(this.ExchangeMapOverlayFileServer));
this.threadHandlePipeSendLast.Start();
}
private void ExchangeMapOverlayFileServer()
{
System.Diagnostics.Debug.WriteLine("server thread started");
Thread.CurrentThread.Name = "apocalypse";
try
{
using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("ClosingPipe", PipeDirection.In, 1, PipeTransmissionMode.Byte))
{
string line;
namedPipeServer.WaitForConnection();
StreamReader sr = new StreamReader(namedPipeServer);
Thread.Sleep(100);
line = sr.ReadLine();
handleRecvMsgFromPipe(line);
namedPipeServer.Disconnect();
namedPipeServer.Close();
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("### " + e.Message + "\n" + e.StackTrace);
}
}
private void handleRecvMsgFromPipe(string line)
{
this.outbox.Text = line;
}
private void buttonOpenFormClient_Click(object sender, EventArgs e)
{
#if DEBUG
#else
if (this.procClient == null)
{
try
{
this.procClient = Process.Start(new ProcessStartInfo(CLIENTPROC));
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error");
}
}
#endif
}
}
And that's the client side:
private ManualResetEvent threadResetEvent;
private Thread threadHandlePipeSendLast;
private string msgPipeSend;
private volatile bool bMsgPipeSend;
private bool done;
public MainWindow()
{
InitializeComponent();
this.threadResetEvent = new ManualResetEvent(false);
this.Closing += (s, a) =>
{
System.Diagnostics.Debug.WriteLine("+++ FormClosing started.");
this.threadHandlePipeSendLast = new Thread(new ThreadStart(this.HandleWindowClosing));
this.threadHandlePipeSendLast.Start();
while (!done)
{
Thread.Sleep(1000);
}
};
}
private void HandleWindowClosing()
{
try
{
using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(".", "ClosingPipe", PipeDirection.Out))
{
namedPipeClient.Connect();
StreamWriter sw = new StreamWriter(namedPipeClient);
//sw.AutoFlush = true;
sw.WriteLine("last message");
namedPipeClient.WaitForPipeDrain();
namedPipeClient.Close();
this.done = true;
}
}
catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.StackTrace); }
}
Can anyone tell me, why this works in the test app and not in the actual one? I also tried various things from Thread.Sleep(x) at different points in the programs over Thread.Join() to pipe methods like WaitForPipeDrain (which is just ignored).

How to fix issue of zkemkeeper.dll realtime events inside windows service?

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !
public partial class AttendanceSyncService_405 : ServiceBase
{
public AttendanceSyncService_405()
{
InitializeComponent();
}
System.Timers.Timer timer = new System.Timers.Timer();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
protected override void OnStart(string[] args)
{
//var thread = new Thread();
//thread.SetApartmentState(ApartmentState.STA);
//thread.Start();
WriteToFile("Service is started at " + DateTime.Now);
Connect();
// LoadCurrentMonthAtt();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 900000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if (bIsConnected == true)
{
WriteToFile("Service recall at " + DateTime.Now);
WriteToFile("Device Status Connected at " + DateTime.Now);
}
else
{
WriteToFile("Device Status DisConnected at " + DateTime.Now);
WriteToFile("Service recall at " + DateTime.Now);
Connect();
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
private void Connect()
{
try
{
int idwErrorCode = 0;
bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
if (bIsConnected == true)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
iMachineNumber = 1;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
else
{
WriteToFile("RT Events didn't registered at " + DateTime.Now);
}
axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
}
}
catch(Exception ex)
{
WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);
}
}
private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
string row = sEnrollNumber + "," + Attendancedate.ToString();
WriteToFile("Attendane :" + row + " Marked At: " + DateTime.Now);
if (bIsConnected == false)
{
Connect();
return;
}
decimal empserial = decimal.Parse(sEnrollNumber);
attInsert(empserial, Attendancedate);
}
private void attInsert(decimal empserial, DateTime Attendancedate)
{
try
{
WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
DBAccess db = new DBAccess();
DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
Boolean INOUT = (count % 2 == 0) ? true : false;
WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + " Marked At: " + DateTime.Now);
db.Parameters.AddWithValue("fkSerial", empserial);
db.Parameters.AddWithValue("attTerminalId", "Time1");
db.Parameters.AddWithValue("attDateTime", Attendancedate);
db.Parameters.AddWithValue("attTgId", 3);
db.Parameters.AddWithValue("attINOUT", INOUT);
db.Parameters.AddWithValue("attEmpCode", "no need");
db.ExecuteNonQuery("spInsertAttendance");
WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);
}
catch (Exception ex)
{
WriteToFile("Exception in insert method :" + ex.Message + " At: " + DateTime.Now);
}
}
}
Type This Code in Your IntializeComponent and it will respond to realtime events
private void InitializeComponent()
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

Csvhelper write with windows service

I am using csvhelper with windows service which runs non stop. I want to create a new csv log file and put the header values only once until the file size grown to 1000 kb and then create another new file so the file size grow too big. At the moment csv file is created once when windows service starts but it repeats header values every time it writes into it.
Do we have some config properties in csv helper to flag size file?
Please have a look at the code and suggest if it can be done efficiently in .net 4.0.
Windows Service code
public partial class Service1 : ServiceBase
{
private Thread executeThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread.Sleep(30000);
executeThread = new Thread(new ThreadStart(Execute));
executeThread.Start();
}
catch (Exception e)
{
Library.LogData("Error : " + DateTime.UtcNow + " " + e.Message);
OnStop();
}
}
protected override void OnStop()
{
try
{
Library.LogData("Stopped: " + DateTime.UtcNow);
executeThread.Abort();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
public void Execute()
{
try
{
Library.LogData("Started");
while (true)
{
Library.LogData("Logging Execute" + DateTime.UtcNow);
Thread.Sleep(5000);
}
}
catch (Exception e)
{
Library.LogData("Error : " + DateTime.UtcNow + " " + e.Message);
OnStop();
}
Library.LogData("Out of Execute" + DateTime.UtcNow);
}
}
Logging code called by windows service
public static class Library
{
public static void LogData(string Message)
{
StreamWriter sw = null;
GetData getData = new GetData();
var dataClasslist = new List<DataClass>
{
new DataClass {}
};
try
{
dataClasslist = getData.ReadData();
using (sw = new StreamWriter("E:\\DataLogs\\LogFile.csv", true))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.RegisterClassMap<DataClassMap>();
csv.WriteHeader<DataClass>();
csv.Configuration.TrimHeaders = true;
csv.Configuration.HasHeaderRecord = false;
csv.WriteRecords(dataClasslist);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + ": " + e.Message.ToString());
err.Flush();
err.Close();
}
}
}
Main windows service
public partial class Service1 : ServiceBase
{
private Thread executeThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread.Sleep(10000);
executeThread = new Thread(new ThreadStart(Execute));
executeThread.Start();
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " OnStart: " + e.Message.ToString());
err.Flush();
err.Close();
OnStop();
}
}
protected override void OnStop()
{
try
{
executeThread.Abort();
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + "OnStop exception: " + e.Message.ToString());
err.Flush();
err.Close();
}
}
public void Execute()
{
try
{
StreamWriter sw = null;
string FileNameAndPath = null;
FileNameAndPath = "E:\\DataLogs\\LogFile" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
using (sw = new StreamWriter(FileNameAndPath, true))
{
sw.WriteLine("TimeStamp " + "," + "col1" + "," + "col2" + "," + "col3"
+ "," + "col4" + "," + "col5" + "," + "col6" + ","
+ "col8" + "," + "col9" + "," + "col7" + "," + "col10");
sw.Flush();
sw.Close();
}
while (true)
{
Library.LogData(FileNameAndPath);
Thread.Sleep(5000);
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " Execute: " + e.Message.ToString());
err.Flush();
err.Close();
OnStop();
}
}
public void TestInConsole(string[] args)
{
Console.WriteLine("Starting.....");
this.OnStart(args);
}
So OnExecute will be called as soon as file hits 100kb and new file will be created with headers written in it only once.
public static class Library
{
public static void LogData(string FileNameAndPath)
{
StreamWriter sw = null;
GetData getData = new GetData();
var dataClasslist = new List<DataClass>
{
new DataClass {}
};
try
{
//System.Diagnostics.Debugger.Break();
dataClasslist = getData.ReadData();
//Create a file seperately
using (sw = new StreamWriter(FileNameAndPath, true))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.RegisterClassMap<DataClassMap>();
//csv.WriteHeader<DataClass>();
csv.Configuration.TrimHeaders = true;
csv.Configuration.HasHeaderRecord = false;
csv.WriteRecords(dataClasslist);
sw.Flush();
sw.Close();
}
var FileSize = new FileInfo(FileNameAndPath);
//for each 1000 kb
if (FileSize.Length >= 1e+6)
{
//go back to the start to create a new file and column headers
Service1 serive1 = new Service1();
serive1.Execute();
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " LogData: " + e.Message.ToString());
err.Flush();
err.Close();
}
}
}
Im open for suggests, please let me know if you can thing of a better way to to do this.

Service stops when connection is lost to the database

I have coded a service in C# which runs and updates a CRM solution. I am trying to get the service to re-establish a connection to the database if it has to drop for some reason. So far when I detach the database and then reattach it, the service stops by itself.. Another thing is that then I detach the database, there is no exception logged by my synch app - it just stops dead.
My partial class where I call my synch from:
namespace Vessel_Schedule_Synch
{
[DisplayName("CRM Vessel Synch")]
partial class startVessel : ServiceBase
{
System.Threading.Timer t;
VesselUpdater v;
protected override void OnStart(string[] args)
{
//System.Threading.Thread.Sleep(20000);
v = new VesselUpdater();
t = new System.Threading.Timer(new System.Threading.TimerCallback(t_TimerCallback), null, 0, 300000);
//InfoLogger.Info("Starting service " + this.ServiceName, true);
}
private void t_TimerCallback(object state)
{
t.Change(Timeout.Infinite, Timeout.Infinite);
lock (v)
{
InfoLogger.Info("Timer fired... updating vessels");
try
{
v.Process();
v.updateCRM();
}
catch (Exception e)
{
if (v == null)
{ throw e; }
else
{
InfoLogger.Exception(e);
}
}
finally
{
InfoLogger.Info("End of Timer Trigger... Restarting Timer.");
t.Change(30000, 30000);
}
}
}
protected override void OnStop()
{
InfoLogger.Info("Service Stopped " + this.ServiceName, true);
}
}
}
My synch class where I have tried to use a bool to test the connection:
namespace Vessel_Schedule_Synch
{
class VesselUpdater
{
private OrganizationServiceProxy _serviceProxy;
private IOrganizationService _service;
private Logger logger = LogManager.GetLogger("VesselUpdater");
public string ConnectionString { get; set; }
public string ServiceUrl { get; set; }
int i = 0;
private bool InitialiseCRMConnection;
public VesselUpdater()
{
InitialiseCRMConnection = true;
Console.WriteLine("Starting the service");
LogMessage("Starting service");
ServiceUrl = ConfigurationManager.AppSettings["CRMUrl"];
LogMessage(ConnectionString);
ConnectionString = ConfigurationManager.ConnectionStrings["iRoot"].ConnectionString;
LogMessage(ServiceUrl);
Console.WriteLine(ServiceUrl);
}
public void Process()
{
if (!InitialiseCRMConnection)
return;
LogMessage("Process Starting");
ClientCredentials UserCredentials = new ClientCredentials();
string UserName = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
UserCredentials.UserName.UserName = UserName;
UserCredentials.UserName.Password = Password;
ClientCredentials DivCredentials = null;
Uri HomeRealmURI = null;
Uri serviceurl = new Uri(ServiceUrl);
_serviceProxy = new OrganizationServiceProxy(serviceurl, HomeRealmURI, UserCredentials, DivCredentials);
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
_serviceProxy.EnableProxyTypes();
LogMessage("CRM Connection Initiated");
InitialiseCRMConnection = false;
}
public void updateCRM()
{
try
{
ProcessVesselSchedule("Insert");
ProcessVesselSchedule("Modification");
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
private void ProcessVesselSchedule(string Type)
{
if (InitialiseCRMConnection)
return;
try
{
LogMessage(string.Format("Processing Vessesl Schedules {0}", Type));
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("VesselScheduleInformation", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Type", Type);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
LogMessage("Processing Record");
LogMessage(dr["new_Name"].ToString());
string Name = dr["new_Name"].ToString() + " " + dr["new_VoyageNo"].ToString();
string Vesselname = dr["new_Name"].ToString();
int LineNo = (int)dr["Line Number"];
string NAVVesselScheduleCode = dr["new_NAVVesselScheduleCode"].ToString();
string CarrierService = dr["new_CarrierService"].ToString();
string ETA = dr["new_ETA"].ToString();
string ETD = dr["new_ETD"].ToString();
string VesselCode = dr["new_Vessel"].ToString();//Vessel Code
string VoyageNo = dr["new_VoyageNo"].ToString();
string TranshipmentVessel = dr["new_TranshipmentVessel"].ToString();
string TranshipmentVoyageNo = dr["new_TranshipmentVoyageNo"].ToString();
string Port = dr["new_Port"].ToString();
string PortOfDis = dr["new_DischargePort"].ToString();
string PortOfLoad = dr["new_LoadPort"].ToString();
//string StackStart = dr["new_StackStart"].ToString();
//string StackEnd = dr["new_StackEnd"].ToString();
bool Create = false;
LogMessage("Assigned all variables");
Console.WriteLine("Assigned all variables");
new_vesselschedule VesselS = FindVessleSchedule(NAVVesselScheduleCode, LineNo, out Create);
//if (DateTime.Parse(StackStart).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackstart"] = DateTime.Parse(StackStart).ToUniversalTime();
//}
//if (DateTime.Parse(StackEnd).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackend"] = DateTime.Parse(StackEnd).ToUniversalTime();
//}
VesselS.new_name = Name;
VesselS.new_navvesselschedulecode = NAVVesselScheduleCode;
VesselS.new_CarrierService = CarrierService;
if (DateTime.Parse(ETA).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETA = DateTime.Parse(ETA).ToUniversalTime();
}
if (DateTime.Parse(ETD).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETD = DateTime.Parse(ETD).ToUniversalTime();
}
VesselS.new_vesselcodeimport = VesselCode;
VesselS.new_vesselnameimport = Vesselname;
VesselS.new_VoyageNo = VoyageNo;
VesselS.new_TransshipmentVessel = TranshipmentVessel;
VesselS.new_TransshipmentVoyageNo = TranshipmentVoyageNo;
VesselS.new_dischargeportimport = PortOfDis;
VesselS.new_loadportimport = PortOfLoad;
if (Create)
{
LogMessage(string.Format("Created {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Create(VesselS);
}
else
{
LogMessage(string.Format("Updated {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Update(VesselS);
}
using (SqlCommand cmdUpdateMates = new SqlCommand())
{
SqlConnection con2 = new SqlConnection(ConnectionString);
con2.Open();
cmdUpdateMates.Connection = con2;
cmdUpdateMates.CommandText = "ProcessedVessSched";
cmdUpdateMates.CommandType = CommandType.StoredProcedure;
cmdUpdateMates.Parameters.AddWithValue("#VesselSched", NAVVesselScheduleCode);
cmdUpdateMates.Parameters.AddWithValue("#LineNo", LineNo);
cmdUpdateMates.ExecuteNonQuery();
i++;
Console.WriteLine("Created/Updated" + " " + i);
}
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
}
}
catch (SqlException e)
{
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
public void LogMessage(string Message)
{
LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", Message);
myEvent.LoggerName = logger.Name;
logger.Log(myEvent);
}
private new_vesselschedule FindVessleSchedule(string NAVVesselScheduleCode, int LineNo, out bool Create)
{
QueryExpression query = new QueryExpression(new_vesselschedule.EntityLogicalName);
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("new_navvesselschedulecode", ConditionOperator.Equal, NAVVesselScheduleCode);
query.Criteria.AddCondition("new_lineno", ConditionOperator.Equal, LineNo);
EntityCollection entitycollection = _serviceProxy.RetrieveMultiple(query);
if (entitycollection.Entities.Count == 0)
{
new_vesselschedule n = new new_vesselschedule();
n.new_navvesselschedulecode = NAVVesselScheduleCode;
n.new_lineno = LineNo;
Create = true;
return n;
}
Create = false;
return (new_vesselschedule)entitycollection.Entities[0];
}
}
}
Am I missing something here?
I found the issue in my code, I had forgotten to sent InitialiseCRMConnection = true; in my SQL Exception thus it could never go through the motions of reInitialising the connection as it would always return;
Fix:
catch (SqlException e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}

Categories