Compsoft Flexible Specialists

Compsoft plc

Compsoft Weblog Compsoft Website News Archive Privacy Policy Contact Us  

Tuesday, May 08, 2007

Embedding resources in .NET assemblies

This is not a typical blog entry for me as I have seen this sort of topic around on technical forums many times and usually I don't feel the need to talk about stuff that has already been talked about however in this case I feel I must impart an extra piece of knowledge which I have gleaned and which I did not find in other discussions.

My initial problem lay with embedding files (in my case JavaScript files) into a reusable assembly. this I mastered very simply using other blogs and technical articles using the following code:

Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Compsoft.WebCode.EmbeddedFiles.Javascript.js");

All fine and dandy right up until the point where I had written my second JavaScript file and needed that embedded too. I used the same tack and added the second JavaScript file to the line below my first. Everything compiled however when it came to running the code it turned out that only my first registered file was actually registered, the second (and all subsequent files) were simply not there. The links to WebResource.axd were there however when those links were inspected the contents of them simply returned a 404 file not found error!!!

This confused me greatly and here I come to the thing that I couldn't find anywhere and therefore the reason for this blog.

I found that in order for more than one file to be registered in the same assembly it is necessary to list these files not only in the class structure when you register the resource to the page but also on the namespace which contains that class as seen below:


[assembly: WebResource("Compsoft.WebCode.EmbeddedFiles.Javascript.js", "text/javascript")]
[assembly: WebResource("Compsoft.WebCode.EmbeddedFiles.OtherScript.js", "text/javascript")]
namespace Compsoft.WebCode.Controls
{
[ToolboxData(@"<{0}:MyControl runat=""server"" />")]
public class MyControl : System.Web.UI.WebControls.WebControl
{

public MyControl()
: base()
{
this.Load += new EventHandler(MyControl_Load);
}

void MyControl_Load(object sender, EventArgs e)
{
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Compsoft.WebCode.EmbeddedFiles.Javascript.js");
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Compsoft.WebCode.EmbeddedFiles.OtherScript.js");

}
}
}


This little bit of insight has made my code so much more manageable and certainly made my life easier, just thought I would share it with the world.

0 Comments:

Post a Comment

<< Home