Moses on DotNetSlackers

.Net Gorean Lifestyler

This site


@ Cambridge, UK



  • MaximumASP

System.Web.UI.WebResourceAttribute Issue

You may've heared about new ASP.NET 2.0 System.Web.UI.WebResourceAttribute class. It defines the metadata attribute that enables an embedded resource in an assembly. It is valid only when used on assembly declarations and it is used to enable a specified embedded resource in an assembly for use as a Web resource.

For example, suppose you are building a web server control, or custom HttpHandler that would render some javascript "js" files and may few images etc...
Where you would store these files "resources"?! The answer is you can embed them in your assembly and reference them as web resources from your code.

To register a resource as WebResource you would use this line of code, you can do that in AssemblyInfo file:
[assembly: System.Web.UI.WebResource("dropdownarrow.jpg", "image/jpeg")]

For more information about WebResource parameter, please return to MSDN, currenlty I can mention that the 1st on is the resource name, and the 2nd one is the content-type of the resource, in our case it is an image so the content type is image/jpeg. If your resouece file is javascript, then the content-type would be text/javascript

And you can reference your resource using ClientScriptManager class through Page.ClientScript Property as the following
string resUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(YouControlType), "dropdownarrow.jpg");

Now use your resUrl to display your image!....
BUT WAIT, this is not going to work!!

If you followed the MSDN code while you are VS.NET this is not going to work at all, your image or your resource file never appear.
Here are the Rule:

  1. You should know your Assembly default namespace.
  2. Recognize where exactly your resource file located in your project, "Its Path"
  3. Define the correct resource name.

Suppose your default namespace is DotNetSlackers.WebControls, while your resource file name is DotNetSlackersUtil.js, this file is located on a folder named DNSResources/Scripts in your project -Dont care about your project name or assembly name, just focus on your Default namespace name-.

Now your resource file should be name "DotNetSlackers.WebControls.DNSResources.Scripts.DotNetSlackersUtil.js".

The rule simpley is [Default namespace].[Resource Path from the project root -replace '/' with '.' of course-].[Resource FileName]

So you'll register your WebResource as the following:

[assembly: System.Web.UI.WebResource("DotNetSlackers.WebControls.DNSResources.Scripts.DotNetSlackersUtil.js", "text/javascript")]

And you can get your resource URL as the following:

string resUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(YouControlType), "DotNetSlackers.WebControls.DNSResources.Scripts.DotNetSlackersUtil.js");

Hope this would help somebody


No Comments