Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ycanardeau/ResXGenerator
ResXGenerator is a C# source generator to generate strongly-typed resource classes for looking up localized strings.
https://github.com/ycanardeau/ResXGenerator
csharp-sourcegenerator
Last synced: 3 months ago
JSON representation
ResXGenerator is a C# source generator to generate strongly-typed resource classes for looking up localized strings.
- Host: GitHub
- URL: https://github.com/ycanardeau/ResXGenerator
- Owner: ycanardeau
- License: mit
- Created: 2023-04-23T01:02:07.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-05-15T09:33:33.000Z (6 months ago)
- Last Synced: 2024-05-16T00:08:33.882Z (6 months ago)
- Topics: csharp-sourcegenerator
- Language: C#
- Homepage: https://www.nuget.org/packages/Aigamo.ResXGenerator
- Size: 220 KB
- Stars: 24
- Watchers: 2
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- RSCG_Examples - https://github.com/ycanardeau/ResXGenerator
- csharp-source-generators - ResXGenerator - ![stars](https://img.shields.io/github/stars/ycanardeau/ResXGenerator?style=flat-square&cacheSeconds=604800) ![last commit](https://img.shields.io/github/last-commit/ycanardeau/ResXGenerator?style=flat-square&cacheSeconds=86400) Generates strongly-typed resource classes for looking up localized strings. (Source Generators / Localization)
README
# ResXGenerator
ResXGenerator is a C# source generator to generate strongly-typed resource classes for looking up localized strings.
NOTE: This is an independent fork of VocaDb/ResXFileCodeGenerator.
## Usage
Install the `Aigamo.ResXGenerator` package:
```psl
dotnet add package Aigamo.ResXGenerator
```Generated source from [ActivityEntrySortRuleNames.resx](https://github.com/VocaDB/vocadb/blob/6ac18dd2981f82100c8c99566537e4916920219e/VocaDbWeb.Resources/App_GlobalResources/ActivityEntrySortRuleNames.resx):
```cs
// ------------------------------------------------------------------------------
//
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// ------------------------------------------------------------------------------
#nullable enable
namespace Resources
{
using System.Globalization;
using System.Resources;public static class ActivityEntrySortRuleNames
{
private static ResourceManager? s_resourceManager;
public static ResourceManager ResourceManager => s_resourceManager ??= new ResourceManager("VocaDb.Web.App_GlobalResources.ActivityEntrySortRuleNames", typeof(ActivityEntrySortRuleNames).Assembly);
public static CultureInfo? CultureInfo { get; set; }///
/// Looks up a localized string similar to Oldest.
///
public static string? CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo);///
/// Looks up a localized string similar to Newest.
///
public static string? CreateDateDescending => ResourceManager.GetString(nameof(CreateDateDescending), CultureInfo);
}
}
```## New in version 3
- The generator now utilizes the IIncrementalGenerator API to instantly update the generated code, thus giving you instant intellisense.
- Added error handling for multiple members of same name, and members that have same name as class. These are clickable in visual studio to lead you to the source of the error, unlike before where they resulted in broken builds and you had to figure out why.
- Namespace naming fixed for resx files in the top level folder.
- Resx files can now be named with multiple extensions, e.g. myresources.cshtml.resx and will result in class being called myresources.
- Added the ability to generate inner classes, partial outer classes and non-static members. Very useful if you want to ensure that only a particular class can use those resources instead of being spread around the codebase.
- Use same 'Link' setting as msbuild uses to determine embedded file name.
- Can set a class postfix name
## New in version 3.1
- The generator can now generate code to lookup translations instead of using the 20 year old System.Resources.ResourceManager
## Options
### PublicClass (per file or globally)
Use cases: https://github.com/VocaDB/ResXFileCodeGenerator/issues/2.
Since version 2.0.0, ResXGenerator generates internal classes by default. You can change this behavior by setting `PublicClass` to `true`.
```xml
true
```
or
```xml
```
If you want to apply this globally, use
```xml
true
```
### NullForgivingOperators (globally)
Use cases: https://github.com/VocaDB/ResXFileCodeGenerator/issues/1.
```xml
true
```
By setting `ResXGenerator_NullForgivingOperators` to `true`, ResXGenerator generates
```cs
public static string CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo)!;
```instead of
```cs
public static string? CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo);
```### Non-static classes (per file or globally)
To use generated resources with [Microsoft.Extensions.Localization](https://docs.microsoft.com/en-us/dotnet/core/extensions/localization) `IStringLocalizer` and resource manager, the resolved type cannot be a static class. You can disable default behavior per file by setting the value to `false`.
```xml
false
```
or globally
```xml
false
```
With global non-static class you can also reset `StaticClass` per file by setting the value to anything but `false`.
### Partial classes (per file or globally)
To extend an existing class, you can make your classes partial.
```xml
true
```
or globally
```xml
true
```
### Static Members (per file or globally)
In some rare cases it might be useful for the members to be non-static.
```xml
false
```
or globally
```xml
false
```
### Postfix class name (per file or globally)
In some cases the it is useful if the name of the generated class doesn't follow the filename.
A clear example is Razor pages that always generates a class for the code-behind named "-Model".
This example configuration allows you to use Resources.MyResource in your model, or @Model.Resources.MyResource in your cshtml file.```xml
Model
false
false
true
true
public
false
Resources
_Resources
```
or just the postfix globally
```xml
Model
```
## Inner classes (per file or globally)
If your resx files are organized along with code files, it can be quite useful to ensure that the resources are not accessible outside the specific class the resx file belong to.
```xml
$([System.String]::Copy('%(FileName).cs'))
MyResources
private
EveryoneLikeMyNaming
false
false
true
$([System.IO.Path]::GetFileNameWithoutExtension('%(FileName)')).resx
```
or globally
```xml
MyResources
private
EveryoneLikeMyNaming
false
false
true```
This example would generate files like this:
```cs
// ------------------------------------------------------------------------------
//
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// ------------------------------------------------------------------------------
#nullable enable
namespace Resources
{
using System.Globalization;
using System.Resources;public partial class ActivityEntryModel
{
public MyResources EveryoneLikeMyNaming { get; } = new();private class MyResources
{
private static ResourceManager? s_resourceManager;
public static ResourceManager ResourceManager => s_resourceManager ??= new ResourceManager("VocaDb.Web.App_GlobalResources.ActivityEntryModel", typeof(ActivityEntryModel).Assembly);
public CultureInfo? CultureInfo { get; set; }///
/// Looks up a localized string similar to Oldest.
///
public string? CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo);///
/// Looks up a localized string similar to Newest.
///
public string? CreateDateDescending => ResourceManager.GetString(nameof(CreateDateDescending), CultureInfo);
}
}
}
```### Inner Class Visibility (per file or globally)
By default inner classes are not generated, unless this setting is one of the following:
- Public
- Internal
- Private
- Protected
- SameAsOuterCase is ignored, so you could use "private".
It is also possible to use "NotGenerated" to override on a file if the global setting is to generate inner classes.
```xml
private
```
or globally
```xml
private
```
### Inner Class name (per file or globally)
By default the inner class is named "Resources", which can be overridden with this setting:
```xml
MyResources
```
or globally
```xml
MyResources
```
### Inner Class instance name (per file or globally)
By default no instance is available of the class, but that can be made available if this setting is given.
```xml
EveryoneLikeMyNaming
```
or globally
```xml
EveryoneLikeMyNaming
```
For brevity, settings to make everything non-static is omitted.
### Generate Code (per file or globally)
By default the ancient `System.Resources.ResourceManager` is used.
Benefits of using `System.Resources.ResourceManager`:
- Supports custom `CultureInfo`
- Languages are only loaded the first time a language is referenced
- Only use memory for the languages used
- Can ship satellite dlls separatelyDisadvantages of using `System.Resources.ResourceManager`
- The satellite dlls are always lazy loaded, so cold start penalty is high
- Satellite dlls requires that you can scan the dir for which files are available, which can cause issues in some project types
- Loading a satellite dll takes way more memory than just loading the respective strings
- Build time for .resources -> satellite dll can be quite slow (~150msec per file)
- Linker optimization doesn't work, since it cannot know which resources are referencedBenefits of using `GenerateCode` code generation:
- All languages are placed in the main dll, no more satellite dlls
- Lookup speed is ~600% faster (5ns vs 33ns)
- Zero allocations
- Very small code footprint (about 10 bytes per language, instead of including the entire `System.Resources`)
- Very fast build time
- Because all code is referencing the strings directly, the linker can see which strings are actually used and which are not.
- No cold start penalty
- Smaller combined size of dll (up to 50%, since it doesn't need to store the keys for every single language)Disadvantages of using `GenerateCode` code generation
- Since `CultureInfo` are pre-computed, custom `CultureInfo` are not supported (or rather, they always return the default language)
- Cannot lookup "all" keys (unless using reflection)
- Main dll size increased since it contains all language strings (sometimes, the compiler can pack code strings much better than resource strings and it doesn't need to store the keys)Notice, it is required to set `GenerateResource` to false for all resx files to prevent the built-in resgen.exe from running.
```xml
true
false
```
or globally
```xml
true
false
```
If you get build error MSB3030, add this to your csproj to prevent it from trying to copy satellite dlls that no longer exists
```xml
```
## Resource file namespaces
Linked resources namespace follow `Link` if it is set. The `Link` setting is also used by msbuild built-in 'resgen.exe' to determine the embedded filename.
Use-case: Linking `.resx` files from outside source (e.g. generated in a localization sub-module by translators) and expose them as "Resources" namespace.
```xml
Resources\%(FileName)%(Extension)
true
false
$([System.IO.Path]::GetFilenameWithoutExtension([System.String]::Copy('%(FileName)'))).resx
```
You can also use the `TargetPath` to just overwrite the namespace
```xml
Resources\%(FileName)%(Extension)
true
false
$([System.IO.Path]::GetFilenameWithoutExtension([System.String]::Copy('%(FileName)'))).resx
```
It is also possible to set the namespace using the `CustomToolNamespace` setting. Unlike the `Link` and `TargetPath`, which will prepend the assemblies namespace and includes the filename, the `CustomToolNamespace` is taken verbatim.
```xml
MyNamespace.AllMyResourcesAreBelongToYouNamespace
```
## Excluding resx files
Individual resx files can also be excluded from being processed by setting the `SkipFile` metadata to true.
```xml
true
```
Alternatively it can be set with the attribute `SkipFile="true"`.
```xml
```
## References
- [Introducing C# Source Generators | .NET Blog](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/)
- [microsoft/CsWin32: A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.](https://github.com/microsoft/cswin32)
- [kenkendk/mdresxfilecodegenerator: Resx Designer Generator](https://github.com/kenkendk/mdresxfilecodegenerator)
- [dotnet/ResXResourceManager: Manage localization of all ResX-Based resources in one central place.](https://github.com/dotnet/ResXResourceManager)
- [roslyn/source-generators.cookbook.md at master · dotnet/roslyn](https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md)
- [roslyn/Using Additional Files.md at master · dotnet/roslyn](https://github.com/dotnet/roslyn/blob/master/docs/analyzers/Using%20Additional%20Files.md)
- [ufcpp - YouTube](https://www.youtube.com/channel/UCY-z_9mau6X-Vr4gk2aWtMQ)
- [amis92/csharp-source-generators: A list of C# Source Generators (not necessarily awesome) and associated resources: articles, talks, demos.](https://github.com/amis92/csharp-source-generators)
- [A NuGet package workflow using GitHub Actions | by Andrew Craven | Medium](https://acraven.medium.com/a-nuget-package-workflow-using-github-actions-7da8c6557863)