There is a great feature in ASP.NET v2 that we can directly use embedded resources in compiled assemblies. For example, we have an image compiled in a assembly. Without this feature, we might have to export the image to local file system, then can use it. But now, we can just simply invoke method Page.ClientScript.GetWebResourceUrl to obtain the url to the embedded image. And all the other messes, such as performance, updating assemblies, etc., can be ignored.
Using Web Resources
Because of its fascinating feature, web resources are welcome a lot. However, it is pretty much short of documentation as of now. It's my pleasure to introduce this great feature to everybody here :) Given you're building a control and you want to embed an image in the compiled assmbly. Then you can follow the steps below:
- Add the image to your project.
- In the solution explorer, click the file, and in the "Properties" window, change "Build Action" to "Embedded Resource". Do not use "add images to a resx file" approach here.
- Add the following code to your AssemblyInfo.cs file to mark it as web-accessible:
[assembly: WebResource( " MyNamespace.ImageName.gif " , " image/gif " )]
Important note: the "MyNamespace", indicating the embedded image's namespace, comes from the naming rule: the project's default namespace followed by the folder hierarchy.
-
Use the GetWebResoureceUrl method on Page.ClientScript to get a url that can be rendered out to the client:
string imageUrl = Page.ClientScript.GetWebResourceUrl( typeof (MyType), " MyNamespace.ImageName.gif " ); -
Note that "MyType" and the embedded image "ImageName.gif" should be compiled in the same assembly.
This results in a URL of the form:
WebResource.axd?d=V7x1l5VnlO8zYm8ThY7DrjADb8AhSEGaVVY60h7WS4rleO9BL96l-_n5GNDTIdvk0VYlnj6jX8C3Us0v3Mzdww2&t=632590134445625000The "d" query string parameter stands for the embedded resource, and the "t" stands for the assembly timestamp.
A cool tip :)
Given we have a javascript file embedded in a assembly. The javascript file will render a image for client users, and I'd like to embed this image as a web resource as well. However, there is no way to get a static url for the image.ASP.NET v2 provides a "WebResource" macro to resolve this problem.
- In the AssemblyInfo.cs, use
[assembly: WebResource( " MyNamespace.ImageName.gif " , " image/gif " , PerformSubstitution = true )]
instead of :
[assembly: WebResource( " MyNamespace.ImageName.gif " , " image/gif " )]"PerformSubstitution=true" means there are macros existed in the resource that need to be substituted in with real values.
- In the resource file, use macro <%= WebResource("MyNamespace.ImageName.gif") %> to replace the image's url.
For now, "WebResource()" is the only macro you can place inside the "<%= %>" syntax within an embedded resource.
Cool huh? :)