ASP.NET Tips: Using Image as Embedded Resource for ASP.NET CustomControl

Problem

I started writing an ASP.NET Custom Server Control, where I wanted an Image to be Embedded Resource of the Assembly itself,
so that, I do not need to ship the images separately, but surprisingly it did not work straightway for me.

The following line was not working for me:
writer.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(typeof(MyControls.MyImageControl), “ferrari.jpg”));

Ok, lets elaborate what I did and what I missed,

Step 1, I created my ClassLibrary project, added an Image, added a Custom Control class.

Image1

Step 2, Made the image an embedded resource of the Assembly.

 

Image2

 

Step3, Written my very simple Custom Control, where I assigned the image “src” to the WebResource URL


Image3
 

Step 4, Then I wanted to tryout this CustomControl in my Test Website

Image5

 

Step 5, But I got the following result.

Image4
Image6

 

Solution

After investigating a bit, I realized I missed some critical bits.


1. I did not put the correct Resource URL. I discovered this by opening up the assembly via Reflector, I found that the resource URL is different than what I have put in my code.

Image8

I corrected the resource URL in my code, (but still it did not work).

writer.AddAttribute(HtmlTextWriterAttribute.Src,
               Page.ClientScript.GetWebResourceUrl(typeof(MyControls.MyImageControl),
               “MyControls.images.ferrari.jpg”));


 Image9



2. I investigated further and found that I did not explicitly declare the image as WebResource in my assembly info . To get the embedded resource bit working, the following line is very important, and this solved my problem.


[assembly: System.Web.UI.WebResource(“MyControls.images.ferrari.jpg”, “image/jpg”)]

Image7

Note: We can also put this directly in the class file itself.


After the fix I got the following result as I have desired.

Image10

 

Summary

I have discussed here, how to embed image in an Assembly and how to use it as WebResource. Two points to note here, which are
1. After embedding a resource it is very important to explicitly declare itself as WebResource in the assembly,
2. We need correct resourceURL to access resouces from the assembly. Note: its case-sensitive as well.

I hope this discussion will save you some time. Thank you for being with me so far.