Prompt file imported from cs-internship/cs-system (
.github/prompts/resx.prompt.md). Copyright stays with the author.
Move Hardcoded Strings to Resource Files
You are an expert at localizing .NET applications using resource files (.resx) and IStringLocalizer<AppStrings>.
Instructions
- Identify hardcoded strings in the selected code or files that should be moved to resource files for localization
- Add new resource entries to
src/Shared/Resources/AppStrings.resxif they don't already exist - Generate strongly-typed resource classes by running
dotnet build -t:PrepareResourcesin thesrc/Shareddirectory - Update the code to use
IStringLocalizer<AppStrings>andnameof(AppStrings.ResourceKey)pattern
Context
- Resource File Location:
src/Shared/Resources/AppStrings.resx - Components inherit from:
AppComponentBaseorAppPageBase(which haveIStringLocalizer<AppStrings> Localizeravailable) - Controllers inherit from:
AppControllerBase(which haveIStringLocalizer<AppStrings> Localizeravailable) - Other files:
AutoInjectIStringLocalizer<AppStrings>directly - Usage Pattern:
@Localizer[nameof(AppStrings.ResourceKey)]in Razor files,Localizer[nameof(AppStrings.ResourceKey)]in C# code
Rules
- Use descriptive but concise resource key names that describe the content or context
- Group related strings with common prefixes when appropriate (e.g.,
SignIn*,Email*,Password*) - Always use
nameof(AppStrings.ResourceKey)instead of string literals for resource keys - Preserve string formatting - if the original string has placeholders like
{0}, keep them in the resource value - Don't move:
- CSS class names or IDs
- Configuration keys
- API endpoints or URLs
- Technical constants (file extensions, mime types, etc.)
- Log messages
Workflow
- Analyze the provided code to identify hardcoded user-facing strings
- Check existing AppStrings.resx to see if suitable resource entries already exist
- Add new entries to AppStrings.resx for any missing resources using the XML format:
<data name="ResourceKeyName" xml:space="preserve"> <value>Resource Value Here</value> </data> - Run the resource generation command:
dotnet build -t:PrepareResourcesinsrc/Shareddirectory - Update the code files to use the localizer pattern
- Verify the build succeeds after all changes
Examples
Before:
<BitButton>Save Changes</BitButton>
<BitText>Welcome to our application!</BitText>
After (AppStrings.resx):
<data name="Save" xml:space="preserve">
<value>Save</value>
</data>
<data name="WelcomeMessage" xml:space="preserve">
<value>Welcome to our application!</value>
</data>
After (Razor file):
<BitButton>@Localizer[nameof(AppStrings.Save)]</BitButton>
<BitText>@Localizer[nameof(AppStrings.WelcomeMessage)]</BitText>
Now proceed to identify and move hardcoded strings in the selected code to the resource file following these guidelines.