Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1303, DoNotPassLiteralsAsLocalizedParameters, but I'm actually not

My code gets the CA1303 warning from Microsoft.Globalization, "Do not pass literals as localized parameters", but my code is not actually passing a literal:

private void MyForm_Load(object sender, EventArgs e)
{
    UpdateTitle();
}

private void UpdateTitle()
{
    Version version = Assembly.GetExecutingAssembly().GetName().Version;
    CultureInfo culture = CultureInfo.CurrentUICulture;
    this.Text = String.Format(culture, "{0} v{1}.{2} Alpha r{3}", this.Text, version.Major, version.Minor, version.Build);
}

This code sets the title of the form to something like this, every time it is loaded:

MyFormNameAsSetInTheDesigner v0.1 Alpha r123

(version.build actually contains the SVN revision, which is auto-updated at each commit, I do not use revision because my versioning scheme uses only 3 numbers, major.minor.revision)

But this triggers the aforementioned warning, because it thinks I'm setting the titlebar text from a string literal. In fact, I've set Localizable = True in the designer, so that the string is fetched from a resource table.

I do not want to set the form's title statically because (especially in the alpha and beta stages) I want it to have dynamic version numbers.

The question is what do I do so I don't get a warning (for example, which code will do what I'm doing but be considered correct per FxCop, or how can I supress it for that line).

like image 760
Camilo Martin Avatar asked Mar 21 '12 12:03

Camilo Martin


1 Answers

Based on the documentation for CA1303, the reason for the warning being raised is that you pass a literal string as the second parameter of the String.Format method, and in addition the second formal parameter of that particular overload is annotated with LocalizableAttribute.

Therefore what the warning wants you to do is to put the string "{0} v{1}.{2} Alpha r{3}" as a localized resource in your resource assembly, and refer to it as such. Which is probably a good idea, as technically the structure of the format string and the fixed parts of its contents are localizable resources.

If you simply want to make FxCop shut up, you can annotate UpdateTitle accordingly:

[SuppressMessage("Microsoft.Globalization",
                 "CA1303:DoNotPassLiteralsAsLocalizedParameters" )]
private void UpdateTitle() { /* ... */ }
like image 84
Jon Avatar answered Nov 05 '22 13:11

Jon