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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Diagnost ics;
using System.ServiceP rocess;
using System.IO;
using System.Web.Mail ;
using System.Data.Sql Client;
using System.Globaliz ation;
using System.Timers;
namespace NAVEmailPO
{
public class NAVEmailPO : System.ServiceP rocess.ServiceB ase
{
public bool debug = true;
private System.Timers.T imer _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.Componen tModel.Containe r components =
null;
public NAVEmailPO()
{
// This call is required by the Windows.Forms
Component Designer.
InitializeCompo nent();
// TODO: Add any initialization after the
InitComponent call
}
// The main entry point for the process
static void Main()
{
System.ServiceP rocess.ServiceB ase[]
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.ServiceP rocess.ServiceB ase[] {new
Service1(), new MySecondUserSer vice()};
//
ServicesToRun = new
System.ServiceP rocess.ServiceB ase[] { new
NAVEmailPO() };
System.ServiceP rocess.ServiceB ase.Run(Service sToRun);
}
/// <summary>
/// Required method for Designer support - do not
modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
components = new
System.Componen tModel.Containe r();
this.ServiceNam e = "NAVEmailPO ";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
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.E lapsedEventHand ler(
this._Timer_Ela psed );
_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.E lapsedEventArgs 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:\P OSettings.txt") ;
if (debug) {writeLog("Crea ting
FileInfo", false);}
StreamReader s = fConf.OpenText( );
if (debug) {writeLog("Open ed File",
false);}
string read = null;
if (debug) {writeLog("Read ing File",
false);}
while ((read = s.ReadLine()) != null)
{
getParam(read);
}
s.Close();
}
catch (Exception e)
{
writeLog("Syste m Error Retrieving
Configuration" +
e.Message.ToStr ing(), true);
}
}
/// <summary>
/// Populates global variables with values passed from
GetConfig()
/// </summary>
private void getParam(string sKeyVal)
{
if (debug) {writeLog("Retr ieving Values using
:" + sKeyVal, false);}
if (sKeyVal.Substr ing(0,3).ToUppe r() != "REM")
{
if (sKeyVal.IndexO f(",",0) > 0)
{
string[] aKeyVal =
sKeyVal.Split(' ,');
string sKey =
aKeyVal[0].ToUpper();
string sVal = aKeyVal[1];
switch (sKey)
{
case "SMTPSERVER ":
SMTPServer =
sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "DATABASESERVER ":
sDBServer =
sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "DATABASE":
sDB = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "USERNAME":
sUID = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "PASSWORD":
sPass = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
default:
writeLog("Param eter 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=SQLOL EDB.1;server=" +
sDBServer + ";UID=" +
sUID + ";PWD=" + sPass + ";DATABASE= " + sDB;
oConn = new SqlConnection(s DSN);
string sSQL = "SELECT [No_] as No, [Buy-from
Vendor No_] as VNo FROM
[CrocusDevelopme ntupdate$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.Execut eReader(Command Behavior.Defaul t);
writeLog("Proce ssing Started", false);
while (oRS.Read())
{
writeLog("No = " +
oRS["No"].ToString(), false);
}
oRS.Close();
oConn.Close();
}
catch (Exception e)
{
writeLog("Proce ssing 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 = "Applicatio n";
string sSource = "NAVEmailPO ";
EventLogEntryTy pe oType;
if (!EventLog.Sour ceExists(sSourc e))
{
EventLog.Create EventSource(sSo urce,
log);
}
EventLog oLog = new EventLog();
oLog.Source = sSource;
if (String.Compare (oLog.Log, log, true,
CultureInfo.Inv ariantCulture) != 0)
{
//Shafted log in use by something else
return false;
}
if (bError)
{
oType = EventLogEntryTy pe.Warning;
}
else
{
oType = EventLogEntryTy pe.Information;
}
oLog.WriteEntry (sMessage, oType);
oLog.Close();
oLog.Dispose();
return true;
}
}
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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Diagnost ics;
using System.ServiceP rocess;
using System.IO;
using System.Web.Mail ;
using System.Data.Sql Client;
using System.Globaliz ation;
using System.Timers;
namespace NAVEmailPO
{
public class NAVEmailPO : System.ServiceP rocess.ServiceB ase
{
public bool debug = true;
private System.Timers.T imer _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.Componen tModel.Containe r components =
null;
public NAVEmailPO()
{
// This call is required by the Windows.Forms
Component Designer.
InitializeCompo nent();
// TODO: Add any initialization after the
InitComponent call
}
// The main entry point for the process
static void Main()
{
System.ServiceP rocess.ServiceB ase[]
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.ServiceP rocess.ServiceB ase[] {new
Service1(), new MySecondUserSer vice()};
//
ServicesToRun = new
System.ServiceP rocess.ServiceB ase[] { new
NAVEmailPO() };
System.ServiceP rocess.ServiceB ase.Run(Service sToRun);
}
/// <summary>
/// Required method for Designer support - do not
modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
components = new
System.Componen tModel.Containe r();
this.ServiceNam e = "NAVEmailPO ";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
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.E lapsedEventHand ler(
this._Timer_Ela psed );
_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.E lapsedEventArgs 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:\P OSettings.txt") ;
if (debug) {writeLog("Crea ting
FileInfo", false);}
StreamReader s = fConf.OpenText( );
if (debug) {writeLog("Open ed File",
false);}
string read = null;
if (debug) {writeLog("Read ing File",
false);}
while ((read = s.ReadLine()) != null)
{
getParam(read);
}
s.Close();
}
catch (Exception e)
{
writeLog("Syste m Error Retrieving
Configuration" +
e.Message.ToStr ing(), true);
}
}
/// <summary>
/// Populates global variables with values passed from
GetConfig()
/// </summary>
private void getParam(string sKeyVal)
{
if (debug) {writeLog("Retr ieving Values using
:" + sKeyVal, false);}
if (sKeyVal.Substr ing(0,3).ToUppe r() != "REM")
{
if (sKeyVal.IndexO f(",",0) > 0)
{
string[] aKeyVal =
sKeyVal.Split(' ,');
string sKey =
aKeyVal[0].ToUpper();
string sVal = aKeyVal[1];
switch (sKey)
{
case "SMTPSERVER ":
SMTPServer =
sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "DATABASESERVER ":
sDBServer =
sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "DATABASE":
sDB = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "USERNAME":
sUID = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
case "PASSWORD":
sPass = sVal;
if (debug)
{writeLog("Para m val = "+sVal ,false);}
break;
default:
writeLog("Param eter 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=SQLOL EDB.1;server=" +
sDBServer + ";UID=" +
sUID + ";PWD=" + sPass + ";DATABASE= " + sDB;
oConn = new SqlConnection(s DSN);
string sSQL = "SELECT [No_] as No, [Buy-from
Vendor No_] as VNo FROM
[CrocusDevelopme ntupdate$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.Execut eReader(Command Behavior.Defaul t);
writeLog("Proce ssing Started", false);
while (oRS.Read())
{
writeLog("No = " +
oRS["No"].ToString(), false);
}
oRS.Close();
oConn.Close();
}
catch (Exception e)
{
writeLog("Proce ssing 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 = "Applicatio n";
string sSource = "NAVEmailPO ";
EventLogEntryTy pe oType;
if (!EventLog.Sour ceExists(sSourc e))
{
EventLog.Create EventSource(sSo urce,
log);
}
EventLog oLog = new EventLog();
oLog.Source = sSource;
if (String.Compare (oLog.Log, log, true,
CultureInfo.Inv ariantCulture) != 0)
{
//Shafted log in use by something else
return false;
}
if (bError)
{
oType = EventLogEntryTy pe.Warning;
}
else
{
oType = EventLogEntryTy pe.Information;
}
oLog.WriteEntry (sMessage, oType);
oLog.Close();
oLog.Dispose();
return true;
}
}
Comment