Thursday, April 12, 2012

Start/Stop Visual Studio Team Build Service using API

Here is full code snippet to start/stop Visual Studio Team Build Service.

private const string TFSBuildService = "TFSBuildServiceHost";
private ServiceController TFSController;

public TeamBuildServiceController()
{
// Check if the Visual Studio Team Build service exists on the machine. If not then raise an error.
bool srvcExists = false;
foreach (ServiceController srvcOnMachine in ServiceController.GetServices())
{

if (string.Compare(srvcOnMachine.ServiceName, TFSBuildService, StringComparison.OrdinalIgnoreCase) == 0)
{
srvcExists = true;
break;
}
}


this.TFSController = new ServiceController {ServiceName = TFSBuildService};
}

public void StopService()
{
if(this.TFSController == null)
{
return;
}

// Stop the service if its running
if (this.TFSController.CanStop)
{
this.TFSController.Stop();
int timecounter = 0;

while (this.TFSController.Status != ServiceControllerStatus.Stopped)
{
if (timecounter > 60)
{
break;
}

timecounter++;
Thread.Sleep(1000);
this.TFSController.Refresh();
}
}

if(this.TFSController.Status != ServiceControllerStatus.Stopped)
{
Thread thread = new Thread(ShowMessageToRestart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start(
"The Visual Studio Team Foundation Build service cannot be stopped. Changes to the environment variable will not reflect on the builds till the service has been restarted. \r\n\r\nPlease restart the service after the installation completes.");
thread.Join();
}
}

public void StartService()
{
if (this.TFSController == null)
{
return;
}

// Start TFS build service
this.TFSController.Start();
int timecounter = 0;

while (this.TFSController.Status != ServiceControllerStatus.Running)
{
if (timecounter > 60)
{
break;
}

timecounter++;
Thread.Sleep(1000);
this.TFSController.Refresh();
}

if (this.TFSController.Status != ServiceControllerStatus.Running)
{
Thread thread = new Thread(ShowMessageToRestart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start(
"The Visual Studio Team Foundation Build service cannot be started. Team build will not be executed on this machine until the service is not started. Please try to start the service manually.");
thread.Join();
}
}




No comments:

Post a Comment