Friday, 15 July 2011

Portable ASP.NET code using EmbeddedResourceVirtualPathProvider now on Nuget

It's not often I see my name written alongside such illustrious names as Phil Haack, Jeremy Miller and Rick Strahl, but today in the “Recent NuGet Packages” feed there it is.

And what have I done to get it there? I’ve released the EmbeddedResourceVirtualPathProvider library. What does it do, in a nutshell?

Makes ASP.NET search referenced assemblies for resource files like .css, .js, .aspx files when it can’t find them in the current project.

And what does that let you do?

Make assemblies containing redistributable chunks of web applications

How does it do it? It registers a custom VirtualPathProvider with ASP. The VPP is fed a list of assemblies containing EmbeddedResources of .css/.js/.png/.aspx/.whatever files. When a path is requested, if it isn’t found in the host directory, these assemblies are checked and the resource is returned.

So to use it, just install the eponymous Nuget package to your ASP.NET web project and it will do the rest. Then move some content files into a referenced assembly, mark them as EmbeddedResource and start your app up. It should continue to work!

Nuget: http://nuget.org/List/Packages/EmbeddedResourceVirtualPathProvider

GitHub: https://github.com/mcintyre321/EmbeddedResourceVirtualPathProvider

Things to know before going into production

  • ASP must process the file extension in order for this to work, so handlers for static file types have to be registered in web.config. The Nuget package registers .css, .js, .png and .jpg for you using the System.Web.StaticFileHandler class. This handler doesn’t set cache headers properly, so you may want to switch the StaticFileHandler for another one that does, like the Talifun static file handler.
  • In order to give a nice out of the box experience, the default Nuget package will register and scan all assemblies in the /bin directory that don’t start  with “System”. You may want to manually configure which assemblies get registered yourself in App_Code/RegisterPathProvider.cs