Friday, January 23, 2009

More Embedded Resource fun

If you're new to embedded resources please read this entry first:

Now we'll use the same image, from my previous blog entry, from within the project we created earlier. For this we will need a...

Custom Web Control

To make this, either use the default ServerControl1.cs, or right click the control project and select: Add -> New Item -> Web -> ASP.NET Server Control. By default this should give us:


To get in the habit, first...

Compile the Control Project

Select: Build -> Rebuild [project name]

This will recompile the custom web control project, including the new (empty) control and place it's DLL into the web project. This is because we previously referenced the control project from the web project. Now, we are going to...

Add a reference to the Embedded Resource to the Custom Control

In the new custom control, find the RenderContents(...) method and replace it's content with:

"<img src='"+
"' />"

You should be able to see that this is essentially just manually writing out the same code as was in the previous web page, however this time we are inside the custom control and so the reference to it can essentially be 'this.GetType()'.

Now, rebuild the custom control project as before (Build -> Rebuild [project name]) and the updated DLL will be copied to the web project. All we need to do is...

Drop the Custom Control onto a Web Page

So, create a new ASPX in the web project and open it's design view. If the custom web control project compiled correctly, you should have a new toolbox group called '[project name] Components'.

Grab the custom control from within the toolbox group and drop it onto the designer. Save everything and run the page.

You should now have the same output as in the previous blog entry!

Easy, eh?

Two things to Note are...

That dropping the custom control on your web page add a Register directive to the top (just as any ASP.NET toolbox control does)

And that you will have a <span> tag surrounding your <img> tag. To remove this, simply override RenderBeginTag and RenderEndTag, like so:

public override void RenderBeginTag(HtmlTextWriter writer)
// removed one line of default code!
public override void RenderEndTag(HtmlTextWriter writer)
// removed one line of default code!

Listing the Known Embedded Resource

If you want to place a stop point in your code and list the embedded resource files that are available to you, paste the following line just before your stop point:

object a = GetType().Assembly.GetManifestResourceNames();

Upon stopping here, the 'a' object will be a list of embedded resources.

As Before...

The entire demo solution can be found here.


1 comment:

  1. Thank you, after hours of searching this is the first page I came across with a straight runnable example that enabled me to see what I was missing.