meta info

Export localized resources from DB to RESX

By Ziya Mollamahmut

The ability to export resources provides flexibility in switching between different resource types, and ease of work on localization by exporting resources to any custom format using custom exporters. The built-in exporters supports exporting from XML to RESX, but you can implement your own exporter to any format.

How to use the built-in DB-to-RESX exporter

Inject IDbResourceExporter and call the export method. Below is a razor page sample;

Required XLocalizer.DB

public class ExportModel : PageModel
{
    private readonly IDbResourceExporter _exporter;
    private readonly ILogger _logger;
    
    public ExportModel(IDbResourceExporter exporter, ILogger<ExportModel> logger)
    {
        _exporter = exporter;
        _logger = logger;
    }

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync(string culture, bool approvedOnly, bool overwrite)
    {
        var totalExported = await _exporter.ExportToResxAsync<LocSource>(culture, approvedOnly, overwrite);

        _logger.LogInformation($"Total {totalExported} resources exported.");

        return Page();
    }
}

How to create custom resource exporter

Create a new class that implements IDbResourceExporter and register it in startup.

public class CustomResourceExporter : IDbResourceExporter
{
    public CustomResourceExporter() 
    {
        // ...
    }

    public async Task<int> ExportToResxAsync<TResource>(string culture, bool approvedOnly, bool overwriteExistingKeys)
            where TResource : class
    {
        // ...
    }

    public async Task<int> ExportToResxAsync(Type type, string culture, bool approvedOnly, bool overwriteExistingKeys)
    {
        // ...
    }
}

Register in startup:

services.AddTransient<IDbResourceExporter, CustomResourceExporter>();

See the built-in DB resource exporter source code: EFDbResourceExporter

Export method parameters

  • TResource / type: Type of resource file
  • culture: The culture to export its resources
  • approvedOnly: Export only resources with approved translations. Auto translated xml resources has the attribute isActive set to false by default.
  • overwriteExistingKeys: Over write existing resources if any...