15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Monitoring <strong>and</strong> Controlling Windows services ❘ 691<br />

}<br />

{<br />

MessageBox.Show(ex.Message, "Timout Service Controller",<br />

MessageBoxButton.OK, MessageBoxImage.Error);<br />

}<br />

catch (InvalidOperationException ex)<br />

{<br />

MessageBox.Show(String.Format("{0} {1}", ex.Message,<br />

ex.InnerException != null ex.InnerException.Message :<br />

String.Empty),<br />

MessageBoxButton.OK, MessageBoxImage.Error);<br />

}<br />

finally<br />

{<br />

this.Cursor = oldCursor;<br />

}<br />

protected void OnExit(object sender, RoutedEventArgs e)<br />

{<br />

Application.Current.Shutdown();<br />

}<br />

protected void OnRefresh_Click(object sender, RoutedEventArgs e)<br />

{<br />

RefreshServiceList();<br />

}<br />

code snippet ServiceControl/ServiceControlWindow.xaml.cs<br />

Because the action of controlling the services can take some time, the cursor is switched to the wait<br />

cursor in the first statement. Then a ServiceController method is called depending on the pressed<br />

button. With the WaitForStatus() method, you are waiting to check that the service changes the status<br />

to the requested value, but you only wait 10 seconds maximum. After this time, the information in the<br />

ListBox is refreshed, <strong>and</strong> the same service as before is selected. The new status of this service is then<br />

displayed.<br />

Because the application requires administrative privileges, as most services require that for starting <strong>and</strong><br />

stopping, an application manifest with the requestedExecutionLevel set to requireAdministrator is<br />

added to the project:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Figure 25-14 shows the completed, running application.<br />

code snippet ServiceControl/app.manifest<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!