Search code examples
c#asp.netdrupallocalizationresource-files

Replacing "token" inside resource files c#


I have a series of Resource Files for Localization purposes.In Drupal, there are something called tokens, which are some patterned text that it is replaced by the server when it is called.

Example:

Resource file in English:

I have this localization text in my resource file in English, and I would like to display to $[user] how this works.

Resource file in Spanish:

Yo tengo este texto localizado en el archivo de recursos en español y quisiera enseñarle al $[user] cómo esto funciona.

Then, after some parsing I would replace the token with the correct details.

My current approach has been the following:

public class LocalizationParser
{
    private Dictionary<string, dynamic> Tokens { get; set; }

    public LocalizationParser()
    {
        Tokens = new Dictionary<string, dynamic>();
        Tokens.Add("$[user]", HttpContext.Current.User.Identity.Name);
    }


    public string ParseResource(string text)
    {
        foreach(var token in Tokens)
        {
            text.Replace(token.Key, token.Value);
        }
        
        return text;
    }
}

I know I have a huge problem that I am getting all these values populated, and there WILL be an unnecessary performance impact. I know that if I could call a method which could retrieve the correct value only if the dictionary key has been found, there wouldn't be a huge overhead into it.

What is the correct way to do this in c#? (Currently using ASP.NET MVC 5 with EF 6.1)


Solution

  • "Premature optimization is the root of all evil" as Knuth says. Why are you so sure there will be a performance impact?

    Is this an assumption or a fact that you can back up with numbers that you identified a bottleneck with a profiler like dotTrace? Also it would be useful to know how many tokens do you expect to have.

    In any case, a Replace is fine. You can use a Hashtable and use the Exists method combined with a regular expression to get first the tokens and then do the lookup.

    Just remember that strings are immutable and thus every replacement means a nee copy and that can be slow if done any times.

    For modifying many times a string use instead a StringBuilder.

    The process is thoroughly documented: https://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.110).aspx