How can I check if there is an external parameter when my application is running and how can I start a new thread if there is an incoming parameter?
protected override void OnStart(string[] args)
{
odbcConnection = new OdbcConnection(ConnectionString);
odbcDataAdapter = new OdbcDataAdapter(QueryString, odbcConnection);
new Thread(new ThreadStart(run)).Start();
}
protected override void OnStop()
{
}
public void run()
{
while (true)
{
try
{
if (odbcConnection.State != ConnectionState.Open)
{
odbcConnection.Close();
odbcConnection.Open();
}
DataSet dataSet = new DataSet();
odbcDataAdapter.Fill(dataSet);
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
}
using (FileStream fileStream = File.Create(Path + DateTime.Now.ToString() + ".xml"))
{
dataSet.WriteXml(fileStream);
}
}
catch (Exception) { }
Thread.Sleep(300000);
}
}
i don't really know what I should do I need to use a parameter for the first time and I need to do it on a running application
Related
I tried to monitor the directory with FileWatcher. When several files changed I must insert added data of txt files into database. But it does not work after the second attempt. So, Windows shows such message: this file is used by another program. I think that it relates to the ReaderWriterLockSlim class which used in this code. Please, suppose your solutions. I am working with ASP.NET MVC, not Windows Forms App.
Here the code
public class MultiWatcher : IDisposable
{
private List<string> filePaths;
private ReaderWriterLockSlim rwlock;
private System.Timers.Timer processTimer;
private string watchedPath;
private FileSystemWatcher watcher;
private int readLinesCount = 0;
public MultiWatcher(string watchedPath)
{
filePaths = new List<string>();
rwlock = new ReaderWriterLockSlim();
this.watchedPath = watchedPath;
InitFileSystemWatcher();
}
private void InitFileSystemWatcher()
{
watcher = new FileSystemWatcher();
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(Watcher_FileChanged);
watcher.Error += Watcher_Error;
watcher.Path = watchedPath;
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
}
private void Watcher_Error(object sender, ErrorEventArgs e)
{
// Watcher crashed. Re-init.
InitFileSystemWatcher();
}
private void Watcher_FileChanged(object sender, FileSystemEventArgs e)
{
try
{
rwlock.EnterWriteLock();
filePaths.Add(e.Name);
if (processTimer == null)
{
// First file, start timer.
processTimer = new System.Timers.Timer(1000);
processTimer.Elapsed += ProcessQueue;
processTimer.Start();
}
else
{
// Subsequent file, reset timer.
processTimer.Stop();
processTimer.Start();
}
}
finally
{
rwlock.ExitWriteLock();
}
}
private void ProcessQueue(object sender, ElapsedEventArgs args)
{
try
{
//Console.WriteLine("Processing queue, " + filePaths.Count + " files created:");
rwlock.EnterReadLock();
foreach (string filePath in filePaths)
{
RecordEntry(filePath); // try to insert txt file data into database
}
filePaths.Clear();
}
finally
{
if (processTimer != null)
{
processTimer.Stop();
processTimer.Dispose();
processTimer = null;
}
rwlock.ExitReadLock();
}
}
//insert txt file data into database
private void RecordEntry(string fileName)
{
if (fileName != null)
{
using (var fs = new FileStream(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName), FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)))
{
Data_access da = new Data_access();
readLinesCount = da.GetReadLinesCount(fileName);
int totalLinesCount = File.ReadAllLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Length;
int newLinesCount = totalLinesCount - readLinesCount;
//var fileByLine = File.ReadLines(HostingEnvironment.MapPath("/Content/101_Sensors.txt")).Last();
var fileByLine = File.ReadLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Skip(readLinesCount).Take(newLinesCount);
var each = fileByLine.Select(l => l.Split('_'));
string[] parsedFileContent = new string[fileByLine.Count()];
foreach (var item in fileByLine)
{
parsedFileContent = item.Split('_');
da.AddParams(parsedFileContent, totalLinesCount, fileName);
}
da.SetReadLinesCount(totalLinesCount, fileName);
}
}
//using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)))
//{
// int totallinesCount = File.ReadAllLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Length;
// int newLinesCount = totallinesCount - readLinesCount;
// //var fileByLine = File.ReadLines(HostingEnvironment.MapPath("/Content/101_Sensors.txt")).Last();
// var fileByLine = File.ReadLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Skip(readLinesCount).Take(newLinesCount);
// var each = fileByLine.Select(l => l.Split('_'));
// string[] parsedFileContent = new string[fileByLine.Count()];
// foreach (var item in fileByLine)
// {
// parsedFileContent = item.Split('_');
// da.AddParams(parsedFileContent, totallinesCount, fileName, readLinesCount);
// }
//}
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (rwlock != null)
{
rwlock.Dispose();
rwlock = null;
}
if (watcher != null)
{
watcher.EnableRaisingEvents = false;
watcher.Dispose();
watcher = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
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 had created a window services and it will stop when it detect there is changes on my database.
Problem : how to start the window services again after it is stop in maybe 5 or 10 second by coding in C# ?
private static string connectString = ConfigurationManager.ConnectionStrings['ConnStr'].ToString();
int sql_depend = 0;//stop
private delegate void GridDelegate(DataTable table);
private SqlDependency dep;
public Watcher()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
SqlDependency.Start(connectString);
sql_depend = 1;
UpdateGrid();
string file = #"E:\WatcherLogFile\sds.txt";
TextWriter writer = new StreamWriter(file, true);
writer.WriteLine("Window services started");
writer.Close();
}
protected override void OnStop()
{
string file = #"E:\WatcherLogFile\sds.txt";
TextWriter writer = new StreamWriter(file, true);
writer.WriteLine("Window services stopped");
writer.Close();
}
//sql dependency check
private void UpdateGrid()
{
string sql = "select [Name], [ClientName] from [Account]";
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(connectString))
{
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cn.Open();
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
}
}
}
//sql dependency detect changes
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
ServiceController myService = new ServiceController();
myService.ServiceName = "Watcher";
myService.Stop();
SqlDependency.Stop(connectString);
sql_depend = 0;
}
can it be loop function in onStop() ? I want it manually start it once on everyday then it start / stop by itself after that.
You can try this.
var sc = new ServiceController(YouServiceNameString);
// stop service
// sc.Stop();
//start service
sc.Start();
// or restart
/*
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
*/
If you want pause, use Thread.Sleep or this example
var _stopToken = new CancellationTokenSource();
// call this when you want stop
// _stopToken.Cancel();
// there is you can set timeout
_stopToken.Token.WaitHandle.WaitOne(YourWaitTime);
// if you want circle
// while (!_stopToken.IsCancellationRequested)
// { /*...do somthing...*/ }
You have various options to solve your problem.
Easiest solution would be configuring recovery action for a service failure.
Check this link for detailed instructions.
Another option I can think of writing your custom script/program to restart it when you notice the failure.
I have an XML file which contains scheduling dates. I want to create a service that will read the date and time from the XML file and trigger (call my application) on that time.
I tried a lot but the service doesn't not trigger my application so I made a console application to replicate my service which work perfectly.
Also, on my service, on Start/Stop I am creating a log file which does seem to be working it just appears to be my trigger that doesn't.
protected override void OnStart(string[] args)
{
TraceService("start service");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService(" Varun Another entry at " + DateTime.Now);
}
private void TraceService(string content)
{
FileStream fs = new FileStream(#"d:\Varun-Pc start up.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
connect();
string xmldata = "";
SqlDataAdapter da = new SqlDataAdapter("select * from Schedualer_Master", cn);
DataSet mds = new DataSet();
da.Fill(mds);
for (int i = 0; i < mds.Tables[0].Rows.Count; i++)
{
xmldata = "";
xmldata = mds.Tables[0].Rows[i]["XML_Data"].ToString();
TaskScheduler.TriggerItem newItem = TaskScheduler.TriggerItem.FromXML(xmldata);
newItem.Enabled = true;
_taskScheduler.AddTrigger(newItem); // set item into trigger
_taskScheduler.Enabled = true;
}
object sender = new object();
EventArgs e = new EventArgs();
_taskScheduler._triggerTimer_Tick(sender, e);
}
And this is my trigger function
public void _triggerTimer_Tick(object sender, EventArgs e)
{
_triggerTimer.Stop();
foreach (TriggerItem item in TriggerItems)
if (item.Enabled)
{
while (item.TriggerTime <= DateTime.Now)
{
item.RunCheck(DateTime.Now);
System.Diagnostics.Process.Start("E:\\SqlBackup_Programs\\console-backup\\Backup_Console_App 22July Latest\\Backup_Console_App\\Backup_Console_App\\bin\\Debug\\Backup_Console_App");
}
}
_triggerTimer.Start();
}
In my window service when I run window service from manage ,ScheduledService file does not contain "Get Connection". I think there is problem in GetConnectionOfReportServer, it may it take more time.
When I debug it is working fine.
Code Example
protected override void OnStart(string[] args)
{
TraceService("start service");
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 90000;
timer.Enabled = true;
}
protected override void OnStop()
{
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
time_elapsed();
TraceService("Another entry at " + DateTime.Now);
}
private void time_elapsed()
{
TraceService("Call susseccfully");
GetConnectionOfReportServer();//The problem is here.
TraceService("Get Connection");
DailyReportFile = getReportFrmServer(reportName, param);
}
public void GetConnectionOfReportServer()
{
TraceService("I am in GetConnectionOfReportServer "); //**Edit part**
try
{
NetworkCredential credential = new NetworkCredential("administrator", "epass#123");
this.reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credential;
this.reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote;
this.reportViewer1.ServerReport.ReportServerUrl = new Uri(#"http://xxx.xxx.xxx.xxx/ReportServer");
}
catch (Exception ex)
{
}
}
private void TraceService(string content)
{
FileStream fs = new FileStream(#"c:\ScheduledService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
Edit Method
public void GetConnectionOfReportServer()
{
TraceService("I am in GetConnectionOfReportServer.");
try
{
TraceService("I am in Try.");
//NetworkCredential credential = new NetworkCredential("administrator", "espl#123","");
NetworkCredential credential = new NetworkCredential("administrator", "esmart#123");
this.reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credential;
//select where the report should be generated with the report viewer control or on the report server using the SSRS service.
this.reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote;
this.reportViewer1.ServerReport.ReportServerUrl = new Uri(#"http://xxx.xxx.xxx.xxx/ReportServer");
TraceService("I am atTry end");
}
catch (Exception ex)
{
TraceService(ex.StackTrace);
}
finally
{
TraceService("I am in finally block");
}
}
But when I am seeing my "ScheduledService File"
start service
Call susseccfully
Find punch
Yes have to send
Yes have to send,
I am in GetConnectionOfReportServer.
I am in Try. // After this line It should be print "I am at Try end"
Call susseccfully.
After it again call OnElapsedTime event.