MSBuilding Web Site Projects doesn’t Copy Silverlight XAP (and How to Fix It)

If you have a Silverlight application that is consumed by a Web Site Project in Visual Studio (not to be confused with a Web Application Project), and you use msbuild on your solution, you may find that the XAP file is not copied to the website.  This will also happen if your solution is building via Team Foundation Server’s Team Build, or another similar tool. 

The issue is that since Web Site Projects (WSPs) do not have a project file associated, they are dumb about copying the XAP file.  When you build from Visual Studio, we wrap some extra smarts into the process to make sure it happens correctly.

You can work around this by creating an AfterBuild command for the Silverlight project to copy the XAP file to the WSP (normally the web project consumes the Silverlight output on its own).  This can be done by editing the project file for the Silverlight app.  The project file contains the following section towards the bottom:

 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
      Other similar extension points exist, see Microsoft.Common.targets.
 <Target Name="BeforeBuild">
 </Target>
 <Target Name="AfterBuild">
 </Target>
 -->

You can hook the AfterBuild target to do the work of copying the XAP file, like this:

 <Target Name="AfterBuild">
     <Copy Condition="" SourceFiles="bin\Debug\SampleSilverlight.xap" DestinationFolder="..\SampleSilverlight.Web\ClientBin" />
 </Target>

SourceFiles should point at the XAP file, and DestinationFolder should be a path to the WSP.  Since the Silverlight app will build before the WSP, you don’t need to worry about lining it up right with the PrecompiledWeb folder – the WSP compilation will copy the XAP for you.