2

I am trying to create a simple web form which will give me a service restart button onscreen.

Upon clicking the button, I am creating an SMO object to talk to a SQL Server database and trying to stop and start the MSSQLSERVER service. All goes well until the Stop() method is called, at which point an exception is thrown stating:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

The code under the button is as follows:

// connect the to server
ManagedComputer computer = 
    new ManagedComputer("172.16.150.52",@"Administrator","secret");

// return if there is a problem
if (computer.Services["MSSQLSERVER"] == null)
{
    PageErrorMessage = "Bad or missing service \"MSSQLSERVER\"";
    return;
}

// get the SQL Server Service
Service sqlServer = computer.Services["MSSQLSERVER"];

// is the server running?
if (sqlServer.ServiceState == ServiceState.Running)
    sqlServer.Stop();

// wait for it to stop completely
int timeout = 0;
while (sqlServer.ServiceState != ServiceState.Stopped || timeout <= 60)
{
    Thread.Sleep(1000);
    sqlServer.Refresh();
    timeout++;
}

if (timeout > 60)
{
    PageErrorMessage = "Stop operation has timed out after 60secs";
    return;
}

// start it again!
sqlServer.Start();

The IP address, username & password are 100% correct. Does anyone know why this would throw an AccessDenied exception?

Johan
  • 74,508
  • 24
  • 191
  • 319
justacodemonkey
  • 620
  • 1
  • 8
  • 20
  • This is an OS error, not a WMI or Smo error so you will probably get a better response on ServerFault. See here: http://technet.microsoft.com/en-us/library/ee692772.aspx#EEAA – Pondlife Dec 21 '11 at 13:35
  • I'm not sure it's OS as such. I'm guessing the OP hasn't implemented code to handle UAC. –  Dec 24 '11 at 11:47

1 Answers1

1

It sounds like you're missing the UAC. Often, to do system-wide tasks such as rebooting, shutting down (and probably also starting/stopping services), you have to get the elevated priviliges, which includes obtaining a token, etc.

Take a look at this article - http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx - it has helped me on a few occasions.

But http://www.codeproject.com/KB/vista-security/ElevatedPrivilegesDemand.aspx might also be helpful.

I have only ever done this client side myself - I don't know how it works when running on a server. For that, you might want to take a look at: http://blogs.msdn.com/b/lightswitch/archive/2011/04/07/how-to-elevate-permissions-in-server-code-ravi-eda.aspx

And if it's not code, but configuration, take a look at this: http://www.lansweeper.com/kb/WMI-Access-is-denied.aspx