0

I am trying simple windows service it works fine till there is no connection with database.once I establish connection my service get installed and start successfully but does not work correctly and does not get stop.It throws an Error as :"Windows Could not Stop service on local computer".

Following is Code :

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

namespace tgfservice4
{
    public partial class tgfservice4 : ServiceBase
    {
        private static string con = "Data Source=ABC;Initial Catalog=ABC;User Id=ABC;Password=ABC";//ConfigurationManager.ConnectionStrings["ABCD"].ToString();
        private SqlConnection sn = new SqlConnection(con);

        private SqlCommand sm;
        Timer timer = new Timer();
        public tgfservice4()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //add this line to text file during start of service
            TraceService("start service");

            //handle Elapsed event
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

            //This statement is used to set interval to 1 minute (= 60,000 milliseconds)

            timer.Interval = 60000;

            //enabling the timer
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
            TraceService("stopping service");
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            TraceService("Another entry at " + DateTime.Now);
        }
        private void TraceService(string content)
        {


            sn.Open();
           // sm = new SqlCommand("Update_Table", sn);
          //  sm.CommandType = CommandType.StoredProcedure;
            try
            {
                //    sm.Parameters.AddWithValue("@value", "0");
                //    sm.ExecuteNonQuery();
            }
            catch
            {
                throw;
            }
            finally
            {
                sm.Dispose();
                sn.Close();
                sn.Dispose();
            }





            //set up a filestream
            FileStream fs = new FileStream(@"d:\MeghaService.txt", FileMode.OpenOrCreate, FileAccess.Write);

            //set up a streamwriter for adding text
            StreamWriter sw = new StreamWriter(fs);

            //find the end of the underlying filestream
            sw.BaseStream.Seek(0, SeekOrigin.End);

            //add the text
            sw.WriteLine(content);
            //add the text to the underlying filestream

            sw.Flush();
            //close the writer
            sw.Close();
        }
    }
}
2
  • 1
    Open the connection(sn.Open();) inside the try block Commented Feb 16, 2015 at 6:26
  • Ok I have open connection inside try block. but now another error is :the service on local computer started and then stopped.Some services stop automatically is they are not in use by other services or program..... Commented Feb 16, 2015 at 6:40

2 Answers 2

1

I think your OnStop method is taking long time to connect to database and opearting on that connection.

Generally you are supposed to do heavy operation in another thread in background.

Usually the OnStart as well as OnStop events within the windows service are used to initiate a process and the time consuming process will carryout it's execution within a child thread

If there is any error on startup then also service may behave like this. To debut you can do something like following.

protected override void OnStart(string[] args)
{
     System.Diagnostics.Debugger.Launch();
     ...
}

and then attach visual studio to the process and debug the issue.

also you can look into the Event viewer for system and application logs.

computer/server manager -> Event Viewer -> Windows Logs -> Application

Sign up to request clarification or add additional context in comments.

Comments

0

If an exception is thrown in OnStop, the Service Control Manager will not unload your service. As such, in case you have a problem connecting to the database, just log this in the event log without throwing further errors. Also, do not attempt to close the connection if it is not already opened. Add a try catch upon closing the connection. Bottom line, make sure nothing blows up in the OnClose.

1 Comment

Well, handle the error appropriately. Do not rethrow it. Log the error details in Windows event log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.