How can I remotely start/stop a service using MSBuild? - msbuild

I'd like to remotely start or stop a windows service on another machine using MSBuild. To accomplish this, I wrote this script:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="C:\Program Files (x86)\MSBuild\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<Target Name="MyTarget">
<ServiceController MachineName="Box2" ServiceName="MyService" Action="Stop" />
</Target>
</Project>
When I run that on a machine that can see Box2, I get this:
Project
"C:\Scripts\Test.xml" on node 1 (default
targets).
C:\Scripts\Test.xml(4,5): error : Couldn't
find the 'MyService'
service on 'Box2' Done Building
Project
"C:\Scripts\Test.xml" (default targets) --
FAILED.
I know that I have the service name correct (I copied and pasted it from the actual service list), and I'm pretty sure that it can see Box2 because if I change it to a machine name that doesn't exist (e.g. Box2asdf), it takes about 10 seconds to come back (with the exact same error, mind you), as opposed to the nearly immediate response that I get when I provide the correct machine name.
How might I debug this issue?

You might try this instead...
You can use the command line program sc and execute that...
ie
SC \ServerName stop ServiceName
http://support.microsoft.com/kb/166819
For more information on how to execute a command from msbuild check this out..
execute a command with parameters using msbuild

The community tasks should work. Just use Sc query to check that the service does work. as for using msbuild its still using msbuild if you wrap sc in an exec?
At least you dont have a dependency on a third party dll in your build process.

ServiceController Target internally uses ServiceController Class. But it doesn't return the reason why it couldn't find the service. If you are shure that both computer and service names are correct, the next thing I can suggest to analyze is access violation problems.
And #jsobo's answer can be very useful to diagnose the actual reason because it can show native errors without .Net exception wrappers around them:
sc.exe \Box2 stop MyService

Related

Can not publish since moving to VS 2019

I have recently uninstalled VS 2017 and installed VS 2019.
When I publish my website via Web Deploy, if fails with 2 error messages
Failed to load publish certificate dialog due to error of Object reference not set to an instance of an object. MyWebsite.Ui
Web deployment task failed. (Connected to the remote computer ("example.com") using the specified process ("Web Management Service"), but could not verify the server’s certificate. If you trust the server, connect again and allow untrusted certificates. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_CERTIFICATE_VALIDATION_FAILED.)
I'm totally clueless on how I can solve this...
Edit
As per the comments, there is a question which is the same, but that question is about Azure. I'm not connecting to anything Azure related. I'm not saying that this makes my questions unique, more that I don't have the knowledge to understand if the cause/solution is the same. Deploying to Azure from Visual Studio fails when connecting
If you trust the server, then you can simply ignore the warning/error by editing the publish file directly
https://stackoverflow.com/a/33662970/3252861
Open the publish profile file (.pubxml) inside /Properties/PublishProfiles in a text editor
Inside the PropertyGroup element, set AllowUntrustedCertificate to True (AllowUntrustedCertificate> True /AllowUntrustedCertificate>) or add it if it doesn't exist
Set UsePowerShell to False (False).
I didn't do the 3rd point, so I guess I either have previously or didn't need it
Now we can follow the advice on https://developercommunity.visualstudio.com/content/problem/484286/publish-fails-to-iis-using-msdeploy-webdeploy.html and actually add the following 2 entries
<UseMSDeployExe>True</UseMSDeployExe>
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
It should be pointed out that some have reported you only need to use one of those two:
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
So, the start of the pubxml XML file now looks like
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<UseMSDeployExe>True</UseMSDeployExe>
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>True</ExcludeApp_Data>
<MSDeployServiceURL>domain</MSDeployServiceURL>
<DeployIisAppPath>name</DeployIisAppPath>
<RemoteSitePhysicalPath />
…
…
In your /Properties/PublishProfiles/xxxxxx.Settings.pubxml file, add the following two lines
<UseMSDeployExe>True</UseMSDeployExe>
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
I know this is old, but I did find a different solution that worked for me (after trying to create/upload certificates; reset publishing profiles, etc.)
If you have the nuget package MSBuild.Microsoft.VisualStudio.Web.targets installed in your project, it's old and that's what breaks it. Remove that package and your publish will work. No need to add the AllowUntrusted flat in your pubxml as long as your server IS trusted. (*ie Azure.)
I´m using VS 2019
Add the next lines into PropertyGroup node:
<UseMSDeployExe>True</UseMSDeployExe>
<AllowUntrustedCertificate>true</AllowUntrustedCertificate>
I am from the product team and I can confirm that this is the only property that needs to be set if the server certificate is untrusted.
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
Verify your code if there is any errors /C#/ Razor syntax, sometimes errors will not show in errors window.
Same problem here. I attempted to delete the obj file folder figuring that was the problem. And it was, I had two pdf files in them that wouldn't delete being they required Admin privilege's to delete. I used the command prompt utility to go in and delete them and then did a rebuild and published with no issues.

The mystery of stuck inactive msbuild.exe processes, locked Stylecop.dll, Nuget AccessViolationException and CI builds clashing with each other

Observations:
On our Jenkins build server, we were seeing lots of msbuild.exe processes (~100) hanging around after job completion with around 20mb memory usage and 0% CPU activity.
Builds using different versions of stylecop were intermittently failing:
workspace\packages\StyleCop.MSBuild.4.7.41.0\tools\StyleCop.targets(109,7):
error MSB4131: The "ViolationCount" parameter is not supported by the "StyleCopTask" task.
Verify the parameter exists on the task, and it is a gettable public instance property.
Nuget.exe was intermittently exiting with the following access violation error (0x0000005):
.\workspace\.nuget\nuget install .\workspace\packages.config -o .\workspace\packages"
exited with code -1073741819.
MsBuild was launched in the following way via a Jenkins Matrix job, with 'BuildInParallel' enabled:
`msbuild /t:%Targets% /m
/p:Client=%Client%;LOCAL_BUILD=%LOCAL_BUILD%;BUILD_NUMBER=%BUILD_NUMBER%;
JOB_NAME=%JOB_NAME%;Env=%Env%;Configuration=%Configuration%;Platform=%Platform%;
Clean=%Clean%; %~dp0\_Jenkins\Build.proj`
After a lot of digging around and trying various things to no effect, I eventually ended up creating a new minimal solution which reproduced the issue with very little else going on. The issue turned out to be caused by msbuild's multi-core parallelisation - the 'm' parameter.
The 'm' parameter tells msbuild to spawn "nodes", these will remain alive after the build has ended, and are then re-used by new builds!
The StyleCop 'ViolationCount' error was caused by a given build re-using an old version of the stylecop.dll from another build's workspace, where ViolationCount was not supported. This was odd, because the CI workspace only contained the new version. It seems that once the StyleCop.dll was loaded into a given MsBuild node, it would remain loaded for the next build. I can only assume this is because StyleCop loads some sort of singleton into the nodes processs? This also explains the file-locking between builds.
The nuget access violation crash has now gone (with no other changes), so is evidently related to the above node re-use issue.
As the 'm' parameter defaults to the number of cores - we were seeing 24 msbuild instances created on our build server for a given job.
The following posts were helpful:
msbuild.exe staying open, locking files
http://www.hanselman.com/blog/FasterBuildsWithMSBuildUsingParallelBuildsAndMulticoreCPUs.aspx
http://stylecop.codeplex.com/discussions/394606
https://github.com/Glimpse/Glimpse/issues/115
http://msdn.microsoft.com/en-us/library/vstudio/ms164311.aspx
The fix:
Add the line set MSBUILDDISABLENODEREUSE=1 to the batch file which launches msbuild
Launch msbuild with /m:4 /nr:false
The 'nr' paremeter tells msbuild to not use "Node Reuse" - so msbuild instances are closed after the build is completed and no longer clash with each other - resulting in the above errors.
The 'm' parameter is set to 4 to stop too many nodes spawning per-job
I had the same issue. One old reference I found was in csproj files
<PropertyGroup>
<StyleCopMSBuildTargetsFile>..\packages\StyleCop.MSBuild.4.7.48.0\tools\StyleCop.targets</StyleCopMSBuildTargetsFile>
Also, I deleted the entire "Packages" folder that's located in the same folder as sln file after I closed the visual studio. It triggered VS to rebuild the folder and let go of the cache of the old version of stylecop
I've had the same issue for a while, builds were taking over 6 minutes to finish after some digging I found our it's node reuse fault so adding /m:4 /nr:false fixing my issue immediately

help building castle dynamic proxy

So I pulled the source from https://svn.castleproject.org/svn/castle/DynamicProxy/trunk/
Open it up in vs.net 2008
problems:
vs.net can't open the assembly.cs
assembly signing failed
What am I doing, rather NOT doing?
Update
So I downloaded nant, setup the .bat file in my PATH so it works in cmd prompt.
I ran:
nant default.build
Getting this error:
build failed, \buildscripts\common-project.xml (48,3)
invalid element . Unknown task or datatype.
How exactly do I build the dynamicProxy project now?
update
This is what I did, see screenshot:
oh and my nant is:
#echo off
"E:\dev\tools\nant-bin\nant-0.86-nightly-2009-05-05\bin\Nant.exe" %*
http://img697.imageshack.us/img697/5623/castlebuildscreenshot.png http://img697.imageshack.us/img697/5623/castlebuildscreenshot.png
You can read the FM (how to build.txt). :)
You need to run the build script first using NAnt (http://nant.sf.net). This will generate the assembly.cs file. Take a look at the .build files in the tree to see what they are doing.
As for the assembly signing failing, check the project settings to get rid of references to CastleKey.snk. It should sign it using DynProxy.snk (in theory).
UPDATE:
The issue with NUnit is now fixed. Do a clean check out. I really have no idea why you're getting that error. Which version of NAnt are you using? Make sure you have the latest (earlier do not have support for .NET 3.5)
You should be able to just pull the source from the trunk, and build with nant (I just did that and it worked). Ok, I lied, looks like the reference to NUnit is wrong, so the unit test project will not build correctly:
BUILD FAILED - 0 non-fatal error(s), 1 warning(s)
D:\OLD\DynamicProxy\buildscripts\common-project.xml(295,5):
'nunit-console.exe' failed to start.
The system cannot find the file specified
Total time: 1.2 seconds.
BUILD FAILED
Nested build failed. Refer to build
log for exact reason.
Total time: 3.4 seconds.
However the important stuff (assemblyinfo generation) will succeed and you should be able to just open Castle.DynamicProxy2-vs2008.sln, fix the reference to the NUnit assembly hit F5 and build the code with no issues.
I just did it on a clean check out, and it worked.
Generally if you're planning to do modifications in DP codebase, it is advised to go to the Castle user group first, and discuss it there.

nant vs. msbuild: stopping a service

I'm trying to decide which side I'm on in the MsBuild vs. Nant war. I'm starting with: stop a service, deploy some files, restart the service. Just from looking at these two links, that is much easier to do in Nant.
MSBuild: Example of using Service Exists MSBuild task in Microsoft.Sdc.Tasks?
<target name="service_exists">
<script language="C#">
<references>
<include name="System.ServiceProcess.dll" />
</references>
<code><![CDATA[
public static void ScriptMain(Project project) {
String serviceName = project.Properties["service.name"];
project.Properties["service.exists"] = "false";
project.Properties["service.running"] = "false";
System.ServiceProcess.ServiceController[] scServices;
scServices = System.ServiceProcess.ServiceController.GetServices();
foreach (System.ServiceProcess.ServiceController scTemp in scServices)
{
etc...
Nant: http://ryepup.unwashedmeme.com/blog/2007/01/04/restart-a-windows-service-remotely/
<!-- Send the stop request -->
<exec program="sc.exe">
<arg line="\\server stop shibd_Default"/>
</exec>
<!-- Sleep a little bit, to give the service a chance to stop -->
<sleep seconds="5"/>
<!-- Send the start request -->
<exec program="sc.exe">
<arg line="\\server start shibd_Default"/>
</exec>
I wonder if the SO community agrees with me. Is it much easier to get basic things like this done in Nant? Sure looks that way. C# code in a CDATA block? WTF?
Our current build process is a) lots of bat files b) lots of cursing. I'd really like to find a good replacement, but that MsBuild stuff looks like a world of pain to my eyes. I'm thinking the way to go is to build scripts in Nant, then use MsBuild to do any .NET builds that need to be done.
One important question: which one is better at catching errors in the script before the script is run? I was thinking of rolling my own here and that was very important part of it: line up all your data and make sure that it makes sense before attempting to run.
In msbuild you could also use the ServiceController task that is packaged in the msbuild community tasks.
You can execute sc.exe using MSBuild every bit as easily ...
<Exec Command="sc.exe \\server stop shibd_Default" />
By default this will "fail" if the exit code (of sc.exe) is non-zero, but that can be customized.
With Nant, there are 2 other ways to stop a service, and one is able to track an error.
First one (using Net Stop):
<exec program="net" failonerror="false"><arg value="stop"/><arg value="${serviceName}"/></exec>
Second one (much cleaner):
<servicecontroller action="Stop" service="${serviceName}" if="${service::is-installed(serviceName,'.') and service::is-running(serviceName,'.')}" />
Note that the second line verifies that the service already exists and is running, which allows to track any weird error.
In addition to #nulpptr's answer for MSBuild, if you don't have the option of using the community tasks, you might have to resort to a hack to wait for your service to stop before moving on. If you have the resource kit you can use the EXEC task with the sleep command.
No resource kit? Use the ping trick...
However, if you don't have the resource kit, you can use the ping trick to force a delay. For instance, the following will stop your service using the sc command, and then pause for about 5 seconds:
<Exec Command="sc.exe \\server stop shibd_Default" ContinueOnError="true" />
<Exec Command="ping 127.0.0.1 -n 5 > nul" ContinueOnError="true" />

Process timeout without showing any error in test execution using cc.net

nunit tests fails when run through cc.net saying process timeout. Process has been killed
All works fine when through nUNit or VS.
Also cc.net will then show the results of previous build even if the build is a clean one.
Any help plz.
The default timeout is 600 seconds. If your tests start to exceed that the build will fail with no indication. You may need to up the timeouts for your cc.net nunit task
If you are seeing the results from a previous build, it is probably because you are not deleting the results from your previous build.
For example, my NUnit test results are written to files with the name {foo}-results.xml:
<publishers>
<merge>
<files>
<file>bin\debug\*-results.xml</file>
</files>
</merge>
</publishers>
In my tasks, I have a step in my build file that deletes the entire "bin\debug" directory so that my results are always the current ones.
One possibility is that you have a permission issue. CruiseControl is perhaps running under a service account and has different permissions than your user account (which I'm assuming you use to manually run the tests.) Try logging into the machine as the service account, then see if you can run the unit tests through VS or NUnit.
I've seen this happen if a test has an assertion, e.g. Debug.Assert(something here). When this happens to me in CC.Net, the CC.Net build pops up a message box for the assertion. Since no one closes out the message box on the build server, the NUnit test times out.