ASP.NET Web Application (MVC) Deployment Automation and Subversion - asp.net

We are trying to automate the build process to our staging servers but have run into a snag, albeit fairly minor. We are using the Publish functionality built into VS2010, committing to Subversion, and then a 3rd party app (Beanstalk) automatically pulls the updated files and FTPs them to the Staging server.
The problem we've run into is that we only appear to have the following choices:
(Lesser of 2 evils) If we choose to use "Replace matching files with local copies", this works great, with one exception: this option does not delete any files that were deleted from the project. This will lead to junk and/or security issues for unkempt files from the days of old.
If we choose to use "Delete all existing files prior to publish", this deletes the entire folder structure, including the .SVN hidden folders that Subversion uses for Update tracking, etc. This seems like the best solution from an accuracy standpoint, but it really destroys the local SVN environment, which is the middle-man for this automation.
My question: Is there an easy work around for this, or a totally different deployment option we're overlooking (we do not want to publish directly to the server from VS, as we want to track who/what/when a deployment takes place)? The only thing I've come across is to delete the file contents manually prior to publishing, while leaving the folder structure intact, then deploying with "Replace matching files with local copies". Unfortunately, this brings on a whole new meaning of the word "automation".
Any ideas on how best to accomplish this?

You may want to consider using NAnt or something similar for tasks you wish to automate, like building and publishing to Subversion. This is most of my build file for a WebApplication Project. It might be different for MVC. If so, I'm sure you can use this as a starting point. I am by no means an NAnt expert so there may be some flaws, but this is definitely working for me.
I had to add a PublishToFileSystem target to each .csproj file I wanted to publish. The source for that can be found here.
Build file also available on Pastebin
<?xml version="1.0"?>
<project name="deploy" default="all">
<property name="nant.settings.currentframework" value="net-4.0" />
<!-- Any of these can be passed through the command line -->
<property name="sourceDirectory" value="${project::get-base-directory()}" />
<property name="publishDirectory" value="${sourceDirectory}\build" />
<property name="MSBuildPath" value="${framework::get-assembly-directory(framework::get-target-framework())}\msbuild.exe" />
<!-- The build configuration to use when publishing and transforming the web.config file. This is useful when you have multiple environments for which you create builds -->
<property name="buildConfiguration" value="Release" />
<!-- Set these as needed -->
<property name="svn.username" value="" />
<property name="svn.password" value="" />
<target name="SvnPrep">
<property name="svn.dir" value="${publishDirectory}\.svn" />
<property name="svn.update" value="true" readonly="false" />
<echo>env.svn.path = svn</echo>
<echo>svn.dir = ${svn.dir}</echo>
<mkdir dir="${publishDirectory}" unless="${directory::exists(publishDirectory)}" />
<!-- Check if there's a .svn dir already. If not: checkout, else: update. -->
<if test="${not directory::exists(svn.dir)}">
<exec program='svn.exe' workingdir="${publishDirectory}" verbose="true">
<arg line='co ${svn.builduri} --username ${svn.username} --password ${svn.password} --non-interactive ./' />
</exec>
<property name="svn.update" value="false" readonly="false" />
</if>
<if test="${svn.update}">
<exec program='svn.exe' workingdir="${publishDirectory}\" verbose="true">
<arg line='up --username ${svn.username} --password ${svn.password} --non-interactive --force ./' />
</exec>
</if>
<!-- Force any conflicts to be resolved with the most recent code -->
<exec program='svn.exe' workingdir="${publishDirectory}\" verbose="true">
<arg line='resolve --accept theirs-full -R ./' />
</exec>
</target>
<target name="DeleteFiles">
<!-- Delete only the files (retain directory structure) in the directory to which you are going to publish/build. NAnt excludes svn directories by default. -->
<delete includeemptydirs="false">
<fileset basedir="${publishDirectory}">
<include name="**/*.*" />
</fileset>
</delete>
</target>
<target name="Publish">
<!-- I know there's an MSBuild task, I don't know why I didn't use it, but this works. -->
<!-- Build and publish frontend -->
<exec program="${MSBuildPath}">
<arg line='"${sourceDirectory}\YourProject.csproj"' />
<arg value='"/p:Platform=AnyCPU;Configuration=${buildConfiguration};PublishDestination=${publishDirectory}"' />
<arg value="/target:PublishToFileSystem" />
</exec>
<!-- Transform the correct web.config and copy it to the build folder. PublishToFileSystem doesn't transform the web.config, unfortunately. -->
<exec program="${MSBuildPath}">
<arg line='"${sourceDirectory}\YourProject.csproj"' />
<arg value='"/p:Platform=AnyCPU;Configuration=${buildConfiguration};PublishDestination=${publishDirectory}"' />
<arg value="/target:TransformWebConfig" />
</exec>
<copy file="${sourceDirectory}\YourProject\obj\${buildConfiguration}\TransformWebConfig\transformed\Web.config" tofile="${publishDirectory}\YourProject\web.config" overwrite="true" />
</target>
<target name="SvnCommit">
<!-- add any new files -->
<exec program='svn.exe' workingdir="${publishDirectory}" verbose="true">
<arg line='add --force .' />
</exec>
<!-- delete any missing files, a modification of this http://stackoverflow.com/questions/1071857/how-do-i-svn-add-all-unversioned-files-to-svn -->
<!-- When there's nothing to delete it looks like this fails (to NAnt) but it is actually fine, that's why failonerror is false -->
<exec program='cmd.exe' workingdir="${publishDirectory}\" verbose="true" failonerror="false"
commandline='/C for /f "usebackq tokens=2*" %i in (`svn status ^| findstr /r "^\!"`) do svn del "%i %j"' >
</exec>
<exec program='svn.exe' workingdir="${publishDirectory}" verbose="true">
<arg line='commit -m "Automated commit from build runner"' />
</exec>
</target>
<target name="ShowProperties">
<script language="C#" prefix="util" >
<code>
<![CDATA[
public static void ScriptMain(Project project)
{
foreach (DictionaryEntry entry in project.Properties)
{
Console.WriteLine("{0}={1}", entry.Key, entry.Value);
}
}
]]>
</code>
</script>
</target>
<target name="all">
<call target="ShowProperties" />
<call target="SvnPrep" />
<call target="DeleteFiles" />
<call target="Publish" />
<call target="SvnCommit" />
</target>
</project>

We also deploy out of SVN and ran into the same problem. Our solution is to essentially branch the project for "significant" upgrades -- situations where we were adding and deleting files, not just fixing small bugs and making tweaks which you can usually handle by xcopy. Svn layout looks like:
--project
---production
----20100101
----20100213
[etc, etc]
Procedure-wise, it is pretty simple -- if there are big enough changes, check in build artifacts as appropriate.
Another thing you might want to try, especially if you cannot get your production bits to "switch" branches easily, would be to use something fancier such as powershell to execute the delete files command, that could filter out the *.svn folders.

I would say "fortunately" this brings a whole new meaning to the word automation :) What you're describing is knows as Application Release Automation, also sometimes called Deployment Automation. If you really want to know who did what and where, what was the outcome, etc. then you are looking for a product like Nolio ASAP (http://www.noliosoft.com). Please let me know if this helps, since from what you're describing, it seems like a perfect match.
+Daniel

Why are you publishing the site to a folder that is handled by Subversion?
The way I would do it is work directly with the files in the SVN handled folders. As soon as I commit anything, it gets pulled by beanstalk to the staging area. This way, files deleted are always deleted from the repo and you don't have to worry about that. Everything is always in sync.
If you feel that this is putting too many files to the staging area, you can still use scripts and Visual Studio commands to publish the site. But I'm not sure how well Beanstalk integrates with this scenario. I know CC.net and many other alternatives do.

Related

Could not load definitions from resource flexTasks.tasks. It could not be found

I'm attempting to compile a Flex application from an ANT script, inside of Eclipse (CFBuilder, based on Eclipse), and I've run into this error:
Could not load definitions from resource flexTasks.tasks. It could not be found.
I haven't been able to find anything that gives directions on where this file (flexTasks.tasks) should be copied to, if it's needed at all. Some places indicate that it should be part of the flexTasks.jar file. I've tried two different things:
Copy the jar file into the ant/plugins/lib folder (and restart my CF Builder instance)
Specify the path to the jar in the classpath attribute, as suggested by the comment on this page
Neither helps me get past this error.
Here's my build script, for reference:
<project name="Tagging" default="compile-tagging" basedir=".">
<!-- setup flex compilation capability -->
<taskdef resource="flexTasks.tasks" />
<property name="flex.src" value="./src" />
<property name="flex.bin" value="./bin"/>
<target name="compile-tagging">
<mxmlc
file="${flex.src}/main.mxml"
output="${flex.bin}/main.swf"
keep-generated-actionscript="true">
<source-path path-element="${FLEX_HOME}/frameworks" />
</mxmlc>
</target>
</project>
Adam, I believe you need to tell taskdef where to look for the file. try keeping flextasks.jar in the same directory as your ant file (for now... you can move it later after you get it working).
then, you can do something like this:
<taskdef name="mxmlc" classname="WhateverTheTaskIsNamed" classpath="flexTAsks.jar" />
While not ideal, this code is working for me at the moment:
<project name="IOLTagging" default="go" basedir=".">
<!-- setup flex compilation capability -->
<property name="FLEX_HOME" value="C:/program files (x86)/Adobe/Adobe Flash Builder Beta 2/sdks/3.4.1/" />
<taskdef name="mxmlc" classname="flex.ant.MxmlcTask" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" />
<taskdef name="html-wrapper" classname="flex.ant.HtmlWrapperTask" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" />
<property name="flex.src" value="./src" />
<property name="flex.bin" value="./bin"/>
<property name="swf.name" value="main" />
<target name="go" depends="compile-flex" />
<target name="compile-flex">
<mxmlc
file="${flex.src}/main.mxml"
output="${flex.bin}/${swf.name}.swf"
debug="false"
keep-generated-actionscript="false">
<source-path path-element="${FLEX_HOME}/frameworks" />
<compiler.library-path dir="${basedir}/libs" append="true">
<include name="*.swc" />
</compiler.library-path>
</mxmlc>
</target>
</project>
I had the same problem, and the reason was in lack of permissions to acces $FLEX_HOME/ant.
You can also put the flexTasks.jar in ~/.ant/lib directory
If you run ant -diagnostics you should see the jar in USER_HOME/.ant/lib jar listing
I think you should have solved this problem. just trying flexmonkey today and also got the same problem.
"Could not load definitions from resource flexTasks.tasks. It could not be found."
solution is to make sure the flexTasks.jar is included in the dir lib of your project workplace.
when I copied flexTasks.jar from flashbuild folder \ant\lib and built it again. the problem is fixed.

NAnt and ASP.NET Compiler

I have a build script running successfully, but I am having a hard time running anything after aspnet_compiler completes. I want to use robocopy to copy the project to another folder. If I put the copy task above the compile (as shown below) I get the message to the console, but if I place it after the compile it is not seen. Am I missing something? Do I need to check for a return code from the compiler to call tasks after its completion?
<target name="copy" depends="init">
<echo message="This is my message for robocopy..."/>
</target>
<target name="compile" depends="copy">
<exec program="${msbuild.exe}"
commandline='MySolution.sln /p:Configuration=${Configuration};OutDir="${build.dir}\\"' />
</target>
<target name="precompile-web" depends="compile">
<exec program="${aspnet_compiler.exe}"
commandline='-v /MyProj-p "${build.dir}"\_PublishedWebsites\MyProj.Web'
/>
And yes, when/if I move the copy task below precompile-web I change the depends="precompile-web" and the compile task depends to "init".
If I understand you correctly here, you want to:
Copy the files
Compile them using MSBuild
Precompile them for the web
Is that right? I would have thought you'd want to do it this way around:
Compile the files using MSBuild
Precompile them for the web
Copy the files somewhere else (for use by IIS, etc)
If my way is correct, then I'd guess you'd want your targets to reference each other like this?
<target name="compile-and-publish" depends="compile,precompile-web,copy" />
<target name="compile">
<exec program="${msbuild.exe}" commandline='MySolution.sln /p:Configuration=${Configuration};OutDir="${build.dir}\\"' />
</target>
<target name="precompile-web">
<exec program="${aspnet_compiler.exe}" commandline='-v /MyProj-p "${build.dir}"\_PublishedWebsites\MyProj.Web' />
</target>
<target name="copy" depends="init">
<echo message="This is my message for robocopy..."/>
</target>
This way, you're not pinning each of your targets down to relying upon other targets (for re-use) but you get the order that you need to achieve the job at hand.
Any good to you?

Using the ASP Compiler in NAnt to build an ASP .Net MVC application

I am succesfully building ASP .Net applications in NAnt using the ASP Compiler, without a problem., as part of my Continuous Integration process.
However, if I try exactly the same process on an ASP .NET MVC application, the build fails in NAnt, but will compile succesfully in Visual Studio. The error message I get in NAnt is:
[HttpParseException]: Could not load type 'MyNamespace.Views.Home.Index'
which appears that it has a problem with the dots in the filenames, but I might be wrong.
Any suggestions are most welcome.
You shouldn't install ASP.NET MVC onto the build box. You should be referencing the System.Web.MVC, System.Web.Routing and System.Web.Abstractions DLLs from wherever you store your third-party references. We normally have a /lib folder for all references where we have those 3 DLLs (and many more) stored and a /src folder where all of our code lives. If you are referencing these DLLs this way, you no longer have to rely on the environment for those DLLs. This blog post explains this idea in more detail.
Installing the MVC bits on the build box should sort this out--it is either lacking the .dlls to know your Home.Index view descends from System.Web.Mvc.ViewPage or it doesn't have the right project template for the compiler to use.
The MVC app needs to be built as a project before using aspnet_compile. If your MVC project uses other class library projects, they also need to be compiled.
After running aspnet_compile, we then want to delete various files that should not be part of the deployed site.
This build file is located in the parent directory to my project MvcApplication.
<project default="build">
<property name="build.dir" value="${project::get-base-directory()}"/>
<property name="build.config" value="Release" />
<target name="build">
<exec program="${framework::get-framework-directory('net-3.5')}/msbuild.exe">
<arg value="/property:Configuration=${build.config}" />
<arg value="${build.dir}/MvcApplication/MvcApplication.csproj" />
</exec>
<delete dir="${build.dir}/PrecompiledWeb" includeemptydirs="true" failonerror="false"/>
<exec program="${framework::get-framework-directory('net-2.0')}/aspnet_compiler.exe">
<arg value="-v" />
<arg value="/" />
<arg value="-p" />
<arg value="MvcApplication/" />
<arg value="-f" />
<arg value="PrecompiledWeb" />
</exec>
<delete verbose="true" includeemptydirs="true" failonerror="false">
<fileset basedir="${build.dir}/PrecompiledWeb">
<include name="Controllers" />
<include name="Properties" />
<include name="obj/**" />
<include name="obj" />
<include name="*.csproj" />
<include name="*.csproj.user" />
</fileset>
</delete>
</target>
</project>
Not exactly an answer to your question but more a different tack that might solve what you wish to achieve.
I find studio to be more friendly that the asp compiler from the command line.
Could you not build it with devenv.exe through a NAnt command line task.
Best of luck,
Dan
On a project I was working on recently we build the ASP.NET MVC web app using this target:
<target name="CompileSite" depends="blah blah">
<exec program="${framework::get-framework-directory('net-2.0')}\aspnet_compiler.exe" commandline="-p "${SrcDir}\Website" -v / -d "${CompiledSiteOutputDir}" -fixednames" workingdir="${BaseDir}" />
</target>
so it is definitely possible. Our views were named something like ProjectName.Views.News.List etc.
Could you provide more details? Does the compiler say where it encounters the error (file, linenumber etc.)?
My best guess is that the ASP.Net mvc dll's are not installed on the build server. ASP.Net MVC is a separate download.

How do I compile an ASP.Net MVC project using MSBuild

How do I compile an ASP.Net MVC project using MSBuild? We use a Continuous Integration server to compile and deploy our applications. To keep things simple I created an MVC 1.0 project in VS2008. I immediately created an MSBuild script file to compile it. I did not change any code in the project. The MSBuild script contained the following target.
<AspNetCompiler
VirtualPath="/"
PhysicalPath="C:\Development\mvc1\"
TargetPath="c:\publish\xxx"
Force="true"
Debug="false"
Updateable="true"
The MVC project sln file is contained in the c:\development\mvc1\ directory. I am running XP/Pro.
I am receiving an error ASPCONFIG: it is an error to use a section registered as allowDefintion='MachineToApplication' beyond application level.. I removed the authenication mode, membership provider, etc. from the web config file until I finally saw a different error message. I am now receiving an error message saying that the file '/views/shared/site.master' does not exist.
What is going on? Thanks in advance for your help!
Am I using the wrong MSBuild command?
If you compile your sln-file (msbuild mysolution.sln) or
<MSBuild Projects="msbuild mysolution.sln" Targets="Rebuild" ContinueOnError="false"
StopOnFirstFailure="false" /><!-- -d -errorstack -->
and the sln-file has the ASP.NET MVC-project .csproj-file then the .csproj-file does have everything you need. Open the .csproj with notepad and look for:
1) This should be true:
<MvcBuildViews>false</MvcBuildViews>
2) Target Name="AfterBuildCompiler":
<Target Name="AfterBuildCompiler" Condition="'$(MvcBuildViews)'=='true'">
<AspNetCompiler VirtualPath="SomeVirtualDir" PhysicalPath="C:\Development\mvc1\" TargetPath="c:\publish\xxx\" />
</Target>
I didn't do anything else and it worked. I actually made my config so that only release build deploy the application (by moving MvcBuildViews-property under PropertyGroups. Then I can use the same .csproj in the development (debug) and deployment (release).
This build script compiles an asp.net MVC 3 application. Since the entire internet appears to have forgotten the concept of "Build Script" this one does not require you to have Visual Studio installed on the target Machine or to "lol, you just have to edit your csproj file to get msbuild!!"
Moving on.
Make sure you have .NET 4 and MVC3 installed. By the way, my build scripts only work with msbuild 4, so make sure you're using the proper one.
The general process is as follows (thanks to many hints and answers I got here!)
1) Build the dependencies (you DLL's)
2) Build the DLL for your web application.
3) Call the asp.net compiler task.
4) Check the scripts for additional comments.
Note that this is called from an outside script that compiles other DLL's (Business, data access, etc.)
<Project ToolsVersion="4.0" DefaultTargets="build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BuildDir>..\..\dist</BuildDir>
<Optimize>true</Optimize>
</PropertyGroup>
<ItemGroup >
<Reference Include="System.dll" />
<Reference Include="System.Core.dll" />
<Reference Include="System.Web.Abstractions.dll" />
<!-- add the remaining DLL's required. Check your References folder inside VS2010 and add the relevant entries here. It's a lot of references. I ommited them to make the post more compact.
For reasons that are beyond me, I only managed to get some DLL's referenced by full path. Go figure... -->
<Reference Include="C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Helpers\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.Helpers.dll" />
<Reference Include="C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Mvc\v4.0_3.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll" />
<Reference Include="C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.dll" />
<!-- The "main build script" compiles the other DLL's from the project and places them on the BuildDir folder. Just reference it here-->
<Reference Include="$(BuildDir)\*.dll"></Reference>
</ItemGroup>
<!-- Build a DLL for the code file inside your web project (controllers, models, the lot...) place it together with the other DLL's
WARNING: Simple build command. Resource files are not included in this.
-->
<Target Name="BuildWebDll">
<ItemGroup>
<CodeFiles Include=".\**\*.cs" />
</ItemGroup>
<CSC Sources="#(CodeFiles)" TargetType="Library" References="#(Reference)" OutputAssembly="$(BuildDir)\cth.web.dll" >
</CSC>
</Target>
<!-- For reasons also unkown, but covered in a number os posts in this forum, the asp.net compiler requires the necessary DLL's to be placed on the BIN/ folder of your web project. That's why we're copying every DLL we need to said folder. For debugging, check the Bin folder on Visual Studio after you compile the project. You need to replicate that in your BIN/
-->
<Target Name="CopyDLLs">
<ItemGroup>
<DllFiles Include="$(BuildDir)/*.dll"/>
</ItemGroup>
<Copy SourceFiles="#(DllFiles)" DestinationFolder="Bin\"></Copy>
</Target>
<Target Name="build">
<CallTarget Targets="BuildWebDll"></CallTarget>
<CallTarget Targets="CopyDLLs"></CallTarget>
<!-- Call this from the webproject directory. PhysicalPath references ".". TargetPath can be everything you want -->
<AspNetCompiler Updateable="true" VirtualPath="/CTH.Web" PhysicalPath="./" TargetPath="$(BuildDir)/CTH.Web" Force="true" Debug="false" />
</Target>
Remember that you have to include resource files, do any web.config replacements, etc. I really hope this helps.
The easiest way I found was to add a WebDeployment project to your solution.
http://www.microsoft.com/DOWNLOADS/details.aspx?FamilyID=0aa30ae8-c73b-4bdd-bb1b-fe697256c459&displaylang=en
You set the properties for the build in the WebDeployment project (like precompile ) . The Buildserver builds the wdprj.
In my environment I have to start by building the web first. After that I can start the wdprj.
Here is my nant - script. It should be easy to write the same in msbuild. It actually runs in TeamCity.
xml version="1.0"?>
<project name="GreatProjectWeb"
default="build" basedir="."
xmlns="http://nant.sf.net/release/0.85/nant.xsd">
<description>Build Script</description>
<!-- builds only the csproj, not the entire solution-->
<target name="build" description="Compile the project using Debug configuration for more verbose error descriptions">
<echo message="Building..."> </echo>
<exec program="C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe" >
<arg value="GreatProjectWeb\GreatProjectWeb.csproj" />
<arg value="/t:Build" />
<arg value="/p:Configuration=Release" />
</exec>
<echo message="Building Projektfile finished. Starting WDP Project..."> </echo>
<exec program="C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe" >
<arg value="GreatProjectWeb_Build\GreatProjectWeb_Build.wdproj" />
<arg value="/t:Build" />
<arg value="/p:Configuration=Release" />
</exec>
<exec program="7z" >
<arg value="a" />
<arg value="GreatProjectWeb_Deploy\web_GreatProject.zip" />
<arg value="GreatProjectWeb_Deploy\*" />
</exec>
</target>
</project>
You could use NAnt which has a "msbuild" task in it that will just do it for you. NAnt is a great way to go for CI builds.
The NAnt home page
The NAnt Contrib home page
The MSBuild task reference from NAnt Contrib
...the contrib library adds some great functionality that the vanilla NAnt doesn't have. It is very simple. I've included a snippet of my .build file here so you can see how I've used it:
<property name="DeployDestination" value="\\MyTestServerName\DestinationFolder"/>
<property name="Solution.Configuration" value="Debug" overwrite="True" />
<property name="nant.settings.currentframework" value="net-3.5" />
<if test="${WebContentDestination=='Production'}">
<property name="DeployDestination" value="\\MyProductionServer\DestinationFolder"/>
</if>
...<snip>
<target name="Build">
<msbuild project="SolutionFileName.sln">
<arg value="/p:Configuration=${Solution.Configuration}" />
</msbuild>
</target>
<target name="Deploy">
<copy todir="${DeployDestination}" flatten="true" >
<fileset>All files to copy</fileset>
</copy>
</target>

How can I deploy an ASP.NET web application using Team Build?

I have managed to install Team Foundation Server 2008 and I created a separate build server (which works because my builds are currently failing).
I have created a simple "Hello World" Web application (all is the standard Default.aspx page) and have it in TFS's source control system.
Previously, prior to TFS, I'd simply precompile my web application and xcopy the results on to a pre-created IIS Virtual directory.
Scouring Google for a while, I have yet to find a step by step guide on correctly deploying an application from TFS Source via TeamBuild to a designated test web server. I know MS Build falls into this equation, so any guidance would be helpful.
I have seen bits and pieces about deployments, with folders such as _PublishedWebSites mentioned, but have yet to find anything step by step.
I've had success using a exec task in the AfterDropBuild target in the TFSBuild.proj file.
<Target Name="AfterDropBuild>
<Exec Command="xcopy /Y /E "$(DropLocation)\\$(BuildNumber)\%(ConfigurationToBuild.FlavorToBuild)\_PublishedWebsites\MyWebsite1\*.*" "\\server\MyWebsite1\"" />
<Exec Command="xcopy /Y /E "$(DropLocation)\\$(BuildNumber)\%(ConfigurationToBuild.FlavorToBuild)\_PublishedWebsites\MyWebsite2\*.*" "\\server\MyWebsite2\"" />
</Target>
Note that the permissions need to be setup correctly for the TFS service user to access the folder on the server your are copying to.
Firstly you should be using WebDeployment projects as this will do a lot more compilation and checking of your code and markup. See here for more info.
I have 4 environments setup DV [Development], PY [Prototype], PP [Pre-Production], PD [Production] all matching branches in TFS. Each of these has also has an entry in the sln configuration manager where you can setup what projects are required to be build and the build flags.
Once that is setup correctly you can then start setting up deployment scripts. I prefer use MSbuild to deploy as it will give you a lot more fine-grained approach to deployment. MSbuild is a bit strange to start with however once you get the hang of it it's quite powerful.
My deployment script which is added to the TeamBuild config is below. Basically as you can see I do a bit of post-build cleanup before I copy to the live servers. I also use 2 MSbuild frameworks (imported at the top).
<Import Project="$(MSBuildExtensionsPath)\Microsoft\SDC Tasks - Release 2.1.3155.0\Microsoft.Sdc.Common.tasks"/>
<Import Project="$(MSBuildExtensionsPath)\FreeToDev\MSBuild Tasks Suite 3.5\FreeToDev.MSBuild.tasks"/>
<PropertyGroup>
<InetpubFolder>\\PathToInetPub</InetpubFolder>
<AppFolder>AppFolder</AppFolder>
<AppFolderPath>$(InetpubFolder)$(AppFolder)</AppFolderPath>
<WebDeployName>WebDeployProjectName</WebDeployName>
<Debug>0</Debug>
<AppConfiguration>DV</AppConfiguration>
</PropertyGroup>
<Target Name="AfterDropBuild">
<Message Text="Begin Release to $(AppConfiguration) Webserver" />
<Message Text="DropLocation = $(DropLocation)" />
<CallTarget Targets="PostBuildCleanUp" />
<CallTarget Targets="DeployApp" />
</Target>
<Target Name="DeployApp">
<GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)">
<Output TaskParameter="DropLocation" PropertyName="DropLocation"></Output>
</GetBuildProperties>
<PropertyGroup>
<CodeDropLocation>$(DropLocation)\$(AppConfiguration) Release</CodeDropLocation>
</PropertyGroup>
<ItemGroup>
<AppFilesToDelete Include="$(AppFolderPath)\**\*.*" Exclude="$(AppFolderPath)\Library\*.*;$(AppFolderPath)\App_Offline.htm;$(AppFolderPath)\jobs\**\*.*" />
</ItemGroup>
<ItemGroup>
<FilesToDeploy Include="$(CodeDropLocation)\$(AppFolder)\**\*.*" Exclude="" />
</ItemGroup>
<Copy SourceFiles="$(CodeDropLocation)\$(AppFolder)\App_Offline[RemoveToActivate].htm" DestinationFiles="$(AppFolderPath)\App_Offline.htm" OverwriteReadOnlyFiles="true"/>
<Message Text="Deleting files in $(AppFolderPath)" />
<Microsoft.Sdc.Tasks.File.DeleteFiles Files="#(AppFilesToDelete)" Force="true" Condition="$(Debug)==0" />
<Message Text="Copy $(CodeDropLocation)\$(AppFolder) to $(AppFolderPath)" />
<Copy Condition="$(Debug)==0" SourceFiles="#(FilesToDeploy)" DestinationFiles="#(FilesToDeploy->'$(AppFolderPath)\%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true"/>
<Message Text="Deploy to $(AppConfiguration) Completed" />
<Microsoft.Sdc.Tasks.File.DeleteFiles Files="$(AppFolderPath)\App_Offline.htm" Force="true" />
<OnError ExecuteTargets="ErrorHandler" />
</Target>
<Target Name="ErrorHandler">
<Message Text="Error encountered!!" />
</Target>
<Target Name="PostBuildCleanUp">
<GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)">
<Output TaskParameter="DropLocation" PropertyName="DropLocation"></Output>
</GetBuildProperties>
<PropertyGroup>
<CodeDropLocation>$(DropLocation)\$(AppConfiguration) Release</CodeDropLocation>
</PropertyGroup>
<ItemGroup>
<PostBuildCleanUpFilesToDelete Include="$(CodeDropLocation)\*.*;$(CodeDropLocation)\bin\*.xml;$(CodeDropLocation)\bin\*.pdb"/>
</ItemGroup>
<RemoveDir Directories="$(CodeDropLocation)\_PublishedWebsites\Web" />
<Microsoft.Sdc.Tasks.File.DeleteFiles Files="#(PostBuildCleanUpFilesToDelete)" Force="true">
<Output TaskParameter="DeletedFiles" ItemName="FilesThatWereDeleted" />
</Microsoft.Sdc.Tasks.File.DeleteFiles>
<Message Text="The files that were removed were #(FilesThatWereDeleted)" />
<FTDFolder TaskAction="Move" Path="$(CodeDropLocation)\_PublishedWebsites\$(WebDeployName)" TargetPath="$(CodeDropLocation)\$(AppFolder)"/>
<RemoveDir Directories="$(CodeDropLocation)\_PublishedWebsites" />
<RemoveDir Directories="$(CodeDropLocation)\$(AppFolder)\WebDeploy" />
<OnError ExecuteTargets="ErrorHandler" />
</Target>
Obviously you will need to modify to your system setup. Also it clears down the target folder before it starts to copy the new build accross. This is to make sure they system is clean but obviously you will need to add anything that you need to keep to the ExcludedFiles list.
I also have a folder for each environment in the main application project. This holds the web.config replacements (another feature of WebDeployment projects) and any other environement specifc files.
It will be a long process to get it working correctly but hopefully this will get you started!! (Obviously if you choose this apporach!)
This can be done via the build scripts directly, the Vertigo Software guys usually are the best source of info for a lot of TFS questions like this...unfortunately their blog posts don't usually rank that high on google. This one's by Jeff Atwood, one of the creators of this site:
Copying Web Files After a Team Build

Resources