Dot Net For All

How to create and Install C# Windows Service

In this article I will discuss about the windows service development and installation. The benefit of having a windows service is that we can put a timer in the service and do the operation on specified time span. Using that timer the service will keep performing its operation. I will develop the service using the C# as language.

This article is divided into three section as follow

  1. Developing the windows service
  2. Debugging the windows service.
  3. Installing/Uninstalling the windows service.

If you want to learn about the WCF service you can go to following links.

Developing the Windows Service

Step 1: Open the visual studio. Click On Add new project. Under Windows you will find Windows Service project template. If you don’t find it search for the windows service project template as shown in the below figure. I have selected the Windows service C# project template.

I have named the service as Logging Service. I will use this service to log some information in the text file at some time interval.

I will get the service project as shown in the figure below. By default Service1.cs is added to the solution, I have renamed it as LogService.cs as shown below.

Step 2: To install the service to the windows machine as service we need to add as installer. Double click on the LogSerivce.cs and we should be able to see the designer view. Right Click on the designer view and Click on the AddInstaller as shown in the figure below.

Step 3: In this step I will change the Code of the LogService.cs as shown below.

public partial class LogService : ServiceBase
    {
        private Timer timer;
        private Stopwatch watch;

        public LogService()
        {
            InitializeComponent();
        }

        public void OnDebug()
        {
           OnStart(null);
        } 

        protected override void OnStart(string[] args)
        {
            timer = new Timer(3000);
            watch = new Stopwatch();

            timer.Start();
            watch.Start();
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            LogWriter.LogInfo(string.Format("Message Logger since {0} seconds starting of service", watch.Elapsed));
        }

        protected override void OnStop()
        {
            watch.Stop();
            timer.Stop();

            timer.Dispose();            
        }
    }

To demonstrate the functionality of the windows service I have have written the code to log something.The functionality can be based on your own requirements. I have added the below class to the project for Logging the information which is not thread safe.

 public class LogWriter
    {
        private static string folderPath = AppDomain.CurrentDomain.BaseDirectory;

        public static void LogInfo(string messsage)
        {
            if (!File.Exists(folderPath + @"\\" + "Log" + ".txt"))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(folderPath + @"\\" + "Log" + ".txt"))
                {
                    sw.WriteLine(DateTime.Now + ":" + messsage + Environment.NewLine);
                }
            }

            else
            {
                using (StreamWriter sw = File.AppendText(folderPath + @"\\" + "Log" + ".txt"))
                {
                    sw.WriteLine(DateTime.Now + ":" + messsage + Environment.NewLine);
                }
            }
        }
    }

Debugging the Windows Service

If we debug the above service we will get the error “Cannot start service from the command line or debugger..” as shown in the figure below.

To debug the service we have to change the code of program.cs as shown below

static void Main()
        {
            #if DEBUG            
            LogService myService = new LogService();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

            #else            
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new LogService() 
            };
            ServiceBase.Run(ServicesToRun);
            #endif
        }

Now based on debugging or Release mode the code will run. I have already added the OnDebug method to the LogService.cs.

Now if we debug the service we can see that a file named Log.txt is created in the bin/Debug folder of the solution. It is being updated continuously at every 3 seconds.

Installing the Windows Service

Till now we have seen how we can debug the service. If we have to install the service to the system we have to follow these steps.

Step 1: To identify the service we have to give it some name. I have done following code changes to the ProjectInstaller.cs file.

    public ProjectInstaller()
        {
            InitializeComponent();
            serviceInstaller1.ServiceName = "LogService";
            serviceInstaller1.Description = "Used to Log Information";
        }

Step 2: Set the account for the ProcessInstaller as “LocalService”. Go the ProjectInstaller in design mode. Right click on the “serviceProcessInstaller1” as shown below and go to properties. Set the Account to “LocalService”.

Now build the project in release mode. Open the command prompt in administrator mode by right clicking on it and selecting Run as Administrator.

Step 2 : Go to the folder “C:\Windows\Microsoft.NET\Framework\v4.0.30319” in the command prompt and call the installUtil.exe as shown in the figure below. Followed by the path of the LoggingService.exe which we got after building the project in the release mode in previous step.

Press enter and we can see that the LoggingService is installed as shown in the figure below.

Step 3: Now open the service by typing “Services.msc” in the Run window which you can open by “Windows + R” key combination. We can see the LogginService is present in the services as shown in the figure below.

Start the service as we have not set the StartType to Automatic. After starting the service we can see in the Release folder where the LoggingService.exe was present, a new log file is created. It is updated at regular intervals. Our windows service is up and running.

Step 4: To uninstall the service we have to follow the same steps same as installing. Adding “-u” at the end of the command. The service will be uninstalled and deleted from the Services.

 Conclusion:

In this article I have shown how we can create windows service. For debugging the service we have to do some changes to the code. And how we can install and uninstall the service.

The code for solution is present here LoggingService.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview