Custom Resource Provider and resource object with key was not found compiler errors

I was using custom resource provider for my globalization project. We had separate class library project for our custom resource provider and we were putting all the resource files (.resx) under that project. Off course when we build that project, It complies resource files into satellite assembly. And it was working as expected. But we have a concern about that satellite assembly. Whenever we add/modify resource text, we need to rebuild satellite assembly and we might need to restart IIS to take it affect. It’s difficult while doing on production so we came up with the conclusion to separate resource files out of class library project and keep it .resx files means not compiling into satellite assembly so It’s easy to modify resource text without recompiling satellite assembly. We succeed in separating resource files out of project. It was working as expected when I hit the web application.

But when I build my project, I ended up with lots of compilation errors. Error – “Resource object with key ‘key’ was not found.” It was strange for me because when I ran that application(not from visual studio I hit the URL directly in browser), It was working fine without any issue. Honestly I took me a whole day to figure it out what’s wrong in my code.

Here is the problem…

In my custom resource provider class, I was trying to map virtual path to physical path using HttpContext.Server.MapPath like this

Dim resourceManager As New ResxResourceManager(MyBase.ClassName, HttpContext.Server.MapPath(ConfigurationManager.AppSettings(“i18nResourcePath”).ToString()))

It works fine as long as there is a httpcontext not null and yes It was working fine If I run my application directly hitting URL from browser. But when we compile the project, It doesn’t have HttpContext at that time so visual studio failed to get resource file and throws an compilation error “Resource object with key ‘key’ was not found”. Yes you would have question in your mind that why visual studio checking that but It does this just to make sure you have no typos. So to fix this, we have to use System.Web.Hosting.HostingEnvironment.MapPath instead of HttpContext.Server.MapPath. It works the same way, as Server.MapPath(), but it is a static method requiring no HttpContext to be present.

Hope this article helps you. Please leave a comment if you have a question about this.

Posted in Microsoft Technology Tagged with: ,

Ads