Embedding web resources in ASP.NET

Created 03 July 2007 00:00
Images, JavaScript, CSS, and pretty much anything you like can be embedded in your web dlls and referenced from code.

To use web resources, do the following:

  1. Add your resource file to your project, and set the property of the file (by right clicking it) to "Embedded Resource
  2. In your C# code, you can refer to the file, for example, as follows:
      ClientScriptManager cs = Page.ClientScript;
      Type type = this.GetType();  
      if (!cs.IsClientScriptIncludeRegistered(type, "MyJavaScriptFile"))
        string url = cs.GetWebResourceUrl(type, "My.Controls.Resources.MyJavaScriptFile.js");
         cs.RegisterClientScriptInclude(type, "MyJavaScriptFile", url);
  3. Finally, you need to reference your web resource in the AssemblyInfo.cs file of your project:
    [assembly: WebResource("My.Controls.Resources.MyJavaScriptFile.js", "text/javascript")]

You can also get .NET to parse the embedded resource for code contained in the resouce, and substitute that for other values. For example, in an embedded CSS file you may want reference an embedded image. This can be done by

  1. Adding PerformSubstitution=true to your AssemblyInfo.cs declaration:
    [assembly: WebResource("My.Controls.Resources.MyStyles.css", "text/javascript", PerformSubstitution = true)]
  2. In MyStyles.css, add standard ASP include code:
      background:url("<%= WebResource("My.Controls.Resources.MyImage.gif") %>") no-repeat left top;

Element Wrapping in IE6

Created 06 July 2007 00:00

Now that tables are no longer acceptable for use when creating displays, there remains a problem when trying to get a row of elements to always display as a row without wrapping. In IE7 and Firefox, you can get it to behave fairly easily, but in IE6 it's actually impossible without using a table.

However, using browser sniffing, you can get a row of elements to always display on a single line with the following code:

<!--[if lte IE 6]><table><tr><td style="display:inline;"><![endif]-->
<div class="TreeNode ">
  <div class="NoText" style="display:inline;"><IMG height="20" alt="" src="images/img1gif" width="16"></div>
  <img alt="" src="images/img2.gif" />
  <a class="TreeText" title="Some title" href="javascript:myFunction()">My example</A>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->

This effectively wraps the elements in a mini table for IE6 only. If you want to use browser sniffing, only output the commented lines if the browser is IE6.