Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Service only ran once - please help!

Posted on 2004-10-19
10
Medium Priority
?
403 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 300 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 1200 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

Tech or Treat! - Giveaway

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

618 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