CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Thursday, September 14, 2006

Using WebResource.axd for embedded resources .net

Using WebResource.axd for embedded resources .net

anyone that has tried to use embedded resources in compiled assemblies using ASP.NET v2 has probably had the urge to beat their head against the wall. The documentation, as of now, pretty much sucks. However, after using our friend Reflector, I think I get what's going on now.

Say that you're building a control and you want to embed an image in the compiled assembly. Then you want to use the handy built-in HttpHandler WebResource.axd to serve that bad boy up. I've seen at least three different stories indicating the way it should work, but I couldn't get any of them to work. This is what worked for me:

1. Add the image to your project.
2. In the solution explorer, click the file, and in the property window, change build action to "embedded resource."
3. Add the following to your AssemblyInfo.cs file:
[assembly: WebResourceAttribute("MyNameSpaces.Resources.MyImage.gif", "image/gif")]
Important note here... the "MyNameSpaces" comes from the default namespace indicated in the project properties. The "Resources" comes from the fact that I happened to put the image file in the "Resources" folder I made.
4. In your control rendering code, you'll need the following to produce a usable URL for the image:
Page.ClientScript.GetWebResourceUrl(typeof(MyNameSpaces.MyControl), "MyNameSpaces.Resources.MyImage.gif")
Notice I used the same naming convention here.
5. Compile away.

This should produce a URL in your rendered control that looks something like:
/WebResource.axd?d=PhPk80h_UWEcbheb-NHNP5WshV_47UOpWqAOl1_li
UFfN4cNofL74cFlQ1fvpFSf0&t=632573240669964903


Now, the issue that I have with this is that I'm sure it involves some kind of reflection or something, and frankly I don't know if it's caching the object/stream/graphic. One of the instructions I saw said to add the images as resources in the project property page, but doing so only generated a Properties\Resources.cs file with more mangled name spaces. So if there's a more "correct" way to do this, someone please share!

Post a Comment