Solved

Service only ran once - please help!

Posted on 2004-10-19
10
398 Views
Last Modified: 2010-04-15
This service only ran once.  I got the code, but it's not working and I don't know or understand enough to fix it.
It needs to run every 30 minutes.  Please help.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
using System.Data.SqlClient;

namespace WGUpdtSvc
{
      public class WGUpdt : System.ServiceProcess.ServiceBase
      {
            private System.Timers.Timer timer1;

            private System.ComponentModel.Container components = null;
            protected object[] recHdr;
            public WGUpdt()
            {
                  InitializeComponent();
            }

            // The main entry point for the process
            static void Main()
            {
                  System.ServiceProcess.ServiceBase[] ServicesToRun;      
                  ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WGUpdt() };
                  System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            }


            private void InitializeComponent()
            {
                  this.timer1 = new System.Timers.Timer();
                  ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();

                  this.timer1.Enabled = true;
                  this.timer1.Interval = 100000;
                  this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);

                  this.ServiceName = "WGUpdt";
                  ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();

            }


            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }


            protected override void OnStart(string[] args)
            {            
            }
 
            protected void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                  this.UpdtWG();
            }
            private void UpdtWG()
            {

                  dbAccess dba = new dbAccess();
                  SqlConnection con = dbAccess.getSqlConnection("Order");
                  SqlConnection conConf = dbAccess.getSqlConnection("Config");      
                  string sqlHdr = "select * from Config ORDER BY ID";

                  string confTabl = "Conf";
                  DataTable dtConf = new DataTable();
                  dtConf = dbAccess.getDataTable(conConf, confTabl, sqlHdr);            
                  foreach (DataRow drC in dtConf.Rows)
                  {
                        try
                        {  
                                      // process each record
                        }
                        catch (Exception ex)
                        {
                              string errmsg=ex.Message;
                              string errmsg2=ex.Message;
                        }

                  }

            }      
            protected override void OnStop()
            {
            }


      }
}
0
Comment
Question by:dcass
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 8

Assisted Solution

by:AaronReams
AaronReams earned 100 total points
ID: 12354642
I suspect opening your database connection is throwing an exception.  Just speculating but maybe you didn't shut down the previous db connection correctly.

try wrapping your entire timer call in a try statement to see if that's it.

protected void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
     this.UpdtWG();
}
catch(Exception ex)
{
    //see if you're getting an exception here
}
}

good luck,
aaron
0
 
LVL 3

Expert Comment

by:aacool
ID: 12354986
I was having problems with your code - with and without a database connection.

I finally deleted your timer event initialization code from the InitializeComponent method.

I then added a new Timer object from the components tab of the Toolbox and set the properties as you have them. I also added an event handler.  This works perfectly fine for me now - both with and without a database connection. Here is the code for my InitializeComponent and EventHandler. Please contact me if you would like the full project code

I assume you are adding a ProcessInstaller to your project and installing it using installutil before starting the windows service.

            private void InitializeComponent()
            {
                  this.timer2 = new System.Timers.Timer();
                  ((System.ComponentModel.ISupportInitialize)(this.timer2)).BeginInit();
                  //
                  // timer2
                  //
                  this.timer2.Enabled = true;
                  this.timer2.Interval = 10000;
                  this.timer2.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
                  //
                  // Service1
                  //
                  this.ServiceName = "TimedSvc";
                  ((System.ComponentModel.ISupportInitialize)(this.timer2)).EndInit();

            }

            private void timer1_Elapsed(object sender, ElapsedEventArgs e)
            {
                  if(flg==false)
                  {
//                        sqlConnection1.Open();
//                        sqlDataAdapter1.Fill(auditDataSet11,"ProductAudit");
//                        sqlConnection1.Close();
//                        m_dataTable = auditDataSet11.Tables["ProductAudit"];
                        flg=true;
                  }

// Both the eventlog writer version
//and the database logger version work fine - commented the db version out                  this.EventLog.WriteEntry(e.SignalTime.ToLongTimeString());
//                  this.UpdateOnElapsed(sender,e);
            }
//            private static int id = 14;
/*            private void UpdateOnElapsed(object sender,ElapsedEventArgs e)
            {
                  try
                  {
                        sqlConnection1.Open();
                        DataRow newRow = m_dataTable.NewRow();
                        newRow["ID"] = id++;
                        newRow["Action"] = sender.ToString()+" woke up";
                        newRow["TookPlace"] = e.SignalTime;
                        m_dataTable.Rows.Add(newRow);
                        int nRows = sqlDataAdapter1.Update(m_dataTable);
                        sqlConnection1.Close();
                  }
                  catch(Exception ex)
                  {
                        this.EventLog.WriteEntry(ex.Message+" "+ex.StackTrace);
                        this.OnStop();
                  }
            }
*/
0
 

Author Comment

by:dcass
ID: 12362027

My problem now is that I need an error log - can you help with that?  It ran on the test server, but is not running at all on the live server.

This code kept it going after the initial first time:
            protected override void OnContinue()
            {
                  this.timer1.Start();
            }
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:aacool
ID: 12362074
Did you try writing to the event log and viewing it from the event viewer? This will work for any windows service app.

this.EventLog.WriteEntry(...)

Or you can write to your own file whenever you have to trap an event. OPen the file in your constructor and do

fs.WriteLine(...) as needed.

Based on how you define an 'error', throw an exception and catch the relevant exception and write to a log file/EventLog
0
 

Author Comment

by:dcass
ID: 12362368
So I can just add this code:
catch (Exception ex)
{
      string errmsg=ex.Message;                                          this.EventLog.WriteEntry(errmsg);
}
nothing else?
0
 
LVL 3

Expert Comment

by:aacool
ID: 12365040
well, you need to have a try block around the code that might throw the exception.
0
 

Author Comment

by:dcass
ID: 12368910
Yes, but I know that I need more code.  Please help!!!
For example, I can't get any of this code from Microsoft to work, so what is right?

// tried adding this with existing code - didn't compile
      //private System.Diagnostics.EventLog eventLog1;
      //protected System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog();

//  Won't compile - no WriteEntry available
      //System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog("Application", "myserver", "newsource");
      //eventLog1.WriteEntry("Test");    


// not even close to compiling
            EventLog myNewLog = new EventLog();
            myNewLog.Log = "NewEventLog";
            myNewLog.MachineName = "MyServer";                      
            foreach(EventLogEntry entry in myNewLog.Entries)
                                                         {
            Console.WriteLine("\tEntry: " + entry.Message);
0
 

Author Comment

by:dcass
ID: 12369375
I got it to compile but to setup, I followed these instructions and get a really weird error (at end):

From the Components tab of the Toolbox, drag an EventLog component to the form.
In the Properties window, set the following values:
Set the Log property to Application.
Set the MachineName property to the name of the server on which the event log resides. Use a period (.) for the local computer.
Set the Source property to the string of your choice. In this case, you can use the name of your project.
Save your files.
Note   For more information on creating EventLog component instances and setting their properties, see Logging Application, Server, and Security Events.
To create an installation component for your EventLog component

In the designer, click the EventLog1 component.
In the Description area at the bottom of the Properties window, click the Add Installer link.
A ProjectInstaller class appears in your project, and an installation component is added to it. You can now install and run your application.

To build your installation

Save your project and build it.
Note   Because this installer will function correctly without changing the existing methods, you do not need to override the Install, Commit, Rollback, and Uninstall methods.
A setup project will install the compiled project files and run the installers needed to run a Windows Service.

To create a setup project for your service

On the File menu, point to Add Project, then click New Project.
In the Project Types pane, select the Setup and Deployment Projects folder.
In the Templates pane, select Setup Project. Name the project MyEventLogSetup.
A setup project is added to the solution. Next you will add the output from the Windows Service project to the setup.

To add the project output to the setup

In Solution Explorer, right-click MyEventLogSetup, point to Add, then choose Project Output.
The Add Project Output Group dialog box appears.

MyEventLog is selected in the Project box.
In the list box, select Primary Output, then click OK.
A project item for the primary output of MyEventLog is added to the setup project. Now add a custom action to install the MyNewService.exe file.

To add a custom action to the setup

In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions.
The Custom Actions editor appears.

In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action.
The Select Item in Project dialog box appears.

Double-click the Application Folder in the list box to open it, select Primary Output from MyEventLog (Active), and click OK.
The primary output is added to all four nodes of the custom actions, Install, Commit, Rollback, and Uninstall.

Build the setup project.
Browse to the directory where the setup project was saved, and run the .msi file to install.


This is where I get:
Error 1706 No valid source could be found for product Visual Studio .NET Enterprise Architect.  The Windows Installer Cannot Continue.
0
 
LVL 3

Accepted Solution

by:
aacool earned 400 total points
ID: 12377101
Looks like your install is corrupt/missing some files
0
 

Author Comment

by:dcass
ID: 12440477
I got this to work for a while, then opened new question so please close.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question