By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,263 Members | 1,694 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,263 IT Pros & Developers. It's quick & easy.

Timer Elapsed event does not fire

P: n/a
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;
}
}

Nov 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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;
}
}

Nov 17 '05 #2

P: n/a
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

Nov 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.