Easier .NET Service installation 1

Below are two code snippets useful when creating a Windows Service in .NET.
 
Windows Services created as a .NET assembly are installed using InstallUtil. The code below allows installation and removal using the executable .NET assembly with the command-line options /i and /u respectively.
 

/// <summary>
///
The main entry point for the process.
/// Allows install and uninstall with command line option.
/// </summary>
///
<remarks>
///
Relies on <see cref="ProjectInstaller.OnBeforeUninstall"/> to set the user to local service
/// just before uninstall to prevent the service entry to linger until a reboot.
/// </remarks>
///
<param name="args">Command line arguments.</param>
private static void Main(string[] args)
{
      
if (args.Length > 0)
       {
             
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
             
string command = Path.Combine(systemPath, @"..\Microsoft.NET\Framework\v1.1.4322\InstallUtil.exe");
             
// Remove the ‘file:///’ prefix.
              string service = "\"" + Assembly.GetExecutingAssembly().CodeBase.Substring(8) + "\"";
             
switch (args[0].ToLower().Substring(1, 1))
              {
                    
case "i":
                           Run(command, service);
                           Run("net", "start Berichtensimulator");
                          
break;
                    
case "u":
                           Run("net", "stop Berichtensimulator");
                           Run(command, "/u " + service);
                          
break;
                    
default:
                           Console.WriteLine("Please specify ‘/i’ to install service and ‘/u’ to uninstall service.");
                          
break;
              }
       }
      
else
       {
              System.ServiceProcess.ServiceBase[] ServicesToRun;
              ServicesToRun =
new ServiceBase[] { new BerichtenSimulatorSvc() };
              ServiceBase.Run(ServicesToRun);
       }
}

private static void Run(string command, string args)
{
       ProcessStartInfo processStart =
new ProcessStartInfo(command, args);
       processStart.UseShellExecute =
false;
       processStart.RedirectStandardOutput =
true;
       Process process = Process.Start(processStart);
       process.WaitForExit();
       Console.WriteLine(process.StandardOutput.ReadToEnd());
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s