I am writing a Scheduling Client Server Application. The Server Application uses Window Service using Quartz and the Client application (For testing using both WEB and Console Applications) . Both client /Server Project build successfully but when i start service and my console application communicate with this service .An exception Comes when Client Object Calls : sched.ScheduleJob(Job,Trigger)
it through Exception on this line.
Below is my code snippet
namespace QuartzService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private IScheduler sched;
public void Show()
{
try {
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServer";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting exporter
properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
properties["quartz.scheduler.exporter.port"] = "555";
properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
properties["quartz.scheduler.exporter.channelType"] = "tcp";
properties["quartz.scheduler.exporter.channelName"] = "httpQuartz";
/// properties = (NameValueCollection)ConfigurationManager.GetSection("quartz");
ISchedulerFactory sf = new StdSchedulerFactory(properties);
sched = sf.GetScheduler();
sched.Start();
string lines = "==================Start===========================\n"+DateTime.Now.TimeOfDay.ToString()+"\n====================END=========================\n";
// Write the string to a file.
string filepath = #"D:\Murtaza\Service\test.txt";
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);
file.WriteLine(lines);
file.Close();
// Console.WriteLine("Hello");
// Thread.Sleep(TimeSpan.FromMinutes(1));
// sched.Shutdown(true);
}
catch { }
}
}
}
===============================
Here is Client Console Application Code:
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteClient";
properties["quartz.scheduler.instanceId"] = "AUTO";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting expoter
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.scheduler.proxy.address"] = "tcp://10.0.0.46:555/QuartzScheduler";// "tcp://10.0.0.85:555/QuartzScheduler"; //"tcp://10.0.0.46:555/QuartzScheduler";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
IJobDetail job = JobBuilder.Create<TestJob>()
.WithIdentity("remotelyAddedJob", "default")
.Build();
JobDataMap map = job.JobDataMap;
map.Put("msg", "Your remotely added job has executed!");
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("remotelyAddedTrigger", "default")
.ForJob(job.Key)
.WithCronSchedule("/5 * * ? * *")
.Build();
// schedule the job
sched.ScheduleJob(job, trigger);
}
catch (Exception ex)
{ }
}
}
}
Related
I have a project installer which installs a Windows service.
When I create a new version I need to uninstall it and install the new version.
Please check the code below:
private void InitializeComponent()
{
this.ServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.MyServiceInstaller = new System.ServiceProcess.ServiceInstaller();
//
// ServiceProcessInstaller
//
this.ServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.ServiceProcessInstaller.Password = null;
this.ServiceProcessInstaller.Username = null;
this.ServiceProcessInstaller.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.BeforeInstall);
//
// MyServiceInstaller
//
this.MyServiceInstaller.Description = "Description";
this.MyServiceInstaller.ServiceName = "My Service";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.ServiceProcessInstaller,
this.MyServiceInstaller});
}
void BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == "My Service")
{
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new InstallContext();
ServiceInstallerObj.ServiceName = "My Service";
ServiceInstallerObj.Uninstall(null);
break;
}
}
}
I set the BeforeInstall event but I got Error 1001 again.
I can successfully Start/Stop service Manually but it fails to start on a system restart although startup type is set to 'Automatic'. On some terminal, when rebooted, service fail to start with error failed to connect DB
29052019 17:25:27 ERROR Logs.TransactionLogManager - Exception Thrown in getNewSession()
29052019 17:25:27 ERROR Logs.TransactionLogManager - Unable To Open Database Session
29052019 17:25:27 ERROR Logs.TransactionLogManager - Unable to complete network request to host "localhost".
at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.CreateNewConnectionIfPossibleImpl(FbConnectionString connectionString)
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.GetConnection(FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare()
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper)
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory)
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at StevensCommon.Database.FluentNHibernateManager.OpenNewSession()
at StevensCommon.DAOs.StevensDAO.GetNewSession()
On development environment whilst debugging I'm not even getting any error. Assuming that on my machine the firebird services does start up before my service, still it fails to start the service on a reboot. And nothing comes up in the log.
I've added some log points within the code and they all gets logged when I Stop/Start the service manually. But nothing shows up in the log when system is rebooted and server never gets started.
Tried adding Firebird Service as a dependencies in the Project/Service Installer, set the DelayedAutoStart = true. Whatever solution I read online I've tried it but service is not starting on a reboot.
Following I'm adding starting/entry point snippet of the service.
Program.cs
static class Program
{
static void Main(string[] args)
{
TransactionLogManager.WriteServiceLog("FLAG - Before DAO Call", null);
// Check to see if we have a licence
if (LicenceFileDAO.GetLicence() != null && LicenceManager.IsLicenceActive())
{
TransactionLogManager.WriteServiceLog("FLAG - Inside DAO Block", null);
//Run the IS Service
ServiceBase[] ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
TransactionLogManager.WriteServiceLog("FLAG - End of DAO Call", null);
}
else
{
TransactionLogManager.WriteServiceLog("No Valid Licence Found - Either A Licence Has Not Been Activated Or It Has Expired. Please Contact Support", null);
}
}
}
MyService.cs
public partial class MyService : ServiceBase
{
protected static Timer importTimer = null;
protected static Timer exportTimer = null;
protected static Timer licenceTimer = null;
protected static Timer requestTimer = null;
protected static Timer uploadTimer = null;
protected static Timer handshakeTimer = null;
protected static Timer scheduledReportTimer = null;
protected static Timer alertTimer = null;
public static Boolean ImportRunning = false;
public static Boolean ExportRunning = false;
public static Boolean RequestRunning = false;
public static Boolean UploadRunning = false;
public static Boolean HandshakeRunning = false;
public static Boolean ScheduledReportRunning = false;
public static Boolean AlertReportRunning = false;
public static int? zynkWorkflowProcessId = null;
public MyService()
{
TransactionLogManager.WriteServiceLog("FLAG - 1", null);
InitializeComponent();
InitializeServiceTimers();
try
{
MessengerService.Start();
TransactionLogManager.WriteServiceLog("Messaging Service Started", null);
}
catch (Exception e)
{
TransactionLogManager.WriteServiceLog(e.Message, e.StackTrace);
}
}
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
//
// MyService
//
this.ServiceName = "MyService";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
private void InitializeServiceTimers()
{
if (!System.Diagnostics.EventLog.SourceExists("Stevens Integration Service"))
{
System.Diagnostics.EventLog.CreateEventSource(
"Stevens Integration Service", "ServiceLog");
}
eventLog1.Source = "Stevens Integration Service";
eventLog1.Log = "ServiceLog";
TransactionLogManager.WriteServiceLog("FLAG - 2", null);
importTimer = new Timer(IntegrationServiceSettings.GetImportInterval() * 1000);
exportTimer = new Timer(IntegrationServiceSettings.GetExportInterval() * 1000);
licenceTimer = new Timer(86400 * 1000); // Daily
requestTimer = new Timer(IntegrationServiceSettings.GetRequestInterval() * 1000);
scheduledReportTimer = new Timer(30000);
alertTimer = new Timer(20000);
importTimer.Elapsed += new ElapsedEventHandler(ImportTimerElapsed);
exportTimer.Elapsed += new ElapsedEventHandler(ExportTimerElapsed);
licenceTimer.Elapsed += new ElapsedEventHandler(LicenceTimerElapsed);
requestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed);
scheduledReportTimer.Elapsed += new ElapsedEventHandler(ScheduledReportTimerElapsed);
alertTimer.Elapsed += new ElapsedEventHandler(AlertTimerElapsed);
TransactionLogManager.WriteServiceLog("FLAG - 3", null);
StartTimers();
TransactionLogManager.WriteServiceLog("FLAG - 4", null);
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Stevens Integration Service Starting...");
TransactionLogManager.WriteServiceLog("FLAG - OnStart() Started", null);
if (StevensDAO.TestConnection())
{
eventLog1.WriteEntry("Configure Settings...");
IntegrationServiceSettings.InitialiseAll();
eventLog1.WriteEntry("Done.");
}
TransactionLogManager.WriteServiceLog("FLAG - OnStart() Finished", null);
TransactionLogManager.WriteServiceLogInfo("Started");
eventLog1.WriteEntry("Started.");
}
}
ProjectInstaller - That Includes System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
private MyService myService ;
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
this.myService = new IntegrationService.MyService();
// serviceProcessInstaller1
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// serviceInstaller1
this.serviceInstaller1.Description = "My Integration Service";
this.serviceInstaller1.DisplayName = "MyService";
this.serviceInstaller1.ServiceName = "MyService";
//this.serviceInstaller1.ServicesDependedOn = new string[] { "Firebird Guardian - DefaultInstance", "Firebird Server - DefaultInstance" };
//this.serviceInstaller1.DelayedAutoStart = true;
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
// myService
this.myService.ExitCode = 0;
this.myService.ServiceName = "MyService";
// ProjectInstaller
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
LogPoints - On manual Start/Stop I do get following log points, but when I reboot the system nothing comes up
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - Before DAO Call
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - Inside DAO Block
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 1
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 2
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 3
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 4
30052019 16:19:35 ERROR Logs.TransactionLogManager - Messaging Service Started
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - OnStart() Started
30052019 16:19:35 ERROR Logs.TransactionLogManager - Client 1 is now connected!
30052019 16:19:36 ERROR Logs.TransactionLogManager - FLAG - OnStart() Finished
here i am giving a small my code snippet just to show what i am trying to achieve.
private void frmMain_Load(object sender, EventArgs e)
{
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
sched = schedFact.GetScheduler();
sched.Start();
IJobDetail job = JobBuilder.Create<frmMain>()
.WithIdentity("Job", "group")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(01, 55))
)
.Build();
sched.ScheduleJob(job, trigger);
}
public void Execute(IJobExecutionContext context)
{
generate();
}
public void generate()
{
if (this.FetchStart != null)
this.FetchStart(this, new EventArgs());
System.Threading.Thread.Sleep(5000);
if (this.FetchDone != null)
this.FetchDone(this, new EventArgs());
}
i have done my project with VS2013 community edition. my objective is to call slide show routine every day at specific time. when i am calling my slide show routine without quartz.net scheduler then it is working fine but when i invoke my routine by quartz.net scheduler then routine is getting called but no slide show image is showing.
what [problem occur is not clear to me. as per my objective i have to use quartz.net scheduler because i need to invoke my routine at a specific time of day every day.
here i am sharing my project code because it is in onedrive. so my request please some one download my project and run at your end to see the problem and tell me the reason which causes not to show images on picture box.
if possible please rectify my code with quartz.net scheduler code. one drive project link is https://1drv.ms/f/s!AmIfMNV-CodPa81zFiNH6Ur7qro
i upload my project folder.
thanks
UPDATE
when i use background worker along with quartz.net to call my generate routine then also no improvement i found. same problem that slide show image is not appearing on picture box.
here is the code for quartz.net with background worker
public partial class frmMain : Form, IJob
{
ucSlide oSlide = new ucSlide();
IScheduler sched = null;
BackgroundWorker m_oWorker = null;
public event EventHandler FetchStart;
public event EventHandler FetchDone;
public event EventHandler NoDataFound;
public frmMain()
{
InitializeComponent();
m_oWorker = new BackgroundWorker();
m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
oSlide.MainForm = this;
oSlide.SlideSource = Utility.SlidePath;
this.Controls.Add(oSlide);
oSlide.Dock = DockStyle.Fill;
}
private void frmMain_Load(object sender, EventArgs e)
{
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
sched = schedFact.GetScheduler();
sched.Start();
IJobDetail job = JobBuilder.Create<frmMain>()
.WithIdentity("Job", "group")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(02,23))
)
.Build();
sched.ScheduleJob(job, trigger);
}
public void Execute(IJobExecutionContext context)
{
m_oWorker.RunWorkerAsync();
}
public void generate()
{
if (this.FetchStart != null)
this.FetchStart(this, new EventArgs());
System.Threading.Thread.Sleep(5000);
if (this.FetchDone != null)
this.FetchDone(this, new EventArgs());
}
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
generate();
}
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// The background process is complete. We need to inspect
// our response to see if an error occurred, a cancel was
// requested or if we completed successfully.
//if (e.Cancelled)
//{
// //lblStatus.Text = "Task Cancelled.";
// isBusy = false;
//}
//// Check to see if an error occurred in the background process.
//else if (e.Error != null)
//{
// //lblStatus.Text = "Error while performing background operation.";
// MessageBox.Show(e.Error.InnerException.Message.ToString());
// isBusy = false;
//}
//else
//{
// // Everything completed normally.
// //lblStatus.Text = "Task Completed...";
// isBusy = false;
//}
}
}
thanks
after spending lots of hour i found out the way to get my code work.
i have to pass my form reference with scheduled this way.
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
sched = schedFact.GetScheduler();
sched.Start();
IJobDetail job = JobBuilder.Create<frmMain>()
.WithIdentity("Job", "group")
.Build();
job.JobDataMap.Put("Form", this);
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(20, 27))
)
.Build();
sched.ScheduleJob(job, trigger);
the main trick lies here
job.JobDataMap.Put("Form", this);
AND
public void Execute(IJobExecutionContext context)
{
var dataMap = context.MergedJobDataMap;
var frmInstance = (frmMain) dataMap["Form"];
frmInstance.generate();
}
all thanks goes to #hillstuk and his link is https://stackoverflow.com/a/25660846/728750
my full code slide show with quartz.net
using System;
using System.IO;
using System.Windows.Forms;
using Quartz;
using Quartz.Impl;
using System.Timers;
namespace SchedulerWithTimer
{
public partial class frmMain : Form, IJob
{
private int imageNumber = 1, SlideCount = 0;
string _SlideSource = "";
System.Timers.Timer aTimer = new System.Timers.Timer();
IScheduler sched = null;
public frmMain()
{
InitializeComponent();
_SlideSource = Utility.SlidePath;
SlideCount = Directory.GetFiles(_SlideSource, "*", SearchOption.AllDirectories).Length;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = false;
}
private void frmMain_Load(object sender, EventArgs e)
{
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
sched = schedFact.GetScheduler();
sched.Start();
IJobDetail job = JobBuilder.Create<frmMain>()
.WithIdentity("Job", "group")
.Build();
job.JobDataMap.Put("Form", this);
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(20, 27))
)
.Build();
sched.ScheduleJob(job, trigger);
}
public void Execute(IJobExecutionContext context)
{
var dataMap = context.MergedJobDataMap;
var frmInstance = (frmMain) dataMap["Form"];
frmInstance.generate();
}
public void generate()
{
FetchStart();
System.Threading.Thread.Sleep(5000);
FetchDone();
}
public void FetchStart()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(delegate()
{
aTimer.Enabled = false;
picSlide.SizeMode = PictureBoxSizeMode.CenterImage;
picSlide.Image = SchedulerWithTimer.Properties.Resources.loading;
}));
}
else
{
aTimer.Enabled = false;
picSlide.SizeMode = PictureBoxSizeMode.CenterImage;
picSlide.Image = SchedulerWithTimer.Properties.Resources.loading;
}
}
public void FetchDone()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(delegate()
{
aTimer.Enabled = true;
}));
}
else
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(delegate()
{
loadNextImage();
}));
}
else
loadNextImage();
}
private void loadNextImage()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(delegate()
{
if (imageNumber == SlideCount)
{
imageNumber = 1;
}
picSlide.SizeMode = PictureBoxSizeMode.Zoom;
picSlide.ImageLocation = string.Format(_SlideSource + #"\Slide{0}.jpg", imageNumber);
}));
}
else
{
if (imageNumber == SlideCount)
{
imageNumber = 1;
}
picSlide.SizeMode = PictureBoxSizeMode.Zoom;
picSlide.ImageLocation = string.Format(_SlideSource + #"\Slide{0}.jpg", imageNumber);
imageNumber++;
}
}
}
}
may be some day my post may help other. thanks all :)
I have a windows service that is supposed to check for a record, email a report for that record, delete the record and then repeat for the table. It checks for the record, emails a report for the first record then shuts off. Any ideas??
Service code:
namespace ReportSender
{
public partial class EmailReportService : ServiceBase
{
private EmailReportApp _app = new EmailReportApp();
public Timer serviceTimer = new Timer();
public EmailReportService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//Set interval (from App Settings) and enable timer
serviceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_OnElapsed);
//Use Conversion utility to determine next start date/time based on properties, use DateTime.Subtract() to find milliseconds difference between Now and the next start time
//serviceTimer.Interval = Date.AddInterval(Properties.Settings.Default.IntervalType, Properties.Settings.Default.Interval).Subtract(DateTime.Now).TotalMilliseconds;
serviceTimer.Interval = 600000;
serviceTimer.Enabled = true;
}
protected override void OnStop()
{
//Stop and disable timer
serviceTimer.Enabled = false;
}
private void ServiceTimer_OnElapsed(object source, ElapsedEventArgs e)
{
try
{
//Stop the timer to prevent overlapping runs
serviceTimer.Stop();
//Start service
//Run your app.Start() code
_app = new EmailReportApp();
_app.Start();
}
catch (Exception ex)
{
}
finally
{
//Re-start the timer
serviceTimer.Start();
}
}
}
}
Code the service is supposed to execute:
namespace ReportSender
{
class EmailReportApp
{
// Private fields
private Thread _thread;
private EventLog _log;
private void Execute()
{
try
{
// Check for a new record
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
dc.reportsSent1s.DeleteOnSubmit(item);
dc.SubmitChanges();
}
}
catch (ThreadAbortException ex)
{
_log.WriteEntry(ex.StackTrace.ToString());
}
}
public void Start()
{
if (!EventLog.SourceExists("EventLoggerSource"))
EventLog.CreateEventSource("EventLoggerSource", "Event Logger");
_log = new EventLog("EventLoggerSource");
_log.Source = "EventLoggerSource";
_thread = new Thread(new ThreadStart(Execute));
_thread.Start();
}
public void Stop()
{
if (_thread != null)
{
_thread.Abort();
_thread.Join();
}
}
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("234#acmetaxabstracts.com", "georr#gmail.com", "Report for BRT # " + matchedAdd, "Attached if the Tax Information Certificate for the aboved captioned BRT Number");
MailAddress copy = new MailAddress("a123s#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.**.***.**");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
}
catch (Exception ex)
{
}
}
}
}
The 'ServiceBase' is losing scope once the OnStart method is called. A 'ManualResetEvent' will keep the service open for you.
Use member:
ManualResetEvent stop = new ManualResetEvent(false);
Try this in your main Start():
do
{
try
{
_app = new EmailReportApp();
_app.Start();
}
catch(Exception e)
{
... handle error or log however you want
}
}
while(!stop.WaitOne(0, false))
in Stop(), make sure to do stop.Set()
I'm having a bizarre issue that I haven't seen before and I'm thinking it MUST be something simple that I'm not seeing in my code.
I have a project with 2 windows services defined. One I've called DataSyncService, the other SubscriptionService. Both are added to the same project installer. Both use a timer control from System.Timers.
If I start both services together, they seem to work fine. The timers elapse at the appropriate time and everything looks okay. However, if I start either service individually, leaving the other stopped, everything goes haywire. The timer elapses constantly and on the wrong service. In other words, if I start the DataSyncService, the SubscriptionService timer elapses over and over. ...which is obviously strange.
The setup is similar to what I've done in the past so I'm really stumped. I even tried deleting both service and starting over but it doesn't seem to make a difference. At this point, I'm thinking I've made a simple error in the way I'm defining the services and my brain just won't let me see it. It must be creating some sort of threading issue that causes one service to race when the other is stopped. Here the code....
From Program.cs:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new DataSyncService(),
new SubscriptionService()
};
ServiceBase.Run(ServicesToRun);
}
From ProjectInstaller.designer.cs:
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.dataSyncInstaller = new System.ServiceProcess.ServiceInstaller();
this.subscriptionInstaller = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// dataSyncInstaller
//
this.dataSyncInstaller.DisplayName = "Data Sync Service";
this.dataSyncInstaller.ServiceName = "DataSyncService";
this.dataSyncInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// subscriptionInstaller
//
this.subscriptionInstaller.DisplayName = "Subscription Service";
this.subscriptionInstaller.ServiceName = "SubscriptionService";
this.subscriptionInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.dataSyncInstaller,
this.subscriptionInstaller});
}
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller dataSyncInstaller;
private System.ServiceProcess.ServiceInstaller subscriptionInstaller;
From DataSyncService.cs:
public static readonly int _defaultInterval = 43200000;
//log4net.ILog log;
public DataSyncService()
{
InitializeComponent();
//log = LogFactory.Instance.GetLogger(this);
}
protected override void OnStart(string[] args)
{
timer1.Interval = _defaultInterval; //GetInterval();
timer1.Enabled = true;
EventLog.WriteEntry("MyProj", "Data Sync Service Started", EventLogEntryType.Information);
//log.Info("Data Sync Service Started");
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("MyProj", "Data Sync Timer Elapsed.", EventLogEntryType.Information);
}
private void InitializeComponent()
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// DataSyncService
//
this.ServiceName = "DataSyncService";
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
From SubscriptionService:
public static readonly int _defaultInterval = 300000;
//log4net.ILog log;
public SubscriptionService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Interval = _defaultInterval; //GetInterval();
timer1.Enabled = true;
EventLog.WriteEntry("MyProj", "Subscription Service Started", EventLogEntryType.Information);
//log.Info("Subscription Service Started");
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("MyProj", "Subscription Service Time Elapsed", EventLogEntryType.Information);
}
private void InitializeComponent() //in designer
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// SubscriptionService
//
this.ServiceName = "SubscriptionService";
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
Again, the problem is that the timer1_elapsed handler runs constantly when only one of the services is started. And it's the handler on the OPPOSITE service.
Anybody see anything?
In the Service.Designer.cs files InitializeComponent() methods, I'm missing
this.CanShutdown = true;
...and I shouldn't be enabling the timers there since I do it in the OnStart handlers.
So it should be something like:
private void InitializeComponent()
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// DataSyncService
//
this.ServiceName = "DataSyncService";
this.CanShutdown = true;
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}