Embedding files(resources) into a web control

July 2, 2008 by ASP.NET  

I've written a number of web controls for ASP.net over the years, and one of the issues I had working with ASP.net 1.0 was how to sufficiently handle static files that ships with my controls (javascript, CSS, images etc).

When ASP.net 2.0 came along, it introduced the capability of embedding these static files into your controls' assembly, and allow you to reference them inside your control, inturn serving resources as axd files to the browser. (functionality extensively being ab... uhm used by Ajax.net)

In my demo we're going to write a very simple control that collapses content on a page, we've got two images and a piece of javascript that we're going to embed.

First off you will need to make sure that your static files are set as embedded resources in its build action property, like demonstrated in the image below.

Web Resources

One would think that thats all you'd need to do (with regards to embedding), but you still need to go to your AssemblyInfo.cs file and do some manual additions to it (perhaps someone can tell us, why this couldnt have been added automatically).

Your reference to the resources will look something like this:
[assembly: WebResource("DemoControl.images.down.jpg", "image/jpg")]
[assembly: WebResource("DemoControl.images.up.jpg", "image/jpg")]
[assembly: WebResource("DemoControl.javascripts.collapse.js", "text/javascript", PerformSubstitution = true)]

Notice the PerformSubstitution bool (if you scroll to the right) in our javascript mime type, this informs our compiler, that we've referenced some webresources inside our javascript file (like the script below), and it needs to resolve those entities for us.

function toggle(sender, e)
    var content = document.getElementById(e);
        case "none":	content.style.display = "block";
                        sender.src = '<%= WebResource("DemoControl.images.up.jpg")%>';
        case "block":	content.style.display = "none";
                        sender.src = '<%= WebResource("DemoControl.images.down.jpg")%>';

Using our embedded resources inside the server side code, we make use of the instantiated ClientScriptManager class in the Page property of the control. I wrote a small little method to retrieve resources similarly to what you see in the javascript code.
private string WebResource(string resourceName)
    return Page.ClientScript.GetWebResourceUrl(this.GetType(), resourceName);

Leave a Comment

December 3, 2008 by Christoff Truter

I figured you didn't see it, since you pointed out using System.Web.UI

December 3, 2008 by Andy Wyatt

Thanks for pointing out you have demo code above through email. Completely missed it!

December 2, 2008 by Andy Wyatt

Thanks you've given me head start. Don't forget to add... using System.Web.UI; ...in the AssemblyInfo.cs

    Related Downloads

    ASP.NET webforms web resources demo