One of the most exciting enhancements of ASP.NET 2.0, are Virtual Path Providers. They allow your web application to load pages and files from any media like a SQL database for example. Does that remind you of SharePoint? It should because SharePoint uses virtual path providers too. So how can you put this feature in use? First of all we need to write our own virtual path provider. All we need resides in the System.Web.Hosting namespace, in the System.Web.DLL assembly. Key classes here are the VirtualPathProvider, VirtualDirectory and VirtualFile. The VirtualPathProvider class, when overridden, it handles the retrieval of resources from a virtual file system. Some notable methods are the GetFile GetDirectory and OpenFile. GetDirectory and GetFile return an object of type VirtualDirectory and VirtualFile respectively. Those classes in their turn, need to handle the directory and file operations. The VirtualDirectory class for example needs to return a collection of files when the Files property is accessed. The VirtualFile, needs to return a stream to the file whenever the Open method is called. As soon as our classes are ready, we need to register our provider. SharePoint does it in a module but there is a much easier way; add a global.asax file to your site and in the ApplicationStart event, register the provider with the following code:

System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(CustomVPProvider);

I am not going to show an example here since I am cooking something that covers virtual path providers and others. I will be posting it soon so stay tuned.

Advertisements