Click here to Skip to main content
Click here to Skip to main content

WebResource ASP.NET 2.0 explained

By , 26 Feb 2006
 

Introduction

This code drop is part of Redux series. This article started out to be about a dropdown date/time ASP.NET 2.0 server control. So I built the control and all its ancillary JavaScript, along with the images, and then everything was put into a zip file for uploading to the CodeProject. The installation instructions for the control went something like this:

  • Unzip the contents to a folder.
  • Copy the DLL to the Bin folder of your new project.
  • Copy the JavaScript file.
  • Copy the CSS file.
  • Copy the images.

Hey, wait a minute, this is really lame, why all the extra files, why not embed them into the DLL as resources. That was the beginning of three days of hell trying to understand and work with WebResources. I have boiled it down to about twenty lines of working code.

Nothing else on the net gives you an actual working sample and a lot of the information is simply wrong (possibly because it was based on beta versions). Well, this code compiles and runs on the release version of .NET 2.0.

Code snippets

Create a project which looks like this (you can get the control from the download and then just add an ASP.NET project to the solution):

Highlight the three files in MyResources, and in the Properties window, set Build Action to Embedded Resource:

The source for the control is as follows:

namespace MyWebResourceProj
{
  [ToolboxData("<{0}:MyWebResource runat="server"></{0}:MyWebResource>")]
  public class MyWebResource : System.Web.UI.WebControls.TextBox
  {
      protected override void RenderContents(HtmlTextWriter output)
      {
         output.Write(Text);
      }

      protected override void OnInit(EventArgs e)
      {
        base.OnInit(e);
        this.Page.ClientScript.RegisterClientScriptInclude(
           this.GetType(), "Test", 
           Page.ClientScript.GetWebResourceUrl(this.GetType(), 
           "MyWebResourceProj.MyResources.Test.js"));

        // create the style sheet control
        // and put it in the document header
        string csslink = "<link href='" + 
           Page.ClientScript.GetWebResourceUrl(this.GetType(), 
            "MyWebResourceProj.MyResources.Test.css")
           + "' rel='stylesheet' type='text/css' />";
        LiteralControl include = new LiteralControl(csslink);
        this.Page.Header.Controls.Add(include);
      }
  }

This is not a discussion on server controls, so let's focus on the parameters of GetWebResourceUrl:

  • this.GetType() - mandatory, just do it.
  • "MyWebResourceProj.MyResources.Test.js" - this is the most misunderstood parameter and the source of just about all errors. It is composed of [Assembly of this project].[Folder containing resource].[Filename of resource].

No matter what you read anywhere else, including Microsoft's official documentation (which is wrong), if you don't do it this way, you will fail (I know this from personal experience).

Now on to the AssemblyInfo.cs:

[assembly: System.Web.UI.WebResource(
      "MyWebResourceProj.MyResources.Test.css", "text/css")]
[assembly: System.Web.UI.WebResource(
      "MyWebResourceProj.MyResources.Test.js", 
      "text/javascript", PerformSubstitution = true)]
[assembly: System.Web.UI.WebResource(
      "MyWebResourceProj.MyResources.Test.gif", "image/gif")]

You need to specify the resource name exactly as you did in your program code. You need to specify the mime-type. If the file contains JavaScript, you may want to have ASP.NET perform text substitution. For example, you may have a line in JavaScript like:

document.write("<img src='Test.gif'>");

When you embed your images in a resource, you no longer know the name of it as it appears in the resource. To fix this, code as follows:

document.write("<img src='<%=WebResource("MyWebResourceProj" + 
                                 ".MyResources.Test.gif")%>'>");

All the "official documentation" and all the articles on the web say that you can leave [AssemblyName].[FolderName] out. But they are dead wrong!

Note: if you are using this control as the base class of another, see yc4king's note below.

Update

KonstantinG has pointed out an error which only becomes apparent when your namespace is not the same as your assembly name. Previously, I had indicated that the name of the resource is: [Namespace of this project].[Folder containing resource].[Filename of resource], but really it is [Assembly of this project].[Folder containing resource].[Filename of resource]. As always, the best way to find information on this is by using Lutz Roeder's .NET Reflector available at aisto.com.

SmashGrab / Redux series

I have recently started two series of articles here at CodeProject.

Smash and Grab is intended as a series of short articles on one specific code technique. Redux is intended as a series of longer articles which attempts to reduce a complicated topic (like WebResource) into its basic constituent parts and show that once you have all the information, it isn't really that hard. To find the Smash and Grab articles, search for the keyword SmashGrab. To find the Redux articles, search for the keyword Redux. I welcome any contributions to either series, but please follow the guidelines when submitting articles to either.

Conclusion

So there you have it, everything you need to know to use WebResources. This article documented how to place CSS files in the <head> section, extract JavaScript files, dynamically change the contents of a JavaScript file.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Gary Dryden
Software Developer (Senior)
Canada Canada
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionabout art. WebResource ASP.NET 2.0 explainedmemberRajung30-Jan-13 21:52 
GeneralInherit from control that uses embedded resource...memberFayu13-Sep-10 12:21 
AnswerRe: Inherit from control that uses embedded resource...memberFayu11-Mar-12 16:11 
QuestionCan I access server variables within the embedded resource file?memberEM1L2-Sep-10 1:50 
QuestionWhat about images referred to within CSS?memberrobvon20-Jan-10 15:32 
AnswerRe: What about images referred to within CSS?memberrobvon30-Jan-10 21:26 
GeneralGreat!memberjoao paulo turski2-Jan-10 3:08 
General[AssemblyName].[FolderName]memberPa226-Nov-09 6:50 
from my experience it is not [AssemblyName].[FolderName] but [Namespace].[FolderName]
in my project they are different and when using reflector on my dll with the embedded resource I see the resource with [Namespace].[FolderName]
alse when I call RegisterClientScriptResource i have to use Namespace otherwhise my jscript file is empty
GeneralRe: [AssemblyName].[FolderName]memberSteve Pritchard9-Dec-09 7:27 
GeneralYohoo!!!memberAzerax21-Oct-09 4:43 
Generalit works in aspx but not work in ascxmemberngohieutp25-Mar-09 8:14 
Question"very urgent" how can i make &gt; link send to a friend option &lt; using asp.net 2.0membersandeepgreaternoida27-Dec-08 0:51 
GeneralMy vote of 2memberykorotia26-Nov-08 7:52 
Rantfor those who doesn't know what is msdn and asp.net forummemberykorotia26-Nov-08 7:51 
GeneralAwesome articlememberAbhishek sur9-Oct-08 22:28 
Generalthanks for removing the confusionmemberpsykoptic29-Jul-08 2:11 
GeneralGreat Articlememberkarpach969-Jul-08 6:17 
QuestionResource not showing when in release modemembermrod153-Jun-08 9:53 
Generalholding the control propertiesmemberjayaram04076-May-08 7:01 
GeneralImage not displayed from assembly web resourcememberSudhir Yadav25-Oct-07 22:30 
GeneralRe: All the "official documentation" ..... are dead wrong!memberExtractor7-Aug-07 21:04 
GeneralRe: All the "official documentation" ..... are dead wrong!memberstmarti12-Sep-07 2:56 
GeneralGood workmemberleapoflogic10-Jun-07 10:19 
GeneralWorth MentioningmemberFrank Olorin Rizzi19-May-07 4:36 
QuestionJS functions not workingmemberUdit Handa1-May-07 23:15 
Questionwhat if head is not runat=server?memberSib26-Mar-07 20:54 
AnswerRe: what if head is not runat=server?membermortb16-May-07 1:07 
GeneralWebResource and MasterPagemembercrustiq14-Feb-07 22:49 
AnswerRe: WebResource and MasterPagememberMarkBaldwin24-May-07 14:55 
GeneralDude you are the bestmemberMember #35549995-Feb-07 12:08 
GeneralThanks!!!!membermaurocodeproject22-Jan-07 12:50 
GeneralMy Toolbox image not reflecting with new imagememberRamesh Tamma16-Jan-07 7:33 
GeneralDLL Resource ReferencememberTonyCsr15-Nov-06 8:53 
GeneralThe folder problemmemberennixo14-Sep-06 10:16 
QuestionBut Atlas Changes everything?memberjokva13-Sep-06 9:00 
GeneralPage.ClientScript does not compilememberwebber12345610-Sep-06 7:49 
Generalthis.GetType() - mandatory, just do it. - EXPLAINEDmemberAdam Selene7-Sep-06 14:40 
GeneralRe: this.GetType() - mandatory, just do it. - EXPLAINEDmembersteph7530-Nov-06 8:30 
General[Assembly of this project].[Folder containing resource].[Filename of resource]membermephix4-Sep-06 5:08 
GeneralRe: [Assembly of this project].[Folder containing resource].[Filename of resource]memberstmarti22-Jan-07 5:01 
GeneralRe: [Assembly of this project].[Folder containing resource].[Filename of resource]membercueshot4-Jun-07 9:31 
GeneralRe: [Assembly of this project].[Folder containing resource].[Filename of resource]membercueshot14-Jun-07 13:44 
GeneralCheck that embedded resource exist before callmemberMichael Freidgeim1-Sep-06 17:25 
GeneralRe: Check that embedded resource exist before callmemberstmarti22-Jan-07 5:25 
GeneralEmbedding an aspxmemberAndrew de Klerk23-Aug-06 23:14 
GeneralRe: Embedding an aspxmemberAdam Selene7-Sep-06 14:47 
GeneralRe: Embedding an aspxmemberAndrew de Klerk7-Sep-06 21:02 
AnswerRe: Embedding an aspxmemberTalk To The Hand6-Apr-07 21:06 
GeneralWrite out variabel or text in Embedded resourcememberSkoder12-Aug-06 5:55 
QuestionBrowser Caching???memberpaul.tyng21-Jul-06 8:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 26 Feb 2006
Article Copyright 2006 by Gary Dryden
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid