• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

RickStrahl/Westwind.Globalization: Database driven resource localization for .NE ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

RickStrahl/Westwind.Globalization

开源软件地址(OpenSource Url):

https://github.com/RickStrahl/Westwind.Globalization

开源编程语言(OpenSource Language):

C# 45.9%

开源软件介绍(OpenSource Introduction):

West Wind Globalization

Database Resource Localization for .NET

Westwind.Globalization (.NET Standard, .NET 4.5+):
NuGet

Westwind.Globalization.AspNetCore (.NET Core 3.1, 2.1):
NuGet

Westwind.Globalization.Web (.NET 4.5+):
NuGet

This library and tooling provides easy to use database resource managers and providers that allow you to use a database for storing localization resources. Unlike static Resx resources, database resources are dynamic, can be changed at runtime and are editable by multiple users at the same time. The custom resource managers, providers and ASP.NET Core StringLocalizers use the standard .NET resource infrastructure, so other than startup configuration there are no code changes when switching from using traditional Resx resources.

It's also possible to import resources into a database, edit them dynamically, and then export them back out into Resx and optionally strongly typed classes so your deployed applications can run with Resx resources, while you can use dynamic Database resources during development.

A rich, Web based resource editor is also provided that makes it easy to create resource content and translate it interactively in a running application where you can see resource changes immediately applied without recompilation. You can import and export Resx resources, generate strongly typed classes and serve resources to JavaScript applications using the database resources. Web Resource Editor

Quick Links

Requirements:

  • works .NET Standard 2.0/.NET Core 2.0 or .NET 4.5 or later
  • SQL Server 2008-2019, SQL Server Express, SQL Compact 4, MySql, SqLite
  • .NET Core Sample Project uses .NET Core 2.2 and needs VS 2019

.NET Version Support

Version 3.0 adds support for the 2.0 versions of .NET Standard, .NET Core and ASP.NET Core. The following versions are provided:

  • Westwind.Globalization (net45 and netstandard2.0)
    NuGet
  • Westwind.Globalization.AspNetCore (netstandard2.0)
    NuGet
  • Westwind.Globalization.Web (net45)
    NuGet
  • Westwind.Globalization.Sample (net45)
  • Westwind.Globalization.Sample.AspNetCore (netcore3.1+, netcore2.1+)

Installation

Installation is different depending on which version of .NET you are running under .NET Core and Full Framework use different project types and NuGet Packages for the Web support.

Limited non-Windows Support for Admin Features

The admin features of this package have not been fully ported to non-Windows platforms. Specifically, any of the RESX and Import Export features will not work on non-windows platforms currently. However runtime database access is fully functional.

For installation use NuGet.

To Install for .NET Core

Please read the installation instructions below to configure once you've installed the project. You will need to configure startup settings in order for the Db Providers to run.

PM> Install-Package Westwind.Globalization.AspNetCore

If you're not using a Web Project you can just use the base package:

PM> Install-Package Westwind.Globalization

ASP.NET Core Administration Web UI: Separate Download

Due to changes in NuGet support in .NET Core we can no longer package static HTML, CSS and JS as part of NuGet packages. As a result a separate download is required to add the Localization Admin UI. You can download it from:

Unzip the contents of the Zip file into your project folder root, which creates the ./wwwroot/LocalizationAdmin Web folder and adds related resources to ./Properties.

To Install on .NET Framework

Please read the Installation Section below or watch the Getting Started Video, which describes how to install the packages, configure the project, import existing resources.

PM> Install-Package Westwind.Globalization.Web.Starter

or if you don't want sample resources and a test page, simply use:

PM> Install-Package Westwind.Globalization.Web

If you're not using a Web Project or you're using MVC/Web API and don't need the Web Resource Editor you can just use the core package:

PM> Install-Package Westwind.Globalization

Resources:

Features

  • .NET Resources in Sql Server, SqlCe, MySql and SqLite
  • Injectable .NET Core StringLocalizers (ASP.NET Core)
  • ASP.NET Database ResourceProviders (ASP.NET/WebForms)
  • .NET ResourceManager (ASP.NET MVC,non-Web apps)
  • Uses standard .NET Resource infrastructure and caching
  • Or: Use our dynamic DbRes string based helper (works anywhere)
  • Interactive Web Resource Editor to edit Resources
  • Keyboard optimized resources editing
  • Translate text resources with Google or Bing
  • Use Markdown in your text resources
  • Import and export Resx resources
  • Generate strongly typed classes from the Db resources
  • Release and reload resources in running Web apps
  • Serve .NET Resources to JavaScript as JSON
  • Create your own custom DbResourceManagers
  • Directly access and manage DbResources with code

Because this library uses the standard .NET resource infrastructure using the DbResourceProvider or DbResourceManager requires no code changes from ResX resources, other than provider configuration in your .config file and potentially a few lines of startup code. You can import existing Resx resources and edit them interactively. Serve your resources either with the DbResourceProvider or DbResourceManager, or if you chose export them back out to Resx files for your final application code. Importing and exporting is a easily done from the Web admin interface or can be fired using code including as part of your build process.

Note: The database is accessed only once per ResourceSet and per Locale, using the standard .NET Resource caching architecture used in Resource Providers and Resource Managers, so database access and usage is minimal. You can use these Providers/Manager in MVC, WebForms and even in non Web applications.

Web Resource Editor

One of the main reasons people want to use Database resources rather than Resx resources is that it allows for dynamic updates of resources. Resx resources are static and compiled into an application and so are typically tied to the development process, while dynamic resources can be updated separately even after the application has been completed and deployed.

Since data is stored in a database it's easy to create editing front ends or programmatic tools that simply manipulate the database. This library ships with a Web interface that allows editing of resources interactively and an easy to use data API to update resources programmatically.

Web Resource Editor

Web Resource Translator Dialog

The resource editor is an easy way to localize resources interactively, but it's not the only way you can do this of course. Since you have access to the data API underneath it as well as the database itself, it's easy to create your own customized UI or data driven API that suits your application needs exactly.

Markdown Support The resource edit form allows you to optionally use Markdown for resource editing which in addition to localization makes it possible to use this libary as a basic CMS to manage user manageable content in your applications.

How the database Providers work

This library implements a custom .NET ResourceManager and ASP.NET ResourceProvider (for .NET 4.x) that are tied to a database provider interface (although you can implement non-data providers as well). This means you can access resources using the same mechanisms that you use with standard Resx Resources in your .NET applications. It also means although resources are initially loaded from the database for the first load of each ResourceSet. .NET then caches resources for each individual ResourceSet and locale the same way that Resx resources are read from the assembly resources and then cached.

The database is hit only for the first read of a given ResourceSet/Locale combination - not every resource access hits the database!

The DbResourceManager can be used in any type of .NET application using the DbRes or DbResInstance class methods, generated strongly typed classes, or using the Resource Manager directly. The DbResourceProvider classes can be used in ASP.NET applications - especially for WebForms with support for local and global resources, implicit resources and control meta tags. MVC applications typically use the ResourceManager with strongly typed resources or the DbRes classes or by exporting resources back into RESX.

Underneath the .NET providers lies a the Westwind.Globalization data access layer (IDbResourceDataManager) that provides the data interface to provide access to various providers. The default provider uses SQL Server as a data source with additional providers available for MySql, SqLite and SqlCompact. This API is accessed by the Resource Provider and Resource Manager implementations to read the resources from the database.

Additionally the API can be directly accessed to provide resource access, and the DbRes helper class provides very easy access to these resources using the DbRes.T() method which can be thought of as a high level translation method.

This interface is also directly accessible and allows your code as well as support code like the UI Web Resource editor to easily access and manipulate resources in real-time at runtime.

This library includes quite a proliferation of classes most of it due to the implementation requirements for the .NET providers which require implementation of a host of interface based classes for customization.

There are three distinct resource access mechanisms supported:

  • ASP.NET Resource Provider (best used with WebForms)
  • .NET Resource Manager and strongly typed resources (Non-Web apps, ASP.NET Core, classic MVC apps or anywhere where you already use Resx)
  • Direct Db Provider access using DbRes and DbResInstance helpers
    (easiest overall - works everywhere)

Running the Sample Application

To run the sample application you have to set up a database to provide the resources. The following assumes you are using the default configuration which uses SQL Server and a database named Localizations - you can change this via web.config settings (see the following section for more details).

  • Create a SQL Server/Express Database called Localizations
  • Make sure the Web User using has rights to create a Table in this DB
  • Open http://localhost:xxxxx/LocalizationAdmin/index.html in your browser
  • You'll get an error message like:
    ResourceLoadingFailed: Invalid Object Name Localizations
  • Use the Create Table button to create the Localizations table
  • Use Import or Export Resx button to import resources from the project into the db
  • Select Import Resources from the dropdown
  • Use the path of ~/Properties/ for Resx Import Folder
  • Click on the Import Resources button
  • You should now have all the sample and LocalizationForm resources in the db

Installation and Configuration

The easiest way to use this library in your own applications is to install the NuGet package into an ASP.NET application.

ASP.NET Core Packages

pm> Install-Package Westwind.Globalization.AspNetCore

@icon-info-circle Download the Localization Admin UI Files

Nuget no longer allows distribution of static content, so in order to use the Localization Admin UI you also need to download the resources for the Localization Admin UI if you want to integrate the Localization interface into your application.

Once you've downloaded the Localization Admin UI zip file, unzip the entire content into the project's root folder.

For non-Web applications or if you use only the DbRes based localization features, you can just install the base package.

pm> Install-Package Westwind.Globalization

ASP.NET Core integration works in combination with ASP.NET Core new Localization features. Westwind.Globalization builds on top of this, or you can just use its native features. West Wind Globalization supports:

  • IStringLocalizer DI via custom IDbResourceStringLocalizer
  • appSettings.json configuration (optional)

ASP.NET Core Configuration

Configuration can be accomplished in 3 ways:

  1. Using a standalone dbResourceConfiguration.json file
  2. Using appsettings.json in a DbResourceProvider section
  3. Additional ASP.NET Core IConfiguration functionality configured (ie. Environment variables, user secrets)
  4. Explicit configuration via AddWestwindGlobalization(opt => return true)

Configuration values are applied in the order listed, with later assignments over-writing earlier settings.

DbResourceConfiguration.json

You can create a standalone DbResourceConfiguration.json file for configuration that works both in full framework and .NET Core:

{
  "ResourceAccessMode": "DbResourceManager",
  "ConnectionString": "server=.;database=localizations;integrated security=true;",
  "DataProvider": "SqlServer",
  "ResourceTableName": "Localizations",
  "ResxExportProjectType": "Project",
  "ResxBaseFolder": "~/Properties/",
  "StronglyTypedGlobalResource": "~/Properties/Resources.cs",
  "ResourceBaseNamespace": "AppResources",
  "AddMissingResources": true,
  "LocalizationFormWebPath": "~/LocalizationAdmin/",
  "GoogleApiKey": "XXXfaSyDcvmGhGN7FlynP9QUZOLF8_4K8iF9ChWo",
  "BingClientId": "12345-4b99-47ed-be7e-caf733526020"
}

If this file exists configuration values are read from it.

@icon-warning Copy to Output Directory

If you want to use DbResourceConfiguration.json for configuration storage make sure you set the Copy to Output Directory option to Copy if newer or Copy always to ensure the file is copied into the published output folder.

ASP.NET Core IConfiguration

For ASP.NET Core operation Westwind.Globalization also registers the DbResourceConfiguration instance as IOptions<DbResourceConfiguration> which gives strongly typed access to the configuration via depedency injection.

This means you can use any configured configuration providers - most commonly:

  • appsettings.json using a DbResourceConfiguration object
  • Environment variables
  • User Secrets store

You can store configuration settings in appsettings.json like this:

{
  "Logging": {...},
  "DbResourceConfiguration": {
    "ResourceAccessMode": "DbResourceManager",
    "ConnectionString": "server=.;database=localizations;integrated security=true;",
    "DataProvider": "SqlServer",
    "ResourceTableName": "Localizations",
    "StronglyTypedGlobalResource": "~/Properties/Resources.cs",
    "ResourceBaseNamespace": "AppResources",
    "ResxExportProjectType": "Project",
    "ResxBaseFolder": "~/Properties/",
    "AddMissingResources": true,
    "LocalizationFormWebPath": "~/LocalizationAdmin/",
    "BingClientId": "12345-4b99-47ed-be7e-caf733526020",
    "GoogleApiKey": "XXXfaSyDcvmGhGN7FlynP9QUZOLF8_4K8iF9ChWo"
  }
}

If provided the appsettings.json file overrides DbResourceConfiguration.json.

We recommend you only use one of the files to avoid confusion. For ASP.NET Core projects we recommend you store settings in appsettings.json since that gives you dependency injection for IOptions<DbResourceConfiguration> as well as putting configuration settings into a well-known location.

Enabling West Wind Globalization in ASP.NET Core

You also need to explicitly enable localization features in ASP.NET Core using the following code in the Startup.cs file's ConfigureServices() method:

public void ConfigureServices(IServiceCollection services)
{
    // Standard ASP.NET Localization features are recommended
    // Make sure this is done FIRST!
    services.AddLocalization(options =>
    {
        // I prefer Properties over the default `Resources` folder
        // due to namespace issues if you have a Resources type as
        // most people do for shared resources.
        options.ResourcesPath = "Properties";
    });
    

    // Replace StringLocalizers with Db Resource Implementation
    services.AddSingleton(typeof(IStringLocalizerFactory), 
                          typeof(DbResStringLocalizerFactory));
    services.AddSingleton(typeof(IHtmlLocalizerFactory),
                          typeof(DbResHtmlLocalizerFactory));
                          
    
    // Required: Enable Westwind.Globalization (opt parm is optional)
    // shown here with optional manual configuration code
    services.AddWestwindGlobalization(opt =>
    {                
        // the default settings comme from DbResourceConfiguration.json if exists
        // you can override the settings here, the config you create is added
        // to the DI system (DbResourceConfiguration)

        // Resource Mode - from Database (or Resx for serving from Resources)
        opt.ResourceAccessMode = ResourceAccessMode.DbResourceManager;  // .Resx
        
        // Make sure the database you connect to exists
        opt.ConnectionString = "server=.;database=localizations;uid=localizations;pwd=local";
        
        // Database provider used - Sql Server is the default
        opt.DataProvider = DbResourceProviderTypes.SqlServer;

        // The table in which resources are stored
        opt.ResourceTableName = "localizations";
        
        opt.AddMissingResources = false;
        opt.ResxBaseFolder = "~/Properties/";

        // Set up security for Localization Administration form
        opt.ConfigureAuthorizeLocalizationAdministration(actionContext =>
        {
            // return true or false whether this request is authorized
            return true;   //actionContext.HttpContext.User.Identity.IsAuthenticated;
        });

    });

    ...
    
    // .NET Core 2.x
    // services.AddMvc()
    //         .AddViewLocalization()
    //         .AddDataAnnotationsLocalization();
    //         .AddApplicationPart(typeof(DbResViewLocalizer).Assembly);
    
    // .NET Core 3.1
    services.AddMvc(opt =>  
        // required for the Administration interface for dynamic serialization
        .AddNewtonsoftJson();
        // for MVC/RazorPages localization
        .AddViewLocalization()
        // for ViewModel Error Annotation Localization
        .AddDataAnnotationsLocalization();

    // this *has to go here* after view localization has been initialized
    // so that Pages can localize - note required even if you're not using
    // the DbResource manager.
    services.AddTransient<IViewLocalizer, DbResViewLocalizer>();
}

Any code changes made override any of the file values. You can also replace the entire DbResourceConfiguration object entirely in this handler.

In addition you probablywant to add standard ASP.NET Core Localization features to the Configure() method in Startup.cs:

public void Configure(IApplicationBuilder app) 
{
    ..
  
    var supportedCultures = new[]
    {
        new CultureInfo("en-US"),
        new CultureInfo("en"),
        new CultureInfo("de-DE"),
        new CultureInfo("de"),
        new CultureInfo("fr")
    };
    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en-US"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures                 
    });
    
    ..
    
    // .NET Core 3.1
    app.UseRouting();

    app.UseDefaultFiles();
    app.UseStaticFiles();

    // .NET Core 3.1 required for Endpoints
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapDefaultControllerRoute();
    });
    
    // .NET Core 2.x only needs this
    //app.UseMvc()
}

Note

Dependency Injection for DbResourceConfiguration

You can get access to DbResourceConfiguration in a number of ways:

  • Via DI by asking for DbResourceConfiguration
  • Via DI by asking for IOptions<DbResourceConfig> (if loaded through IConfiguration)
  • Static DbResourceConfiguration.Curr

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap