title: How to Start/Stop a Windows Service from an ASP.NET app - Security issues
body: <p>Here's my Windows/.NET security stack:</p>
  
  <ul>
  <li>A Windows Service running as LocalSystem on a Windows Server 2003 box.</li>
  <li>A .NET 3.5 Website running on the same box, under "default" production server IIS settings (so probably as NETWORKSERVICE user?)</li>
  </ul>
  
  <p>On my default VS2008 DEV environment I have this one method, which gets called from the ASP.NET app, which works fine:</p>
  
  <pre><code>private static void StopStartReminderService() {
  
      ServiceController svcController = new ServiceController("eTimeSheetReminderService");
  
      if (svcController != null) {
          try {
              svcController.Stop();
              svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
              svcController.Start();
          } catch (Exception ex) {
              General.ErrorHandling.LogError(ex);
          }
      }
  }
  </code></pre>
  
  <p>When I run this on the production server, I get the following error from the ServiceController:</p>
  
  <blockquote>
    <p>Source: System.ServiceProcess ->
    System.ServiceProcess.ServiceController -> IntPtr
    GetServiceHandle(Int32) -> System.InvalidOperationException Message:
    Cannot open eTimeSheetReminderService service on computer '.'.</p>
  </blockquote>
  
  <p><strong>Why is this happening, and how do I fix it?</strong></p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>The answer is below, mostly in comments, but to clarify:</p>
  
  <ol>
  <li>The issue was Security related, and occurred because the NETWORKSERVICE account did not have sufficient rights to Start/Stop a service</li>
  <li>I created a Local User Account, and added it to the PowerUsers Group (this group has almost admin rights)</li>
  <li>I don't want my whole Web App to impersonate that user all the time, so I impersonate only in the method where I manipulate the service. I do this by using the following resources to help me do it in code:</li>
  </ol>
  
  <p><a href="http://support.microsoft.com/kb/306158" rel="noreferrer">MS KB article</a> and <a href="http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=287" rel="noreferrer">this, just to get a better understanding</a></p>
  
  <p><strong>NOTE:</strong> I don't impersonate via the web.config, I do it in code. See the MS KB Article above.</p>