Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Programatically Setup Windows Service using Windows Application

0.00/5 (No votes)
9 Mar 2016 1  
Easily setup service example with windows application

Introduction

I have been going through several windows service codes and samples. But everywhere, I was finding codes for services, but installation uses install.ui.exe using command line. I thought that for beginners, it will be very difficult to understand the uses of services and how it works.

Service Handling

  • Installing a Windows Service
  • Uninstalling a Windows Service
  • Starting a Service
  • Stopping a Service
  • Restarting a Service

Background

There is a Multiline Textbox that shows the result of each button click... like the installation, starting the service, stopping the service and uninstalling the service. If there is any exception, it will also be displayed in the textbox which makes it easy to understand and solve the problem.

Using the Code

You just need to change the path of the service so that you can run the service.

Besides the front end and the other part, the service is running with main 5 functions.

Installing the Service

try
            {
                ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();

                //In case of service account details

                ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
                InstallContext Context = new System.Configuration.Install.InstallContext();
                String path = String.Format("/assemblypath={0}", 
		@"C:\Users\Administrator\Downloads\Compressed\MyNewService\
		MyNewService\bin\Debug\MyNewService.exe");
                String[] cmdline = { path };

                Context = new System.Configuration.Install.InstallContext("", cmdline);
                ServiceInstallerObj.Context = Context;
                ServiceInstallerObj.DisplayName = "CoreMatchingCalculationService";
                ServiceInstallerObj.Description = "MyService installer test";
                ServiceInstallerObj.ServiceName = "MyService";
                ServiceInstallerObj.StartType = ServiceStartMode.Automatic;
                ServiceInstallerObj.Parent = ProcesServiceInstaller;

                System.Collections.Specialized.ListDictionary state = 
				new System.Collections.Specialized.ListDictionary();
                ServiceInstallerObj.Install(state);
                RichTextBoxExtensions.AppendText(txtMessage, "Service Installation Successfull!!" + 
						"\n\n", Color.Green);
            }
            catch (Exception ex)
            {
                RichTextBoxExtensions.AppendText(txtMessage, ex.Message.ToString() + 
				"!!Service Installation Failed!!" + "\n\n", Color.Red);
            }

Starting the Service

ServiceController service = new ServiceController("MyService");
           try
           {
               TimeSpan timeout = TimeSpan.FromDays(timeoutMilliseconds);

               service.Start();
               service.WaitForStatus(ServiceControllerStatus.Running, timeout);
               RichTextBoxExtensions.AppendText(txtMessage,
               "Service Started Successfully!!" + "\n\n", Color.Green);
               //ProcessStartInfo sInfo = new ProcessStartInfo("http://www.sanxodus.com/");
               //Process.Start(sInfo);
           }
           catch (Exception ex)
           {
               RichTextBoxExtensions.AppendText(txtMessage, ex.Message.ToString() +
                   "!!Service Start Failed!!" + "\n\n", Color.Red);
           }

Stopping the Service

ServiceController service = new ServiceController("MyService");
            try
            {
                TimeSpan timeout = TimeSpan.FromDays(timeoutMilliseconds);
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                RichTextBoxExtensions.AppendText(txtMessage, 
				"Service Stopped Successfully!!" + "\n\n", Color.Green);
            }
            catch (Exception ex)
            {
                RichTextBoxExtensions.AppendText(txtMessage, 
			ex.Message.ToString() + "!!Service Stop Failed!!" + "\n\n", Color.Red);
            }

Restarting the Service

ServiceController service = new ServiceController("MyService");
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromDays(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                RichTextBoxExtensions.AppendText(txtMessage, 
			"Service Restarted Successfully!!" + "\n\n", Color.Green);
            }
            catch (Exception ex)
            {
                RichTextBoxExtensions.AppendText(txtMessage, 
			ex.Message.ToString() + "!!Service Restart Failed!!" + "\n\n", Color.Red);
            }

Unistalling the Service

try
            {
                ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
                InstallContext Context = new InstallContext(@"C:\Users\Administrator\Downloads\Compressed\MyNewService\MyNewService\bin\Debug\MyNewService.exe", null);
                ServiceInstallerObj.Context = Context;
                ServiceInstallerObj.ServiceName = "MyService";
                ServiceInstallerObj.Uninstall(null);
                RichTextBoxExtensions.AppendText(txtMessage, "Service Uninstalled Successfully!!" + "\n\n", Color.Green);
            }
            catch (Exception ex)
            {
                RichTextBoxExtensions.AppendText(txtMessage, ex.Message.ToString() + "!!Service Uninstallation Failed!!" + "\n\n", Color.Red);

            }

 

 

Points of Interest

I think by just running this project, you will be able to understand the complete concept of the services. And the only need is to run the project and write the task to be executed.

History

  • Version 1.0

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here