Example: Spell Checking String Resources

String resources are commonly used to centralize strings used by a program so that the text can be localized to multiple languages. This example uses the FxCop WordParser class and the FxCop spell checking facilities to verify that the words in these strings are spelled correctly. Note that this is a very simple implementation and more sophisticated checks, such as whether strings begin with a capital letter, are not included.

Rule XML:

<Rule TypeName="SpellCheckStringResources" Category="Tutorial" CheckId="TT1020">
  <Name>String resources should be spelled correctly</Name>
  <Description>
    String resources should be spelled correctly.
  </Description>
  <Url></Url>
  <Resolution>Check the spelling of the word '{0}'.</Resolution>
  <MessageLevel Certainty="75">Warning</MessageLevel>
  <Email></Email>
  <FixCategories>NonBreaking</FixCategories>
  <Owner></Owner>
</Rule>

Rule Implementation:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Resources;
using System.Text;

using Microsoft.FxCop.Sdk;

namespace TutorialRules
{
  class SpellCheckStringResources : BaseIntrospectionRule
  {
    public SpellCheckStringResources() :
      base("SpellCheckStringResources", "TutorialRules.TutorialRules",
      typeof(SpellCheckStringResources).Assembly)
    {
    }

    public override ProblemCollection Check(Resource resource)
    {
      using (MemoryStream mstream = new MemoryStream(resource.Data, false))
      {
        using (ResourceReader reader = new ResourceReader(mstream))
        {
          foreach (DictionaryEntry entry in reader)
          {
            string s = entry.Value as string;
            if (s != null)
            {
              foreach (String word in WordParser.Parse(s, WordParserOptions.None))
              {
                if (NamingService.DefaultNamingService.CheckSpelling(word) !=
                  WordSpelling.SpelledCorrectly)
                {
                  this.Problems.Add(new Problem(this.GetResolution(word), word));
                }
              }
            }
          }
        }
      }

      return this.Problems;
    }
  }
}