.Net, C#, Programming, Software, VB.NET, Visual Studio 2010, Visual Studio 2013

Example of Setting up a Blank Windows Service in Visual Studio 2017

When you are creating a new Windows Service Application in NET, you can’t simply generate the project and then click F5 to debug in Visual Studio. You need to follow a few setup steps to get the service to work. In the article below I’ll explain the basics along with a code sample.

First you’ll have to set up your Service so that it can be installed on your system. Then you need to register the service using the Developer Command Prompt for VS 2017. After you see that it has been successfully registered, you’ll need to start your service (the simplest way (again) is using the Developer Command Prompt for VS 2017). To uninstall after your test, you’ll also need to use the Developer Command Prompt.

The first step is to create a properly configured Service project

First Create the Windows Service Project:
  1. Open Visual Studio 2017
  2. Click File –> New Project and under C# or Visual Basic, select Windows Classic Desktop
  3. Select Windows Service (.NET Framework)
  4. Fill out the name, location, and solution fields
  5. Click the OK button to create your new service application
A framework for your bare-bones service will now exist. But this is not ready to be run as a service; first you must make some configurations.
  1. In Solution Explorer rename the Service1 file to a name of your choosing.
  2. A prompt will appear asking if you want to change the name everywhere… select the Yes option
  3. Also, while you are in the Design mode view of the new Service, check the Properties Window and make sure the ServiceName option is called what you want your service to be named.
Note that MSGBox alerts and other ways of debugging windows forms applications do not work with a Windows Service application, including the debugger, which will throw an error. The best way of checking code execution is to output from your service to the Windows Event logs.

For this bare-bones example, we’ll output to the Application event log when the Service first starts

  1. In Visual Studio click to view source of your service.
  2. Import the System.Diagnostics library
  3. Modify the OnStart event with custom event writing code so that it looks like the example below:
Imports System
Imports System.Diagnostics
Public Class ExampleService
    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        Dim strSource As String
        Dim strLog As String
        Dim strEvent As String
        Dim strMachine As String
        strSource = "ExampleService"
        strLog = "Application"
        strEvent = "Super Simple Example Event Warning Message"
        strMachine = "."
Dim mySourceData As EventSourceCreationData = New EventSourceCreationData(strSource, strLog)
        mySourceData.MachineName = strMachine
        If Not EventLog.SourceExists(strSource, strMachine) Then
            EventLog.CreateEventSource(mySourceData)
        End If
        Dim outLog As New EventLog(strLog, strMachine, strSource)
        outLog.WriteEntry(strEvent)
        outLog.WriteEntry(strEvent, EventLogEntryType.Warning, 234, CType(3, Short))
    End Sub
    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub
End Class
Ok great, now we have the code that will confirm that our service works when it first starts up. But you can’t just start the service up. You’ll first need to create an Installer file for your Service:
  1. In Visual Studio, click on the Design mode of your service so that you see it in your editor window
  2. Right-click in the gray area of the Service
  3. Click Add Installer
A new ProjectInstaller.vb class will be added to your solution. By default it will be in design mode and will have two components: ServiceInstaller1 and ServiceProcessInstaller1.
  1. Click once on ServiceInstaller1 
  2. In the Properties options, make sure the ServiceName option is what you entered as a Service Name in the design view of your Service
  3. Also, check the StartType… the easiest while you are developing is to choose the Manual start type

Now you’ll need to manage how the Service will run on the system. By default a service is not required to run as the local user account, and you can specify what account and what user-credentials the Service needs to run as. Here is a Microsoft help article that explains the different options that you can select: https://docs.microsoft.com/en-us/dotnet/api/system.serviceprocess.serviceaccount?view=netframework-4.7.1

  1. First click once on ServiceProcessInstaller1
  2. In the Properties options, choose the type of Account that you want the service to run as.
  3. If you choose User, then you’ll need to enter a UserName and Password in the installer’s InitializeComponent code, or otherwise you will be prompted for these when you install the service
  4. To do so, view the source of your ProjectInstaller
  5. Right click on the InitializeComponent  method call
  6. Choose: Go To Definition
  7. Update the UserName and Password information. These are set to null values by default.
Here is what you’ll see in the auto-generated InitializeComponent method, and how you should change your UserName, Password:
 <System.Diagnostics.DebuggerStepThrough()>
    Private Sub InitializeComponent()
        Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller()
        Me.ServiceInstaller1 = New System.ServiceProcess.ServiceInstaller()
       
        Me.ServiceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User
        Me.ServiceProcessInstaller1.Username = "yourDomain\username"
        Me.ServiceProcessInstaller1.Password = "SomePassword"
        
        Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceProcessInstaller1, Me.ServiceInstaller1})

    End Sub

Notice that if you want your service to impersonate a Network user, you have to set the service account type to User and then enter the user name and password for the account. Also make sure the account has sufficient permissions on the computer where you are going to be running it from (for example add it to the Administrators group). This will prevent installation errors when you are registering your service.

Finally, compile your project to make sure the executable for the new Service is built.

Getting your Service to Run

The Second Step is to Register and Start your new Service Project

At this point you are ready to register your new service on your system. If you chose a manual start type in ServiceInstaller1, you’ll also need to manually start your service. You can accomplish both of these things using the Developer Command Prompt for VS 2017.

First start the Developer Command Prompt for VS 2017 running as an Administrative level account. The Administrative level is important since otherwise your install is likely to fail for mysterious-seeming reasons. The simplest way is just to right click and select Run as Administrator when you are starting up the the Developer Command Prompt for VS 2017.

To locate the Developer Command Prompt for VS 2017:
  1. Open the start menu
  2. Then find the Expandable area for Visual Studio 2017 and expand it
  3. You’ll see the option to run the Developer Command Prompt for VS 2017
  4. To be sure you are running with high-enough credentials, right-click on the Developer Command Prompt for VS 2017 and select More –> Run as Administrator

In the the Developer Command Prompt for VS 2017 command prompt browse to the location where your Service executable file was created. If you are in Debug mode, this will likely be on your local file system under your Solution’s Name\bin\debug

Once you have browsed to the location of your service’s executable file, run the InstallUtil to register your new Service on your machine. The example syntax is:

installutil ExampleService.exe

At this point your new service should be registered and visible in your computer’s list of services. If you set your Service start type to Manual, you’ll now need to set your service to start. The easiest way is to use the Net Start command in the Developer Command Prompt for VS 2017 as follows:

Net Start ExampleService

If you check your computer’s list of services, you should now see that your bare-bones service is in the running state. Further, make sure to check that the service has logged its warning. In this example, the warning will have been logged to the Application events of the Windows Logs.

Note that if you want to uninstall your service, you’ll first want to stop your service and then unininstall it. To stop the service, type:

Net Stop ExampleService

And then to uninstall the service, the syntax is:

installutil /u ExampleService.exe
Advertisements