[C#] Enum has corresponding value in resx file

Hey,

We would like to suggest a new bug rule. The rule is for limiting bugs which occur when a developer forgets to add values to their resource files. This is primarily used when working with localization. A way to do this is through having enums defined and looking for them in the resx file. Our suggestion is to add a rule that raises an issue if the enum does not have a defined value in any resx file.
We are interested in developing the rule and doing a pull request if it would speed up the addition to sonar-dotnet, as we are already working on an analyzer to detect the bug.

Description of the rule:
Language: C#

Reason:
When the developer has an Enum and Resx with the same names, i.e. Error.cs, Error.en-US.resx they are used for localizing strings. If they have a missing key (enum value) in their resx file it can lead to wrong error messages for the user.

Tags: asp.net core localization

Type: Bug
Severity: Minor

Display name: Add Localization for enum value to at least 1 resx file.

Description: When using enums and resx files for localization you should avoid having enums not defined in resx files as it leads to missing strings.

External references: An example of use is here https://github.com/Hjaltesorgenfrei/TranslationExample

Noncompliant code:

//Error.cs
internal enum Error
{
    Forbidden, NotFound
}

 // Error.en-US.resx
….
  <data name="Forbidden" xml:space="preserve">
    <value>You are not authorised.  Access is for authorised personnel only.</value>
  </data>
….

Compliant code:

//Error.cs
internal enum Error
{
    Forbidden, NotFound
}
    // Error.en-US.resx
….
  <data name="Forbidden" xml:space="preserve">
    <value>You are not authorised.  Access is for authorised personnel only.</value>
  </data>
  <data name="NotFound" xml:space="preserve">
    <value>The requested resource was not found.</value>
  </data>
….

Hi @Hjaltesorgenfrei,

As far as I can see, usage of Enum for purpose of querying resource file is a project level design and decision. With build-in disadvantage of possible inconsistency that you’ve described.

From this point of view, I don’t see a way how to determine that

  • Specific Enum is meant to be used as a resource key
  • Specific Resource file is meant to be queried by an Enum
  • How to pair correct Enum (from various namespaces) to correct resource file

Also, as long as you have explicit list of resources and resources available at build time (to be able to trigger the rule), you can easily use ResXFileCodeGenerator and access keys from resource file directly.

For these reasons, I don’t think it would be valuable rule for wide range of projects with precise matching. Best option here would be to develop a custom rule for your project.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.