Oct 24 2006

Including WebResource in ASP.NET server control

Posted by admin under Controls

Embedding resources (such as images, javascript, stylesheet information) into your server control makes it a lot easier for redistribution - and reusing the control in other projects is indeed the reason as why to create a control at all.

This example will show you how to embed a javascript in your server control.

Consider this example:

We are creating a control - JSLog in assembly JSLogControl.dll - and it relies on two javascripts (jslog.js, jslogrel.js). We want other developers to just copy the dll (nothing more) and start using it in his/her projects.

So - we make them compile as embedded resources - by selecting them in solution explorer (one at a time) and setting the build action:

 

These embedded resources can be retrieved through unique url - and those can be retrieved from our code. First we add these attributes to the controls cs file:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


[assembly: WebResource("JSLogControl.scripts.jslog.js", "text/javascript")]
[assembly: WebResource("JSLogControl.scripts.jslogrel.js", "text/javascript")]  


namespace JSLogControl
{


    [ToolboxData("<{0}:JSLog runat=server></{0}:JSLog>"), Designer("JSLogControl.JSLogControlDesigner")]
    public class JSLog : WebControl
    {
...
...
...


Here we associate the embedded resources with a certain mime type - we want to return the data as "text/javascript".

The secret about getting this to work is naming:

JSLogControl.scripts.jslogrel.js

means

[assemblyname].[path].[filename]

Next step is to get the <script src='''> call into the page. We override OnPreRender:



            if (Page.ClientScript.IsClientScriptBlockRegistered("ASPCodeJSLog") == false)
            Page.ClientScript.RegisterClientScriptInclude("ASPCodeJSLog",
                         Page.ClientScript.GetWebResourceUrl(this.GetType(),
                                                     "JSLogControl.scripts.jslog.js"));


By using the Page.ClientScript.GetWebResourceUrl and the same name as above ASP.NET will generate a call to webresource.axd with a strange guid-type looking identifier



<script src="/JSLog.NET/WebResource.axd?d=z8i_jQgzlsIlo6Wjkog0gd8MF2UqhWSt5n_7PYhmtqBbW1lCtrvb162pxemoxkK70&amp;t=632972889607752916" type="text/javascript"></script>

but that's now our problem. ASP.NET will handle it for us and retrieve the javascript from the resources and serve it - as text/javascript - for us.

And as I said - all you need now is copy the dll to whatever machine you'd like (and nothing but the dll) and no javascript files at all! 

 For an example of this technique - download and test out JSLog.NET