Embedded Resouces In ASP.NET 2.0

posted on 2005-10-09 at 21:57:03 by Joel Ross

In the Tourney Bracket Control, we have a few Javascript methods that allow for the control to be interactive on the client side. In version 1.0, that code was put right into our control - hardcoded into a StringBuilder and then registered to the page. It works for us, but it wasn't ideal.

With the next version, we wanted to be able to get two benefits that we don't have now: 1.) allow the standard javascript functions to be cached on the client, and 2.) maintain the Javascript code in a .js file rather than in a string. So we started looking at what it takes to embed resources into our DLL. We looked at it in .NET 1.1, and it looked like a bit of a pain to get the little bit of benefit we would have.

But along came .NET 2.0, and it becomes much simpler. We created a folder to hold our resources, and in it, we put a .js file with our standard functions in it, and a css file with our standard css styles that we want. Then, in the control, there's two steps we needed to perform. The first is to put an assembly level attribute that exposes that resource to the world:

[assembly: System.Web.UI.WebResource("Resources/BracketFunctions.js", "text/js")]

Then, in the PreRender event, we register this script to be put into the page:

string scriptLocation?= this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "BracketFunction.js");
this.Page.RegisterClientScriptInclude("BracketFunctions", scriptLocation);

Then, when the page is rendered, you end up with a script include in the HTML page:

<script src="WebResource.axd?SomeExtraStuff!" language="Javascript" />

All in all, it's pretty simple and straight forward, and it accomplishes both of our goals. Because it's included as an external script file, the browser can cache it, and since we can now manage it as a javascript file, it's much easier to modify. Same with the css file.

This is just one of the things that have made our life easier building the new control. I'm installing Visual Studio 2005 RC1 right now, and I'm looking forward to see how things have progressed. Once I get the TBC up and running on that, I'll give a quick update on how the migration process went (I expect it to be pretty easy), and what we have left to do.

Categories: ASP.NET