220

Visual Studio 2010 has a Publish command that allows you to publish your Web Application Project to a file system location. I'd like to do this on my TeamCity build server, so I need to do it with the solution runner or msbuild. I tried using the Publish target, but I think that might be for ClickOnce:

msbuild Project.csproj /t:Publish /p:Configuration=Deploy

I basically want to do exactly what a web deployment project does, but without the add-in. I need it to compile the WAP, remove any files unnecessary for execution, perform any web.config transformations, and copy the output to a specified location.

My Solution, based on Jeff Siver's answer

<Target Name="Deploy">
    <MSBuild Projects="$(SolutionFile)" 
             Properties="Configuration=$(Configuration);DeployOnBuild=true;DeployTarget=Package" 
             ContinueOnError="false" />
    <Exec Command="&quot;$(ProjectPath)\obj\$(Configuration)\Package\$(ProjectName).deploy.cmd&quot; /y /m:$(DeployServer) -enableRule:DoNotDeleteRule" 
          ContinueOnError="false" />
</Target>
Sayed Ibrahim Hashimi
  • 42,483
  • 14
  • 139
  • 172
jrummell
  • 41,300
  • 17
  • 110
  • 165
  • possible duplicate: http://stackoverflow.com/questions/1162253/can-teamcity-publish-a-web-project-using-the-sln2008-build-runner – Steven Evers Jun 22 '10 at 22:06
  • @SnOrfus I'm currently using Web Deployment Projects in VS 2008 (as I mentioned in my answer to that question) but I'd like to try automating the Publish feature of VS 2010 instead. – jrummell Jun 22 '10 at 23:05
  • This question looks helpful http://stackoverflow.com/questions/1983575/copywebapplication-with-web-config-transformations/2953376#2953376 – jrummell Jun 23 '10 at 18:30
  • 2
    Just one little amendment to your script: you're using $(ProjectPath) for the deploy script but you really want is $(ProjectDir) otherwise you end up with .csproj\obj – Troy Hunt Oct 28 '10 at 02:55
  • @Troy Hunt - ProjectPath is actually a variable in my script that holds the relative path to the project folder, but ProjectDir should also work. – jrummell Oct 28 '10 at 12:42
  • FYI Web Deployment Projectd are just MSBuild files, so to want the same behavior and not use them just means you'll be writing the MSBuild yourself. If you don't want to see in in VS then after you add it just remove it. WDP supports ASP.NET Compile/Merge which I see no mention of in any answer here. – Sayed Ibrahim Hashimi Oct 30 '10 at 01:40
  • 2
    Starting with VS2012, this is much easier: http://stackoverflow.com/a/13947667/270348 – RobSiklos Aug 12 '14 at 15:04

11 Answers11

137

I got it mostly working without a custom msbuild script. Here are the relevant TeamCity build configuration settings:

Artifact paths: %system.teamcity.build.workingDir%\MyProject\obj\Debug\Package\PackageTmp 
Type of runner: MSBuild (Runner for MSBuild files) 
Build file path: MyProject\MyProject.csproj 
Working directory: same as checkout directory 
MSBuild version: Microsoft .NET Framework 4.0 
MSBuild ToolsVersion: 4.0 
Run platform: x86 
Targets: Package 
Command line parameters to MSBuild.exe: /p:Configuration=Debug

This will compile, package (with web.config transformation), and save the output as artifacts. The only thing missing is copying the output to a specified location, but that could be done either in another TeamCity build configuration with an artifact dependency or with an msbuild script.

Update

Here is an msbuild script that will compile, package (with web.config transformation), and copy the output to my staging server

<?xml version="1.0" encoding="utf-8" ?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
        <SolutionName>MySolution</SolutionName>
        <SolutionFile>$(SolutionName).sln</SolutionFile>
        <ProjectName>MyProject</ProjectName>
        <ProjectFile>$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    </PropertyGroup>

    <Target Name="Build" DependsOnTargets="BuildPackage;CopyOutput" />

    <Target Name="BuildPackage">
        <MSBuild Projects="$(SolutionFile)" ContinueOnError="false" Targets="Rebuild" Properties="Configuration=$(Configuration)" />
        <MSBuild Projects="$(ProjectFile)" ContinueOnError="false" Targets="Package" Properties="Configuration=$(Configuration)" />
    </Target>

    <Target Name="CopyOutput">
        <ItemGroup>
            <PackagedFiles Include="$(ProjectName)\obj\$(Configuration)\Package\PackageTmp\**\*.*"/>
        </ItemGroup>
        <Copy SourceFiles="@(PackagedFiles)" DestinationFiles="@(PackagedFiles->'\\build02\wwwroot\$(ProjectName)\$(Configuration)\%(RecursiveDir)%(Filename)%(Extension)')"/>
    </Target>
</Project>

You can also remove the SolutionName and ProjectName properties from the PropertyGroup tag and pass them to msbuild.

msbuild build.xml /p:Configuration=Deploy;SolutionName=MySolution;ProjectName=MyProject

Update 2

Since this question still gets a good deal of traffic, I thought it was worth updating my answer with my current script that uses Web Deploy (also known as MSDeploy).

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
    <ProjectFile Condition=" '$(ProjectFile)' == '' ">$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    <DeployServiceUrl Condition=" '$(DeployServiceUrl)' == '' ">http://staging-server/MSDeployAgentService</DeployServiceUrl>
  </PropertyGroup>

  <Target Name="VerifyProperties">
    <!-- Verify that we have values for all required properties -->
    <Error Condition=" '$(ProjectName)' == '' " Text="ProjectName is required." />
  </Target>

  <Target Name="Build" DependsOnTargets="VerifyProperties">
    <!-- Deploy using windows authentication -->
    <MSBuild Projects="$(ProjectFile)"
             Properties="Configuration=$(Configuration);
                             MvcBuildViews=False;
                             DeployOnBuild=true;
                             DeployTarget=MSDeployPublish;
                             CreatePackageOnPublish=True;
                             AllowUntrustedCertificate=True;
                             MSDeployPublishMethod=RemoteAgent;
                             MsDeployServiceUrl=$(DeployServiceUrl);
                             SkipExtraFilesOnServer=True;
                             UserName=;
                             Password=;"
             ContinueOnError="false" />
  </Target>
</Project>

In TeamCity, I have parameters named env.Configuration, env.ProjectName and env.DeployServiceUrl. The MSBuild runner has the build file path and the parameters are passed automagically (you don't have to specify them in Command line parameters).

You can also run it from the command line:

msbuild build.xml /p:Configuration=Staging;ProjectName=MyProject;DeployServiceUrl=http://staging-server/MSDeployAgentService
jrummell
  • 41,300
  • 17
  • 110
  • 165
  • 2
    thanks - this also works well directly from powershell (apologies for the formatting - no carriage returns in comments): &msbuild "$solution" /p:"Configuration=$configuration" ; &msbuild "$project" /t:Package /p:"Configuration=$configuration;_PackageTempDir=$outputfolder" – zcrar70 Feb 02 '11 at 12:25
  • I tried the example from your first Update and it seems that the `Package` target depends on WebDeploy, too: `error : Package/Publish task Microsoft.Web.Publishing.Tasks.IsCleanMSDeployPackageNeeded failed to load Web Deploy assemblies. Microsoft Web Deploy is not correctly installed on this machine.` (Mentioning it since you write that your second update uses WebDeploy, which might imply the first would not use WebDeploy yet.) – chiccodoro May 08 '14 at 14:35
  • @jrummell: I want to deploy my Visual Studio web project to a remote Windows server from TeamCity. What should I do. I am a beginner and have no idea about what to to do – Nevin Raj Victor May 27 '15 at 11:40
  • 1
    I'm able to get this to work on TeamCity with Web Application Projects, but I also have a legacy bound Website PROJECT that I also need to publish (as a package) then need to use MSDeploy. If I publish within VS2013 I get a deployment package, but MSBuild from the cmd line does not create one. Any thoughts? – KnowHowSolutions Jun 05 '15 at 20:57
  • @KnowHowSolutions I'm not sure that this method will work with website projects. I've only tried it with web application projects. – jrummell Jun 08 '15 at 13:00
  • Yes, I'm not sure either feels like it should. It works in Visual Studio and it does create a publish profile, it's just that msbuild itself doesn't seem to use it with the these switches. Thanks. – KnowHowSolutions Jun 08 '15 at 16:17
  • How did you configure your visual studio solution to have a target:package section in the project build files? – Chris Jul 16 '15 at 15:45
  • @KnowHowSolutions recent versions of Visual Studio will now create publish profiles for Website projects. Since Website project doesn't have a project file a Websitepublish.proj (not 100% on the name here) which can be used in place of the .csproj file in this case. – Sayed Ibrahim Hashimi Aug 14 '15 at 08:45
  • A couple more interesting properties to consider when publishing: FilesToIncludeForPublish=AllFilesInProjectFolder;ExcludeGeneratedDebugSymbol=true; – XDS May 17 '18 at 09:57
  • 1
    I don't see any mention of the publish profile in this. Publish profile should be specified so the correct web.config transform is applied. Update: Nevermind... that feature was introduced 2 years after this post. This one still probably works. Later post in this thread shows how to publish with a publish profile from command line. – Triynko Jan 07 '19 at 22:43
  • @Triynko that's correct. The preferred way now is with a publish profile as shown in Chris' answer. – jrummell Jan 08 '19 at 15:52
85

Using the deployment profiles introduced in VS 2012, you can publish with the following command line:

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0

For more information on the parameters see this.

The values for the /p:VisualStudioVersion parameter depend on your version of Visual Studio. Wikipedia has a table of Visual Studio releases and their versions.

Chris
  • 6,279
  • 3
  • 48
  • 71
  • 6
    Using VS2012 .NET 3.5, this did not work for deploying to the file system. It simply builds and does no deployment. – Jay Sullivan Feb 11 '14 at 21:20
  • 2
    your /p:VisualStudioVersion=11.0 saved my life. I use /p:VisualStudioVersion=12.0 for vs2013 and its works fine. – Seyed Morteza Mousavi Aug 11 '14 at 19:22
  • What will be the value for `/p:VisualStudioVersion=?` for VS 2017? – Nishant Jun 03 '20 at 07:35
  • created build script `msbuild test.sln /p:DeployOnBuild=True /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl=.\build_output1\pub /p:PublishProfile=FolderProfile /p:VisualStudioVersion=11.0 /p:outdir=.\build_output1` ......But still getting only DLLs not all the files like in publish folder :(` – Nishant Jun 03 '20 at 10:20
  • 1
    @Nishant For VS 2017, use `/p:VisualStudioVersion=15`. I am not sure if this is related to your file copying issue. – Chris Jun 04 '20 at 09:58
39

I came up with such solution, works great for me:

msbuild /t:ResolveReferences;_WPPCopyWebApplication /p:BuildingProject=true;OutDir=C:\Temp\build\ Test.csproj

The secret sauce is _WPPCopyWebApplication target.

Community
  • 1
  • 1
Alexander Beletsky
  • 18,109
  • 9
  • 57
  • 84
  • 1
    What is _WPPCopyWebApplication and how can I use it MSBbuild xml config file/ – Johnny_D Sep 11 '13 at 12:20
  • 4
    Using VS2012 .NET 3.5, I got the error `error MSB4057: The target "_WPPCopyWebApplication" does not exist in the project`. Taking out that part led to a deployment without deploying any views – Jay Sullivan Feb 11 '14 at 21:19
  • You might need to call it with a different /p:VisualStudioVersion=12.0 because build uses the targets from c:\program files (x86)\msbuild\microsoft\visualstudio\VERSION\Webapplication\Microsoft.WebApplication.targets so maybe its using an older version that doesnt have the correct target. – Jim Wolff Oct 09 '14 at 07:00
  • @FRoZeN I tried using MSBuild as `MSBuild.exe C:\BuildAgent\work\4c7b8ac8bc7d723e\WebService.sln /p:Configuration=Release /p:OutputPath=bin /p:DeployOnBuild=True /p:DeployTarget=MSDeployPublish /p:MsDeployServiceUrl=https://204.158.674.5/msdeploy.axd /p:username=Admin /p:password=Password#321 /p:AllowUntrustedCertificate=True /p:DeployIisAppPath=Default WebSite/New /p:MSDeployPublishMethod=WMSVC`. It gives me an error `MSBUILD : error MSB1008: Only one project can be specified. Switch: WebSite/New`. Is there a solution for this? – Nevin Raj Victor May 27 '15 at 14:56
  • 1
    @NevinRajVictor that error is likely because you have a space in the DeployIisAppPath value. You will need to put the value in quotes. e.g. /p:DeployIisAppPath="Default Website/New" – shiitake Dec 28 '15 at 18:00
28

I don't know TeamCity so I hope this can work for you.

The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.

With WebDeploy, you run the command line

msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp

This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.

Jeff Siver
  • 7,201
  • 27
  • 32
  • That looks promising. However, it looks like the Management Service is only available on Server 2008. My staging server (where I want to automate deployment) is running Windows 7 Pro. – jrummell Jun 23 '10 at 14:00
  • 2
    There are two pieces to the product. The pieces that integrate right into IIS require Server 2008. The command line component does not have that requirement; I have it running on a Server 2003 box I use for deployments. – Jeff Siver Jun 23 '10 at 20:34
  • I've done some reading on MSDeploy. I got it installed and working on my staging server, thanks! Can I run MSDeploy from an MSBuild script? – jrummell Jun 24 '10 at 19:15
  • It should run fine as an EXEC task in your build script. – Jeff Siver Jun 25 '10 at 06:38
  • 1
    does the same thing as which configuration of the VS Publish command? Which publish method - file system or other? Does it use the MyProject.Publish.xml file to determine which files to copy? – Anthony Sep 22 '11 at 10:23
  • 1
    I just gave it a shot but it did not do the same as VS Publish. It did the same as XCopy including all source files. – Louis Somers Mar 04 '15 at 16:09
13

With VisualStudio 2012 there is a way to handle subj without publish profiles. You can pass output folder using parameters. It works both with absolute and relative path in 'publishUrl' parameter. You can use VS100COMNTOOLS, however you need to override VisualStudioVersion to use target 'WebPublish' from %ProgramFiles%\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets. With VisualStudioVersion 10.0 this script will succeed with no outputs :)

Update: I've managed to use this method on a build server with just Windows SDK 7.1 installed (no Visual Studio 2010 and 2012 on a machine). But I had to follow these steps to make it work:

  1. Make Windows SDK 7.1 current on a machine using Simmo answer (https://stackoverflow.com/a/2907056/2164198)
  2. Setting Registry Key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VS7\10.0 to "C:\Program Files\Microsoft Visual Studio 10.0\" (use your path as appropriate)
  3. Copying folder %ProgramFiles%\MSBuild\Microsoft\VisualStudio\v11.0 from my developer machine to build server

Script:

set WORK_DIR=%~dp0
pushd %WORK_DIR%
set OUTPUTS=%WORK_DIR%..\Outputs
set CONFIG=%~1
if "%CONFIG%"=="" set CONFIG=Release
set VSTOOLS="%VS100COMNTOOLS%"
if %VSTOOLS%=="" set "PATH=%PATH%;%WINDIR%\Microsoft.NET\Framework\v4.0.30319" && goto skipvsinit
call "%VSTOOLS:~1,-1%vsvars32.bat"
if errorlevel 1 goto end
:skipvsinit
msbuild.exe Project.csproj /t:WebPublish /p:Configuration=%CONFIG% /p:VisualStudioVersion=11.0 /p:WebPublishMethod=FileSystem /p:publishUrl=%OUTPUTS%\Project
if errorlevel 1 goto end
:end
popd
exit /b %ERRORLEVEL%
Community
  • 1
  • 1
Ivan Samygin
  • 3,265
  • 17
  • 26
12

found two different solutions which worked in slightly different way:

1. This solution is inspired by the answer from alexanderb [link]. Unfortunately it did not work for us - some dll's were not copied to the OutDir. We found out that replacing ResolveReferences with Build target solves the problem - now all necessary files are copied into the OutDir location.

msbuild /target:Build;_WPPCopyWebApplication  /p:Configuration=Release;OutDir=C:\Tmp\myApp\ MyApp.csproj
Disadvantage of this solution was the fact that OutDir contained not only files for publish.

2. The first solution works well but not as we expected. We wanted to have the publish functionality as it is in Visual Studio IDE - i.e. only the files which should be published will be copied into the Output directory. As it has been already mentioned first solution copies much more files into the OutDir - the website for publish is then stored in _PublishedWebsites/{ProjectName} subfolder. The following command solves this - only the files for publish will be copied to desired folder. So now you have directory which can be directly published - in comparison with the first solution you will save some space on hard drive.

msbuild /target:Build;PipelinePreDeployCopyAllFilesToOneFolder /p:Configuration=Release;_PackageTempDir=C:\Tmp\myApp\;AutoParameterizationWebConfigConnectionStrings=false MyApp.csproj
AutoParameterizationWebConfigConnectionStrings=false parameter will guarantee that connection strings will not be handled as special artifacts and will be correctly generated - for more information see link.
Community
  • 1
  • 1
Pavel Cermak
  • 1,006
  • 9
  • 13
  • Your option #2 helped me seamlessly get rid of the obsolete _CopyWebApplication. You rescued my Build-Server after upgrade to VS 2015. Great research. Appreciative. – it3xl Jan 09 '17 at 14:45
  • Your option #2 was perfect for my build script. – AnthonyVO Mar 24 '20 at 21:41
3

You must set your environments

  • < WebSite name>
  • < domain>

and reference my blog.(sorry post was Korean)

  • http://xyz37.blog.me/50124665657
  • http://blog.naver.com/PostSearchList.nhn?SearchText=webdeploy&blogId=xyz37&x=25&y=7

    @ECHO OFF
    :: http://stackoverflow.com/questions/5598668/valid-parameters-for-msdeploy-via-msbuild
    ::-DeployOnBuild -True
    :: -False
    :: 
    ::-DeployTarget -MsDeployPublish
    :: -Package
    :: 
    ::-Configuration -Name of a valid solution configuration
    :: 
    ::-CreatePackageOnPublish -True
    :: -False
    :: 
    ::-DeployIisAppPath -<Web Site Name>/<Folder>
    :: 
    ::-MsDeployServiceUrl -Location of MSDeploy installation you want to use
    :: 
    ::-MsDeployPublishMethod -WMSVC (Web Management Service)
    :: -RemoteAgent
    :: 
    ::-AllowUntrustedCertificate (used with self-signed SSL certificates) -True
    :: -False
    :: 
    ::-UserName
    ::-Password
    SETLOCAL
    
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v3.5" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v3.5"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v4.0.30319" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319"
    
    SET targetFile=<web site fullPath ie. .\trunk\WebServer\WebServer.csproj
    SET configuration=Release
    SET msDeployServiceUrl=https://<domain>:8172/MsDeploy.axd
    SET msDeploySite="<WebSite name>"
    SET userName="WebDeploy"
    SET password=%USERNAME%
    SET platform=AnyCPU
    SET msbuild=%FXPath%\MSBuild.exe /MaxCpuCount:%NUMBER_OF_PROCESSORS% /clp:ShowCommandLine
    
    %MSBuild% %targetFile% /p:configuration=%configuration%;Platform=%platform% /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=False /p:DeployIISAppPath=%msDeploySite% /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=%msDeployServiceUrl% /p:AllowUntrustedCertificate=True /p:UserName=%USERNAME% /p:Password=%password% /p:SkipExtraFilesOnServer=True /p:VisualStudioVersion=12.0
    
    IF NOT "%ERRORLEVEL%"=="0" PAUSE 
    ENDLOCAL
    
Kim Ki Won
  • 1,581
  • 1
  • 21
  • 18
1

This my batch file

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Projects\testPublish\testPublish.csproj  /p:DeployOnBuild=true /property:Configuration=Release
if exist "C:\PublishDirectory" rd /q /s "C:\PublishDirectory"
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v / -p C:\Projects\testPublish\obj\Release\Package\PackageTmp -c C:\PublishDirectory
cd C:\PublishDirectory\bin 
del *.xml
del *.pdb
  • 5
    It would be great if you could detail your answer. How exactly does your batch file solves the OP's issue? Thanks! – Luís Cruz Jun 08 '15 at 17:09
1

this is my working batch

publish-my-website.bat

SET MSBUILD_PATH="C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin"
SET PUBLISH_DIRECTORY="C:\MyWebsitePublished"
SET PROJECT="D:\Github\MyWebSite.csproj"


cd /d %MSBUILD_PATH%
MSBuild %PROJECT%  /p:DeployOnBuild=True /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl=%PUBLISH_DIRECTORY%

Note that I installed Visual Studio on server to be able to run MsBuild.exe because the MsBuild.exe in .Net Framework folders don't work.

Alper Ebicoglu
  • 6,488
  • 1
  • 34
  • 39
  • `msbuild test.sln /p:DeployOnBuild=True /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl=.\build_output1\pub /p:PublishProfile=FolderProfile /p:VisualStudioVersion=11.0 /p:outdir=.\build_output1` ......But still getting only DLLs not the files structure i want. Whats wrong with it? :( – Nishant Jun 03 '20 at 10:24
1

For generating the publish output provide one more parameter. msbuild example.sln /p:publishprofile=profilename /p:deployonbuild=true /p:configuration=debug/or any

1

You can Publish the Solution with desired path by below code, Here PublishInDFolder is the name that has the path where we need to publish(we need to create this in below pic)

You can create publish file like this

Add below 2 lines of code in batch file(.bat)

@echo OFF 
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsMSBuildCmd.bat"
MSBuild.exe  D:\\Solution\\DataLink.sln /p:DeployOnBuild=true /p:PublishProfile=PublishInDFolder
pause