5

I am trying to develop an windows service for Windows 10 (64bit), which intends to insert record in local MS SQL Server (v.11) periodically.

It installed and ran successfully, but no record is inserted. I tried both System.Timers.Timer and System.Threading.Timer.

I also tried to insert on service start event. But that also didn't work.

Here is my code:

public partial class Service1 : ServiceBase
{
    // System.Timers.Timer timer;
    System.Threading.Timer threadTimer;
   
    public Service1()
    {
        InitializeComponent();
    }


    //UPDATE: I checked the following method code in a console application. It works fine.
    private void InsertRecord()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection("Server=.;Database=TestDb; Trusted_Connection=True;"))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;
                    command.CommandText = "Insert into .....')";
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected override void OnStart(string[] args)
    {
        InsertRecord(); //This line not executed also.

        TimeSpan tsInterval = new TimeSpan(0, 2, 0); //2 minute interval.
        threadTimer = new Timer(new TimerCallback(threadTimer_Elapsed)
            , null, tsInterval, tsInterval);


        //timer = new System.Timers.Timer();
        //timer.Interval = 10000;
        //timer.Elapsed += Timer_Elapsed;
        //timer.Enabled = true;
        //timer.Start();
    }

    private void threadTimer_Elapsed(object state)
    {
         InsertRecord();
    }

    //private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    //{
    //      InsertRecord()
    //}

    protected override void OnStop()
    {
        threadTimer.Change(Timeout.Infinite, Timeout.Infinite);
        threadTimer.Dispose();
        threadTimer = null;

        //timer.Stop();
    }
}

What did I miss here?

7
  • Make sure your insert code works and check if your service is running from windows services. Commented Oct 27, 2017 at 5:13
  • 4
    An empty catch block is a good way to stay in the dark... Commented Oct 27, 2017 at 5:14
  • You are using Trusted Connection=true. Does the user that your Windows Service run under have permissions to access the database and run the query? Commented Oct 27, 2017 at 5:15
  • If it is not reaching OnStart then you have a service startup failure. Look at the Windows Event Log Commented Oct 27, 2017 at 5:15
  • 1
    Also, it would help considerably if you add some sort of logging so you can see what errors are happening when running the service. Commented Oct 27, 2017 at 5:15

3 Answers 3

8

In your SQL Server, allow NT AUTHORITY/SYSTEM to server Role as sysadmin.

Follow the screenshots-

enter image description here

enter image description here

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

Comments

1

Change the Run As setting on the service to run as your own personal account. This will provide the same security environment as your console test. This will allow the service permission to log into SQL Server.

Then change the service to "Local System" or similar and it will fail - you need to then grant "Local System" rights to access the database.

Also - an empty Catch block is the reason you are posting to SO - if you coded the simplest of error handler and loggers you would get your answer.

Comments

0

You did not provide a lot of information about your connection string, but as @NightOwl888 pointed out, the problem may have to do with your use of Trusted_Connection=True.

If you are using Sql Authentication (as opposed to Windows Authentication) to connect to the Sql server, I believe you need to set Trusted_Connection=False.

This should allow your connection string credentials to be used (rather than the machine name/Windows service account/etc.).

Comments

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.