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();
}
}
}
(sn.Open();)inside thetryblock