Hello all,
I am having trouble creating a windows service with a timer.
Everything seems to go ok but the elapsed event does not fire.Can
anyone shed any light on this, may be something simple as I am new to
this. Full code below :
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Web.Mail;
using System.Data.SqlClient;
using System.Globalization;
using System.Timers;
namespace NAVEmailPO
{
public class NAVEmailPO : System.ServiceProcess.ServiceBase
{
public bool debug = true;
private System.Timers.Timer _Timer = new Timer();
public string SMTPServer, sDBServer, sDB, sUID, sPass,
sContactField;
private SqlConnection oConn;
private int _Interval = 50000;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components =
null;
public NAVEmailPO()
{
// This call is required by the Windows.Forms
Component Designer.
InitializeComponent();
// TODO: Add any initialization after the
InitComponent call
}
// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[]
ServicesToRun;
// More than one user Service may run within
the same process. To
add
// another service to this process, change the
following line to
// create a second service object. For example,
//
// ServicesToRun = new
System.ServiceProcess.ServiceBase[] {new
Service1(), new MySecondUserService()};
//
ServicesToRun = new
System.ServiceProcess.ServiceBase[] { new
NAVEmailPO() };
System.ServiceProcess.ServiceBase.Run(ServicesToRu n);
}
/// <summary>
/// Required method for Designer support - do not
modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new
System.ComponentModel.Container();
this.ServiceName = "NAVEmailPO";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service can do its
work.
/// </summary>
protected override void OnStart(string[] args)
{
GetConfig();
_Timer.Interval = _Interval;
_Timer.Elapsed += new
System.Timers.ElapsedEventHandler(
this._Timer_Elapsed );
_Timer.Enabled = true;
_Timer.Start();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
_Timer.Stop();
_Timer.Enabled = false;
}
/// <summary>
/// Pause this service.
/// </summary>
protected override void OnPause()
{
_Timer.Stop();
}
/// <summary>
/// Continue this service.
/// </summary>
protected override void OnContinue()
{
_Timer.Start();
}
/// <summary>
/// Respond to the _Timer elapsed event.
/// <summary>
private void _Timer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
_Timer.Stop();
//Run Code
writeLog("TIMER ELAPSED",true);
ProcessPO();
_Timer.Start();
}
/// <summary>
/// Gets configuration settings from text file
/// </summary>
private void GetConfig()
{
try
{
FileInfo fConf = new
FileInfo(@"c:\POSettings.txt");
if (debug) {writeLog("Creating
FileInfo", false);}
StreamReader s = fConf.OpenText();
if (debug) {writeLog("Opened File",
false);}
string read = null;
if (debug) {writeLog("Reading File",
false);}
while ((read = s.ReadLine()) != null)
{
getParam(read);
}
s.Close();
}
catch (Exception e)
{
writeLog("System Error Retrieving
Configuration" +
e.Message.ToString(), true);
}
}
/// <summary>
/// Populates global variables with values passed from
GetConfig()
/// </summary>
private void getParam(string sKeyVal)
{
if (debug) {writeLog("Retrieving Values using
:" + sKeyVal, false);}
if (sKeyVal.Substring(0,3).ToUpper() != "REM")
{
if (sKeyVal.IndexOf(",",0) > 0)
{
string[] aKeyVal =
sKeyVal.Split(',');
string sKey =
aKeyVal[0].ToUpper();
string sVal = aKeyVal[1];
switch (sKey)
{
case "SMTPSERVER":
SMTPServer =
sVal;
if (debug)
{writeLog("Param val = "+sVal ,false);}
break;
case "DATABASESERVER":
sDBServer =
sVal;
if (debug)
{writeLog("Param val = "+sVal ,false);}
break;
case "DATABASE":
sDB = sVal;
if (debug)
{writeLog("Param val = "+sVal ,false);}
break;
case "USERNAME":
sUID = sVal;
if (debug)
{writeLog("Param val = "+sVal ,false);}
break;
case "PASSWORD":
sPass = sVal;
if (debug)
{writeLog("Param val = "+sVal ,false);}
break;
default:
writeLog("Parameter not in local variables. Param = "+sKey
,false);
break;
}
}
}
}
/// <summary>
/// Looks for Purchase Orders to process and generates
emails for
suppliers
/// </summary>
private bool ProcessPO()
{
string sDSN = "provider=SQLOLEDB.1;server=" +
sDBServer + ";UID=" +
sUID + ";PWD=" + sPass + ";DATABASE=" + sDB;
oConn = new SqlConnection(sDSN);
string sSQL = "SELECT [No_] as No, [Buy-from
Vendor No_] as VNo FROM
[CrocusDevelopmentupdate$Purch_ orders for e-mailing] WHERE Processed =
0 AND [Document Type] = 1";
SqlCommand oCommand = new
SqlCommand(sSQL,oConn);
SqlDataReader oRS;
try
{
oConn.Open();
oRS =
oCommand.ExecuteReader(CommandBehavior.Default);
writeLog("Processing Started", false);
while (oRS.Read())
{
writeLog("No = " +
oRS["No"].ToString(), false);
}
oRS.Close();
oConn.Close();
}
catch (Exception e)
{
writeLog("Processing PO's DB error : "
+ e.Message,true);
}
//oConn.Close();
return true;
}
/// <summary>
/// Write messages to the application event log
/// </summary>
public bool writeLog(string sMessage, bool bError)
{
string log = "Application";
string sSource = "NAVEmailPO";
EventLogEntryType oType;
if (!EventLog.SourceExists(sSource))
{
EventLog.CreateEventSource(sSource,
log);
}
EventLog oLog = new EventLog();
oLog.Source = sSource;
if (String.Compare(oLog.Log, log, true,
CultureInfo.InvariantCulture) != 0)
{
//Shafted log in use by something else
return false;
}
if (bError)
{
oType = EventLogEntryType.Warning;
}
else
{
oType = EventLogEntryType.Information;
}
oLog.WriteEntry(sMessage, oType);
oLog.Close();
oLog.Dispose();
return true;
}
} 2 5120
Hi,
It should work ok, I have a similar deployment but instead of using a Timer
I use a FileSystemWatcher and it does work fine, did you check the
Application event log ?
what about this Config method?
what if you put this code in a win app, does it work fine?
cheers,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Besta" <Ga*******@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com... Hello all, I am having trouble creating a windows service with a timer. Everything seems to go ok but the elapsed event does not fire.Can anyone shed any light on this, may be something simple as I am new to this. Full code below :
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.IO; using System.Web.Mail; using System.Data.SqlClient; using System.Globalization; using System.Timers;
namespace NAVEmailPO { public class NAVEmailPO : System.ServiceProcess.ServiceBase { public bool debug = true; private System.Timers.Timer _Timer = new Timer(); public string SMTPServer, sDBServer, sDB, sUID, sPass, sContactField; private SqlConnection oConn; private int _Interval = 50000;
/// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null;
public NAVEmailPO() { // This call is required by the Windows.Forms Component Designer. InitializeComponent();
// TODO: Add any initialization after the InitComponent call }
// The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example,
// // ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new System.ServiceProcess.ServiceBase[] { new NAVEmailPO() }; System.ServiceProcess.ServiceBase.Run(ServicesToRu n); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); this.ServiceName = "NAVEmailPO"; }
/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }
/// <summary> /// Set things in motion so your service can do its work. /// </summary> protected override void OnStart(string[] args) { GetConfig(); _Timer.Interval = _Interval; _Timer.Elapsed += new System.Timers.ElapsedEventHandler( this._Timer_Elapsed ); _Timer.Enabled = true; _Timer.Start(); }
/// <summary> /// Stop this service. /// </summary> protected override void OnStop() { _Timer.Stop(); _Timer.Enabled = false; } /// <summary> /// Pause this service. /// </summary> protected override void OnPause() { _Timer.Stop(); } /// <summary> /// Continue this service. /// </summary> protected override void OnContinue() { _Timer.Start(); }
/// <summary> /// Respond to the _Timer elapsed event. /// <summary> private void _Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { _Timer.Stop(); //Run Code writeLog("TIMER ELAPSED",true); ProcessPO(); _Timer.Start(); } /// <summary> /// Gets configuration settings from text file /// </summary> private void GetConfig() { try { FileInfo fConf = new FileInfo(@"c:\POSettings.txt"); if (debug) {writeLog("Creating FileInfo", false);} StreamReader s = fConf.OpenText(); if (debug) {writeLog("Opened File", false);} string read = null; if (debug) {writeLog("Reading File", false);} while ((read = s.ReadLine()) != null) { getParam(read); } s.Close(); } catch (Exception e) { writeLog("System Error Retrieving Configuration" + e.Message.ToString(), true); } }
/// <summary> /// Populates global variables with values passed from GetConfig() /// </summary> private void getParam(string sKeyVal) { if (debug) {writeLog("Retrieving Values using :" + sKeyVal, false);} if (sKeyVal.Substring(0,3).ToUpper() != "REM") { if (sKeyVal.IndexOf(",",0) > 0) { string[] aKeyVal = sKeyVal.Split(','); string sKey = aKeyVal[0].ToUpper(); string sVal = aKeyVal[1]; switch (sKey) { case "SMTPSERVER": SMTPServer = sVal; if (debug) {writeLog("Param val = "+sVal ,false);} break; case "DATABASESERVER": sDBServer = sVal; if (debug) {writeLog("Param val = "+sVal ,false);} break; case "DATABASE": sDB = sVal; if (debug) {writeLog("Param val = "+sVal ,false);} break; case "USERNAME": sUID = sVal; if (debug) {writeLog("Param val = "+sVal ,false);} break; case "PASSWORD": sPass = sVal; if (debug) {writeLog("Param val = "+sVal ,false);} break; default:
writeLog("Parameter not in local variables. Param = "+sKey ,false); break; } } } } /// <summary> /// Looks for Purchase Orders to process and generates emails for suppliers /// </summary> private bool ProcessPO() { string sDSN = "provider=SQLOLEDB.1;server=" + sDBServer + ";UID=" + sUID + ";PWD=" + sPass + ";DATABASE=" + sDB; oConn = new SqlConnection(sDSN); string sSQL = "SELECT [No_] as No, [Buy-from Vendor No_] as VNo FROM [CrocusDevelopmentupdate$Purch_ orders for e-mailing] WHERE Processed =
0 AND [Document Type] = 1"; SqlCommand oCommand = new SqlCommand(sSQL,oConn); SqlDataReader oRS; try { oConn.Open(); oRS = oCommand.ExecuteReader(CommandBehavior.Default); writeLog("Processing Started", false); while (oRS.Read()) { writeLog("No = " + oRS["No"].ToString(), false); } oRS.Close(); oConn.Close();
} catch (Exception e) { writeLog("Processing PO's DB error : " + e.Message,true); } //oConn.Close(); return true; } /// <summary> /// Write messages to the application event log /// </summary> public bool writeLog(string sMessage, bool bError) { string log = "Application"; string sSource = "NAVEmailPO"; EventLogEntryType oType; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, log); } EventLog oLog = new EventLog();
oLog.Source = sSource; if (String.Compare(oLog.Log, log, true, CultureInfo.InvariantCulture) != 0) { //Shafted log in use by something else return false; } if (bError) { oType = EventLogEntryType.Warning; } else { oType = EventLogEntryType.Information; } oLog.WriteEntry(sMessage, oType); oLog.Close(); oLog.Dispose(); return true; }
}
Ignacio,
Thanks for the help. I created a new service and copied the code
and pasted it in. It now seems to work ok, so not sure what was
happening. I will slowly integrate the code back in and see how it
progresses.
Gary This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Mr. B |
last post by:
My current app has a timer that I kick ON in my Form1_Load as follows:
' Set Up the Timer Function
Dim t As New System.Timers.Timer(12000) ' 1000 = 1 Second
t.Enabled = True ' False to Turn OFF...
|
by: Daniel P. |
last post by:
I'm trying to set a timer that gets called every 3 seconds so I can update a
field in the UI with the time elapsed since the process started.
What am I doing wrong that timerDF_Tick does not get...
|
by: Nathan Sokalski |
last post by:
I am trying to learn how to use the System.Timers.Timer control to perform
an action every certain amount of time. However, the Elapsed event doesn't
want to fire, but I can't figure out why. I...
|
by: Bob |
last post by:
I have a splashscreen running on a thread from Sub Main and it works OK. It
displays information in a statusbar about queries. I also have a time on the
splashscreen, but the tick event never...
|
by: Manuel |
last post by:
Used VS2005 to create a windows service and I can't make a timer trigger the
tick/elapsed event.
On the form viewer I dragged a timer from the components section of the
toolbar, enabled it but...
|
by: Liverpool fan |
last post by:
I have a windows application written using VB .NET that encompasses a
countdown timer modal dialog. The timer is a System.Timers.Timer with
an interval of 1 second. AutoReset is not set so accepts...
|
by: Gina_Marano |
last post by:
I have created an array of timers (1-n). At first I just created
windows form timers but I read that system timers are better for
background work. The timers will just be monitoring different...
|
by: igor |
last post by:
I have recently discovered that the system.Timers.Timer from.Net
Framework v1.1 is not reliable when used on Windows 2003 server. When
incorporated into a Windows Service, the timer_elapsed event...
|
by: Boki |
last post by:
Hi All,
I have a timer, if my data queue Q has data, the timer should start
work, if there is no data in Q, the timer should stop.
However, there is an event can fire timer to start.
Should I...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |