Tuesday, June 19, 2012

Embedded resource

I have the feeling that I faced this difficulty already in the past. But obviously did not write about it here. And so this time again, it took some time to figure out. Now I should keep it here.

It is to have some “resource files” embedded in the assembly and accessible from clients. Not about the other type of “resource files” where you have key/value pairs.

I used this technique in the past with a web part, and remember it was rather straightforward.

But then, this time, tried to do the same in a web application project and ran across a few points that required some Googling to overcome.

First of all, the project's AssemblyInfo file needs to modified. With hands? I did. http://aspnet.4guysfromrolla.com/articles/080906-1.aspx explains it.

Secondly, the “this.GetType()” in the following code does not work, with a web application project.

Page.ClientScript.RegisterClientScriptInclude("hoge", Page.ClientScript.GetWebResourceUrl(this.GetType(), "hoge.js"));

Correct me if I am wrong. I did not bother digging it further to confirm, but in a web app project, embedded resource files such as a javascript file are included into the project’s assembly together with the code behind classes etc. But the “this” does not point to it. Rather, it points to the temporal assembly the framework generates from the .aspx file accessed.

But GetWebResourceUrl method succeeds nevertheless. This makes its debugging difficult. The method succeeds and return a seemingly valid WebResource.axd path. It is then included into the response html. Client requests it and Bomb. The requested file is not found.

http://stackoverflow.com/questions/320484/webresource-hell-resource-cannot-be-found told me the fix.

Page.ClientScript.RegisterClientScriptInclude("hoge", Page.ClientScript.GetWebResourceUrl(typeof(whatever class that I am sure cohabit with the js), "hoge.js"));

I do not know how framework maps the long parameter of WebResource.axd request to my javascript. But it is certainly not in the temporal assembly the framework generates, represented by “this”, but in my project’s assembly. I have to specify it precisely.

No comments: