Reputation: 2105
When throwing custom exceptions or issuing messages to the end user, one could use hard-coded the strings (including string constants), use resource-only assemblies or get strings from a table in a database.
I would like my application to be able to switch to a different language easily without having to recompile. While storing the string resources in a assembly or database would achieve this purpose, it adds to the complexity of program logic which in turn adds to the cost of the product.
My question is: what is the best way to go with the objective in mind without ignoring the cost that comes with each option? If you have a practice that is better than what's been listed, I'd love to hear it.
Technologies: OS: Windows family Platform: .NET Frame 2 and up Language: C# Database: MS SQL 2005 and up
Thanks guys!
Cullen
Upvotes: 4
Views: 3836
Reputation: 933
.NET already supports multiple resources for multiple cultures using a naming convention:
<default resource file name>.<culture>.resx
Essentially as Josh pointed out VS2008 creates a nice type safe wrapper to access these resources.
However the VS UI exposes the bear minimum of what you can do.
If you create a new Resource File called exactly the same as the default, however add the culture info before the resx. (NOTE: You will need to create it somewhere else then copy it into the magic Properties folder.)
Then your application will if you have applied the culture to the thread accessing the resource pull the correct string from the specific resources.
For example:
// Using the default culture
string s = Resources.Error1Msg;
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-CO");
// Using the specific culture specified as above:
s = Resources.Error1Msg;
If you need to parameterize you message, use string.Format to parameterize the output.
One word of caution is try to architect your application layers in such a way that your exceptions carry a rich payload (to describe the error), instead of relying on just text.
That way your presentation layer can present the best UI experience which might utilize the payload.
HTH
Philip
Upvotes: 2
Reputation: 67108
Use resources:
How does this add more complexity to the program logic?
try
{
//do something with System.Net.Mail with invalid email..
}
catch (FormatException fex)
{
throw new Exception(Resources.ErrorMsg.Invalid_Email, fex);
}
In VS2008 when you create a resource, you can define if its internal or public. So assume we set it to public, in an assembly called ClassLibrary1, we can access a property like:
ClassLibrary1.Properties.Resources.InvalidError
Where InvalidError is the name of the error. Again I don't think this adds any compelxity to the logic.
Upvotes: 4