Resource files are commonly used in software that includes multi-language support: we want to keep the strings and its translations separated from the code.

If we are dealing with a more or less complex solutions that contains multiples projects, we may want to separate the common translations to its own resources library.  The different projects that need to access to that common set of translations only need to add a reference to the library.

For example, let´s imagine an ASP.NET MVC application that uses in its Views strings that are translated depending on the local.

The controller passes the model to the View:

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Test()
        {
            TestModel model = new TestModel("Welcome to my application");
            return View(model);
        }
    }
}

Model implementation:

namespace WebApplication2.Models
{
    public class TestModel
    {
        public string Title { get; set; }

        public TestModel(string title)
        {
            this.Title = title;
        }
    }
}

And our View should print

</pre>
<h1>@Model.Title</h1>
<pre>

We want to create a multi-language web application. So we create a Resource file that will contain the “Welcome to my application” string. Since our solution contains other projects that use this string we create our resource file not in the ASP.NET MVC project but we create a separate project – Class Library, for example – to store our resource files.

We add the necessary reference to our ASP.NET MVC project, and we rewrite the bit on the controller that creates the View model to use the resource file:

public ActionResult Test()
        {
            TestModel model = new TestModel(Resource.Welcome);
            return View(model);
        }

And here is where we may encounter the following error:

‘Resource’ is inaccessible due to its protection level

The solution

If that happens we only need to make sure that the Resource class containing our translations is public (as opposed to define it as internal)

Set Access Modifier to Public

If the Access Modifier is set to internal we will be able to use the resource file inside the same project, but not from other external projects.

For other projects to be able to access the translations we need to set the Access Modifier to public.

Other problems we may encounter when working with resources files is the “Could not find any resources appropriate for the specified culture …“.

Advertisements