Adding ASP.NET to your universal JavaScript Store apps project

While exploring the possibilities of using frameworks like KnockoutJS and Backbone in my store apps I started wondering if it would be possible to share my JavaScript code between Windows Store app, Windows Phone app and an ASP.NET website. After some exploration and fiddling with various options I figured it out.

Here’s how to do it.

If you have a solution with an ASP.NET website, add a universal project to the solution. Or add a MVC project to the solution with you universal projects.

Unload the web application and add to the following line to the file right before the import of “Microsoft.CSharp.targets”. Where App79 would be the name of your shared project of course…

 <Import Project="..\App79.Shared\App79.Shared.projitems" Label="Shared" />

This will enable the connection between the projects. Because linking JavaScript files doesn’t work in web projects (the files are not really in the expected folder) the files have to be copied too.

After some searching I came across the following blogpost by Matt Perdeck, Copying linked content files at each build using MSBuild. He explains how to have the build copy linked files to their target location.

By adding the following lines to the end of the project file, right before the last closing tag, files are copied before the build. He even optimized it a bit, by skipping the unchanged files.

<Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)" 
          DestinationFiles="%(Content.Link)" 
          SkipUnchangedFiles='true' 
          OverwriteReadOnlyFiles='true' 
          Condition="'%(Content.Link)' != ''" />
</Target>

Close the project file and reload the project. As you can see in the references section the shared project is included.

You need to make sure that the names of the folders in the shared project are available in the web project too. I assume these are already created in the Windows Phone and Windows Store projects.

One nice extra is that you can add breakpoints in the shared project that will hit when running the web project. You can also switch the context to the web application in the .js files.