4
Answers

To execute a Stored procedure inside a windows service

I have created a windows service which has to execute a stored procedure once in every 5-10 min.
My service runs and builds without any errors but it does not execute the stored procedure. Below is the code I have written. I dont understand where the mistake is. Any suggestion will be really helpful. Even URLs related to this will be great.

using System;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using System.Configuration;


namespace offsiteBilling
{
    public partial class OffsiteAgent : ServiceBase
    {
      Timer sysTimer = new Timer();
      private int _interval = 300000;

      public OffsiteAgent()
      {
        InitializeComponent();
      }

      protected override void OnStart(string[] args)
      {
        sysTimer.Interval = _interval;
        sysTimer.Enabled = true;
        sysTimer.Start();
        sysTimer.Elapsed += new System.Timers.ElapsedEventHandler(onElapsed);
      }

      protected override void OnStop()
      {
      }

      private void onElapsed(object sender, ElapsedEventArgs e)
      {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
        try
        {
          SqlCommand cmd = new SqlCommand("GetOffsiteSrvrpath", conn);
          cmd.CommandType = CommandType.StoredProcedure;
          conn.Open();
          cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
          EventLog.WriteEntry("Error", ex.Message, EventLogEntryType.Warning);
        }
      }
    }
}
Answers (4)