Files
ResourceString.Net.Contract/Readme.md
2023-05-20 15:25:01 +02:00

8.5 KiB

ResourceString.Net

What is ResourceString.Net?

ResourceString.Net is a powerful .NET library that allows you to work with string resources in a type-safe manner. It leverages the resx file in your project and utilizes a c# source code generator to create a comprehensive API. With ResourceString.Net, you can handle resource strings as "multi-language strings" (see The ResourceString-Classes) instead of built-in strings. This provides the ability to switch languages during runtime without the need to rerun string factory methods. Additionally, ResourceString.Net ensures that formatted strings have methods with the correct number of expected parameters.

Installation and Setup Instructions

To incorporate ResourceString.Net into your .NET application, follow these simple steps:

  1. Install the NuGet package by executing the following command in the NuGet package manager or the dotnet CLI:
dotnet add package ResourceString.Net
  1. Once the package is installed, you can start using the APIs in your application.

Getting Started

To quickly get started with ResourceString.Net, follow the steps below:

  1. Run the following script to create a new project and a resource file:
dotnet new console --name MyTestConsoleApp
cd MyTestConsoleApp

dotnet add package "System.Resources.Extensions"
dotnet add package "ResourceString.Net"

echo "<?xml version='1.0' encoding='utf-8'?>
<root>
  <data name='Greetings'>
    <value>Hello {0}</value>
    <comment>0 = name</comment>
  </data>
  <data name='World' type='System.String'>
    <value>World</value>
  </data>
</root>
" > Resources.resx

echo "var message = MyTestConsoleApp.Resources.Greetings.From(
    MyTestConsoleApp.Resources.World
);

Console.WriteLine(message.Value);
" > Program.cs
  1. Add the following PropertyGroup to the MyTestConsoleApp.csproj file to enable ResourceString.Net to handle the project's resource file:
<PropertyGroup>
  <AdditionalFileItemNames>$(AdditionalFileItemNames);EmbeddedResource</AdditionalFileItemNames>
</PropertyGroup>
  1. Run the project using the following command:
dotnet run
# Expected output: Hello World

During compile time, the ResourceString.Net source code generator will automatically add the following code to the MyTestConsoleApp.csproj project:

using ResourceString.Net.Contract;
using System;
using System.Globalization;
using System.Resources;
using System.Threading;

namespace MyTestConsoleApp
{
  internal static class Resources
  {

      #region ResourceManager 

      private static readonly Type _Type = typeof(Resources);
    
      private static readonly Lazy<ResourceManager> _ResourceManager = new Lazy<ResourceManager>(
          () => new ResourceManager(_Type.FullName ?? string.Empty, _Type.Assembly),                   
          LazyThreadSafetyMode.PublicationOnly
      );

      public static ResourceManager ResourceManager => _ResourceManager.Value;

      #endregion // ResourceManager
  

      internal static class Greetings 
      {
          private static readonly Lazy<IResourceString> LazyFormat = new Lazy<IResourceString>(
              () => new ResourceManagerString("Greetings", ResourceManager, CultureInfo.CurrentCulture),
              LazyThreadSafetyMode.PublicationOnly
          );

          public static IResourceString Format => LazyFormat.Value;
          
          public static IResourceString From(IResourceString name) => new FormattedResourceString(
              Format, 
              name
          );
  
      } 
  
      #region World 

      private static readonly Lazy<IResourceString> LazyWorld = new Lazy<IResourceString>(
          () => new ResourceManagerString("World", ResourceManager, CultureInfo.CurrentCulture),
          LazyThreadSafetyMode.PublicationOnly
      );

      public static IResourceString World => LazyWorld.Value;

      #endregion // World 
  
  }
}

The ResourceString-Classes

IResourceString

  • Interface that defines the contract for resource strings.
  • Contains properties: Value, representing the string value, and GetValue(CultureInfo cultureInfo), for retrieving the value for a specific CultureInfo.

FormattedResourceString

  • Implements the IResourceString interface.
  • Represents a resource string with placeholders for parameters.
  • Allows for dynamic formatting of the string by providing a format and an array of parameters.
  • Formats the string by replacing the placeholders with the parameter values.

JoinedResourceString

  • Implements the IResourceString interface.
  • Represents a resource string that joins multiple elements with a separator.
  • Useful for constructing strings that involve concatenating multiple resource strings or literal strings together.
  • Allows customization of the separator between the elements.

LiteralString

  • Implements the IResourceString interface.
  • Represents a literal string resource.
  • Provides the actual string value as-is without any formatting or localization.
  • Can be used for static, non-localized strings.

ResourceManagerString

  • Implements the IResourceString interface.
  • Represents a resource string retrieved from a ResourceManager.
  • Provides access to resource strings stored in resx files or other resource sources.
  • Handles retrieving the localized value for the specified CultureInfo.

Great! Based on the provided code for the console app ResourceString.Net.App.Console, let's enhance the Readme.md file to include instructions on how to use the console app and generate a C# class based on a given resource file.

Console App: ResourceString.Net.App.Console

The ResourceString.Net project also provide a console app, ResourceString.Net.App.Console, which allows you to generate a C# class based on a given resource file. This can be useful for automating the creation of resource classes in your projects without usage of the source generator.

Usage

To use the console app, follow these steps:

  1. Build the console app from this source repository
  2. Open a command prompt or terminal.
  3. Navigate to the directory where the ResourceString.Net.App.Console executable is located.

Syntax

ResourceString.Net.App.Console <sourceFile> [namespaceString] [className]

Parameters

  • <sourceFile>: Required. The path to the resource file (e.g., Resources.resx) that you want to generate the C# class from.
  • [namespaceString] (optional): The namespace for the generated C# class. If not provided, the default value is "Properties".
  • [className] (optional): The name of the generated C# class. If not provided, the default value is "Resources".

Examples

Here are some examples of how to use the console app:

  • Generate a C# class named Resources.cs in the "Properties" namespace based on the Resources.resx file:

    ResourceString.Net.App.Console Resources.resx
    
  • Generate a C# class named MyResources.cs in the "MyNamespace" namespace based on the MyResources.resx file:

    ResourceString.Net.App.Console MyResources.resx MyNamespace MyResources
    

Output

The console app will generate the C# class code based on the provided resource file and output it to the console. You can redirect the output to a file if desired.

Third party packages

Package Version
Fody 6.7.0
ILMerge.Fody 1.24.0
Microsoft.CodeAnalysis.Analyzers 3.3.4
Microsoft.CodeAnalysis.CSharp 4.3.0
NETStandard.Library (Auto-referenced) 2.0.3
LanguageExt.Core 4.4.3
System.Resources.Extensions 7.0.0

Development Notes

Here are some useful aliases for running Nix commands with experimental features:

  • nixe: This alias runs the nix command with the experimental feature flag nix-command flakes.
  • nulock: This alias runs the nixe command with the argument run .#devTasks.updateNugetLock, which updates the NuGet lock file.
  • fllock: This alias runs the nixe command with the argument run .#devTasks.updateFlakeLock, which updates the Flake lock file.
  • ulock: This alias combines the nulock and fllock aliases to update both the NuGet and Flake lock files.

To load the alias.sh source file from the current folder, use the following command:

source ./alias.sh

By executing the command above, you'll make the aliases available for use in the current terminal session.