Click here to Skip to main content
15,889,335 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Programatically Setup Windows Service using Windows Application

Rate me:
Please Sign up or sign in to vote.
4.72/5 (19 votes)
9 Mar 2016CPOL1 min read 21K   609   43   4
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

Image 1

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

C#
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

C#
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

C#
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

C#
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

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Comments and Discussions

 
Question+1 for TopShelf Pin
pharry2210-Mar-16 13:22
pharry2210-Mar-16 13:22 
AnswerRe: +1 for TopShelf Pin
Nadir Muhammed11-Mar-16 20:22
professionalNadir Muhammed11-Mar-16 20:22 
GeneralMy vote of 5 Pin
csharpbd10-Mar-16 8:02
professionalcsharpbd10-Mar-16 8:02 
GeneralMy vote of 3 Pin
sam.hill10-Mar-16 4:27
sam.hill10-Mar-16 4:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.