├── .gitattributes
├── .gitignore
├── Images
└── ExampleLoggingLog.png
├── LICENSE.txt
├── LocalizeMessagesAndErrors
├── DefaultLocalizer.cs
├── DefaultLocalizerFactory.cs
├── DefaultLocalizerOptions.cs
├── IDefaultLocalizer.Generic.cs
├── IDefaultLocalizer.cs
├── IDefaultLocalizerFactory.cs
├── ISimpleLocalizer.cs
├── ISimpleLocalizerFactory.cs
├── IStatusGenericLocalizer.Generic.cs
├── IStatusGenericLocalizer.cs
├── LocalizeKeyClass.cs
├── LocalizeKeyExtensions.cs
├── LocalizeMessagesAndErrors.csproj
├── LocalizeMessagesAndErrorsNuGetIcon.png
├── LocalizeSetClassNameAttribute.cs
├── LocalizedLog.cs
├── NameExtension.cs
├── RegisterLocalizeExtensions.cs
├── SimpleLocalizer.cs
├── SimpleLocalizerFactory.cs
├── SimpleLocalizerOptions.cs
├── StatusGenericLocalizer.Generic.cs
├── StatusGenericLocalizer.cs
├── StubDefaultLocalizerFactory.cs
└── UnitTestingCode
│ ├── StubDefaultLocalizer.Generic.cs
│ ├── StubDefaultLocalizer.cs
│ ├── StubSimpleLocalizer.cs
│ ├── StubStringLocalizer.Generic.cs
│ ├── StubStringLocalizer.cs
│ └── StubStringLocalizerFactory.cs
├── LocalizedWebApp
├── Controllers
│ ├── DefaultLocalizerController.cs
│ ├── HomeController.cs
│ ├── StatusGenericLocalizerController.cs
│ └── StringLocalizerController.cs
├── LocalizedWebApp.csproj
├── Models
│ ├── CreateDateDto.cs
│ └── ErrorViewModel.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Resources
│ ├── Controllers.HomeController.en.resx
│ └── Controllers.HomeController.fr.resx
├── Views
│ ├── DefaultLocalizer
│ │ ├── Index.cshtml
│ │ ├── MissingResourceEntry.cshtml
│ │ └── StringMessage.cshtml
│ ├── Home
│ │ ├── Index.cshtml
│ │ └── Privacy.cshtml
│ ├── Shared
│ │ ├── Error.cshtml
│ │ ├── _Layout.cshtml
│ │ ├── _Layout.cshtml.css
│ │ └── _ValidationScriptsPartial.cshtml
│ ├── StatusGenericLocalizer
│ │ ├── CheckNull.cshtml
│ │ ├── CreateDate.cshtml
│ │ └── Index.cshtml
│ ├── StringLocalizer
│ │ ├── Index.cshtml
│ │ ├── MissingResourceEntry.cshtml
│ │ └── StringMessage.cshtml
│ ├── _ViewImports.cshtml
│ └── _ViewStart.cshtml
├── appsettings.Development.json
├── appsettings.json
└── wwwroot
│ ├── css
│ └── site.css
│ ├── favicon.ico
│ ├── js
│ └── site.js
│ └── lib
│ ├── bootstrap
│ ├── LICENSE
│ └── dist
│ │ ├── css
│ │ ├── bootstrap-grid.css
│ │ ├── bootstrap-grid.css.map
│ │ ├── bootstrap-grid.min.css
│ │ ├── bootstrap-grid.min.css.map
│ │ ├── bootstrap-grid.rtl.css
│ │ ├── bootstrap-grid.rtl.css.map
│ │ ├── bootstrap-grid.rtl.min.css
│ │ ├── bootstrap-grid.rtl.min.css.map
│ │ ├── bootstrap-reboot.css
│ │ ├── bootstrap-reboot.css.map
│ │ ├── bootstrap-reboot.min.css
│ │ ├── bootstrap-reboot.min.css.map
│ │ ├── bootstrap-reboot.rtl.css
│ │ ├── bootstrap-reboot.rtl.css.map
│ │ ├── bootstrap-reboot.rtl.min.css
│ │ ├── bootstrap-reboot.rtl.min.css.map
│ │ ├── bootstrap-utilities.css
│ │ ├── bootstrap-utilities.css.map
│ │ ├── bootstrap-utilities.min.css
│ │ ├── bootstrap-utilities.min.css.map
│ │ ├── bootstrap-utilities.rtl.css
│ │ ├── bootstrap-utilities.rtl.css.map
│ │ ├── bootstrap-utilities.rtl.min.css
│ │ ├── bootstrap-utilities.rtl.min.css.map
│ │ ├── bootstrap.css
│ │ ├── bootstrap.css.map
│ │ ├── bootstrap.min.css
│ │ ├── bootstrap.min.css.map
│ │ ├── bootstrap.rtl.css
│ │ ├── bootstrap.rtl.css.map
│ │ ├── bootstrap.rtl.min.css
│ │ └── bootstrap.rtl.min.css.map
│ │ └── js
│ │ ├── bootstrap.bundle.js
│ │ ├── bootstrap.bundle.js.map
│ │ ├── bootstrap.bundle.min.js
│ │ ├── bootstrap.bundle.min.js.map
│ │ ├── bootstrap.esm.js
│ │ ├── bootstrap.esm.js.map
│ │ ├── bootstrap.esm.min.js
│ │ ├── bootstrap.esm.min.js.map
│ │ ├── bootstrap.js
│ │ ├── bootstrap.js.map
│ │ ├── bootstrap.min.js
│ │ └── bootstrap.min.js.map
│ ├── jquery-validation-unobtrusive
│ ├── LICENSE.txt
│ ├── jquery.validate.unobtrusive.js
│ └── jquery.validate.unobtrusive.min.js
│ ├── jquery-validation
│ ├── LICENSE.md
│ └── dist
│ │ ├── additional-methods.js
│ │ ├── additional-methods.min.js
│ │ ├── jquery.validate.js
│ │ └── jquery.validate.min.js
│ └── jquery
│ ├── LICENSE.txt
│ └── dist
│ ├── jquery.js
│ ├── jquery.min.js
│ └── jquery.min.map
├── Net.LocalizeMessagesAndErrors.sln
├── README.md
├── ReleaseNotes.md
├── ServiceLayer
├── ExamplesOfStatusGenericsLoc.cs
└── ServiceLayer.csproj
└── Test
├── StubClasses
├── StubDefaultLocalizerOptions.cs
├── StubLocalizeDefaultWithLogging.Generic.cs
├── StubLocalizeDefaultWithLogging.cs
└── StubSimpleLocalizerOptions.cs
├── Test.csproj
├── UnitCommands
└── LocalizationCaptureCommands.cs
├── UnitTests
├── TestDefaultLocalizerController.cs
├── TestDefaultLocalizerFactory.cs
├── TestExamplesOfStatusGenericsLoc.cs
├── TestLocalizeFormattedMessage.cs
├── TestLocalizeKeyExtensions.cs
├── TestLocalizeStringMessage.cs
├── TestNameExtension.cs
├── TestRegisterLocalizeExtensions.cs
├── TestSimpleLocalizer.cs
├── TestSimpleLocalizerFactory.cs
├── TestStatusGenericLocalizer.cs
├── TestStatusGenericLocalizerGeneric.cs
└── TestStubLocalizeDefaultWithLogging.cs
└── appsettings.json
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/Images/ExampleLoggingLog.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JonPSmith/Net.LocalizeMessagesAndErrors/4020b2326ed7ff3af35f12ca6dc8ae4f61df934f/Images/ExampleLoggingLog.png
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [2022] [Selective Analytics Ltd.]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/DefaultLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 |
5 | using System.Collections.Concurrent;
6 | using System.Reflection;
7 | using LocalizeMessagesAndErrors.UnitTestingCode;
8 | using Microsoft.Extensions.DependencyInjection;
9 | using Microsoft.Extensions.Localization;
10 | using Microsoft.Extensions.Logging;
11 |
12 | namespace LocalizeMessagesAndErrors;
13 |
14 | ///
15 | /// This allows you to create a when your resource class is
16 | /// no known on startup.
17 | ///
18 | public class DefaultLocalizerFactory : IDefaultLocalizerFactory
19 | {
20 | private static readonly ConcurrentDictionary CreateCache = new ();
21 |
22 | private readonly IServiceProvider _serviceProvider;
23 |
24 | ///
25 | /// ctor
26 | ///
27 | ///
28 | public DefaultLocalizerFactory(IServiceProvider serviceProvider)
29 | {
30 | _serviceProvider = serviceProvider;
31 | }
32 |
33 | ///
34 | /// This with create a linked to the TResource type
35 | ///
36 | /// type of the resource class defining the localization resource files
37 | ///
38 | ///
39 | public IDefaultLocalizer Create(Type resourceSource)
40 | {
41 | if (resourceSource == null)
42 | //If the resourceSource is null (which means DefaultLocalizer isn't set up), then return a stub version
43 | return new StubDefaultLocalizer();
44 |
45 | var localizeFactory = _serviceProvider.GetService();
46 |
47 | if (localizeFactory == null)
48 | //If the localizeFactory is null (which means that StringLocalizer isn't configured), then return a stub version
49 | return new StubDefaultLocalizer();
50 |
51 | var options = _serviceProvider.GetService();
52 | if (options == null)
53 | throw new NullReferenceException(
54 | $"This failed because you haven't registered the {nameof(IDefaultLocalizer)} service.");
55 |
56 | return CreateCache.GetOrAdd(resourceSource, newValue =>
57 | CreateDefaultLocalizer(resourceSource, localizeFactory, options));
58 | }
59 |
60 | ///
61 | /// This creates the service with the correct resource type
62 | ///
63 | ///
64 | ///
65 | ///
66 | ///
67 | private IDefaultLocalizer CreateDefaultLocalizer(Type resourceSource, IStringLocalizerFactory localizeFactory,
68 | DefaultLocalizerOptions options)
69 | {
70 | var stringLocalizer = localizeFactory.Create(resourceSource);
71 | var defaultLocalizerType = typeof(DefaultLocalizer<>).MakeGenericType(resourceSource);
72 | var loggerFactory = _serviceProvider.GetRequiredService();
73 | var logger = loggerFactory.CreateLogger(defaultLocalizerType);
74 | var defaultLocalizer = Activator.CreateInstance(defaultLocalizerType,
75 | BindingFlags.Instance | BindingFlags.NonPublic, null,
76 | new object[] { options, stringLocalizer, logger }, null);
77 | return defaultLocalizer as IDefaultLocalizer;
78 | }
79 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/DefaultLocalizerOptions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This contains the options that the needs to work.
8 | ///
9 | public class DefaultLocalizerOptions
10 | {
11 | ///
12 | /// This holds the culture of the messages provided
13 | ///
14 | public string DefaultCulture { get; set; }
15 |
16 | ///
17 | /// This defines what cultures are supported. This is used to
18 | /// log a warning when supported resource file entry isn't found.
19 | ///
20 | public string[] SupportedCultures { get; set; }
21 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/IDefaultLocalizer.Generic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This is the interface for the class
8 | ///
9 | ///
10 | public interface IDefaultLocalizer : IDefaultLocalizer
11 | {
12 |
13 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/IDefaultLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This is the interface for the service
8 | /// when used in
9 | ///
10 | public interface IDefaultLocalizer
11 | {
12 | ///
13 | /// This is a localization adapter that allows you to have readable messages in your code via strings,
14 | /// e.g. "This is my message".
15 | ///
16 | /// This contains the localizeData and the calling class to log errors with a logger containing the called class.
17 | /// This contains your default message for the culture defined in the .
18 | ///
19 | ///
20 | string LocalizeStringMessage(LocalizeKeyData localizeKey, string message);
21 |
22 | ///
23 | /// This is a localization adapter that allows you to have readable messages in your code using
24 | /// s to allow you to provide dynamic values in the message, e.g. $"The time is {DateTime.Now:T}"
25 | ///
26 | /// This is the key for finding the localized message in your respective resources / cultures.
27 | /// This is the default message for the culture defined in the .
28 | /// This takes one or more s. and concatenates them into one message.
29 | /// This allowed you to have multiple s to handle long messages.
30 | ///
31 | ///
32 | ///
33 | string LocalizeFormattedMessage(LocalizeKeyData localizeKey, params FormattableString[] formattableStrings);
34 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/IDefaultLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This allows you to create a when your resource class is
8 | /// no known on startup.
9 | ///
10 | public interface IDefaultLocalizerFactory
11 | {
12 | ///
13 | /// This with create a linked to the TResource type
14 | ///
15 | /// type of the resource class defining the localization resource files
16 | ///
17 | ///
18 | IDefaultLocalizer Create(Type resourceSource);
19 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/ISimpleLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | namespace LocalizeMessagesAndErrors;
7 |
8 | ///
9 | /// Interface for simple localizer
10 | ///
11 | public interface ISimpleLocalizer
12 | {
13 | ///
14 | /// This provides the given message based on the culture give when registering the service
15 | /// If the current culture matches the register's culture, then the given message is returned.
16 | /// If the current culture does NOT match the register's culture, then it will look up
17 | /// in the resource file defined by the resource type give when registering the service
18 | /// using a localize key in the form {}_{message}
19 | ///
20 | /// The message to show when the app's culture matches
21 | /// The type of the class / struct you are calling from.
22 | /// DO NOT use. This a filled by the calling method name
23 | /// DO NOT use. This a filled by the calling line number
24 | /// localized string
25 | string LocalizeString(string message, TThis callingClass,
26 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0);
27 |
28 | ///
29 | /// This provides the given message based on the culture give when registering the service
30 | /// If the current culture matches the register's culture, then the given message is returned.
31 | /// If the current culture does NOT match the register's culture, then it will look up
32 | /// in the resource file defined by the resource type give when registering the service
33 | /// using a localize key in the form {}_{message}
34 | ///
35 | /// The formattable message to show when the app's culture matches
36 | /// The type of the class / struct you are calling from.
37 | /// DO NOT use. This a filled by the calling method name
38 | /// DO NOT use. This a filled by the calling line number
39 | /// localized string
40 | string LocalizeFormatted(FormattableString formatted, TThis callingClass,
41 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0);
42 |
43 | ///
44 | /// This is useful when working in static methods or where it hard to obtain this.
45 | /// It provides the given message based on the culture give when registering the service
46 | /// If the current culture matches the register's culture, then the given message is returned.
47 | /// If the current culture does NOT match the register's culture, then it will look up
48 | /// in the resource file defined by the resource type give when registering the service
49 | /// using a localize key in the form {}_{message}
50 | ///
51 | /// The message to show when the app's culture matches
52 | /// The type of the class / struct you are calling from
53 | /// DO NOT use. This a filled by the calling method name
54 | /// DO NOT use. This a filled by the calling line number
55 | /// localized string
56 | string StaticLocalizeString(string message, Type callingClassType,
57 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0);
58 |
59 | ///
60 | /// This is useful when working in static methods or where it hard to obtain this.
61 | /// It provides the given message based on the culture give when registering the service
62 | /// If the current culture matches the register's culture, then the given message is returned.
63 | /// If the current culture does NOT match the register's culture, then it will look up
64 | /// in the resource file defined by the resource type give when registering the service
65 | /// using a localize key in the form {}_{message}
66 | ///
67 | /// The formattable message to show when the app's culture matches
68 | /// The type of the class / struct you are calling from
69 | /// DO NOT use. This a filled by the calling method name
70 | /// DO NOT use. This a filled by the calling line number
71 | /// localized string
72 | string StaticLocalizeFormatted(FormattableString formatted, Type callingClassType,
73 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0);
74 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/ISimpleLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This allows you to create a using a resource type
8 | /// provided by you at runtime.
9 | ///
10 | public interface ISimpleLocalizerFactory
11 | {
12 | ///
13 | /// This with create a linked to the TResource type
14 | ///
15 | /// type of the resource class defining the localization resource files
16 | ///
17 | ///
18 | ISimpleLocalizer Create(Type resourceSource);
19 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/IStatusGenericLocalizer.Generic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using StatusGeneric;
5 |
6 | namespace LocalizeMessagesAndErrors;
7 |
8 | ///
9 | /// This is a version of that contains a result.
10 | /// Useful if you want to return something with the status.
11 | ///
12 | ///
13 | public interface IStatusGenericLocalizer : IStatusGeneric
14 | {
15 | ///
16 | /// This contains the return result, or if there are errors it will return default(T)
17 | ///
18 | T Result { get; }
19 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/IStatusGenericLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.ComponentModel.DataAnnotations;
5 | using StatusGeneric;
6 |
7 | namespace LocalizeMessagesAndErrors;
8 |
9 | ///
10 | /// Interface for the
11 | ///
12 | public interface IStatusGenericLocalizer : IStatusGeneric
13 | {
14 | ///
15 | /// This adds an error to the status using a string. Don't use this if you have dynamic values in the message.
16 | ///
17 | /// This is the key for finding the localized error in your respective resources / cultures.
18 | /// The error message in the language / culture you defined when creating the
19 | /// StatusGenericLocalizer.
20 | /// optional. A list of property names that this error applies to
21 | /// The StatusGenericLocalizer to allow fluent method calls.
22 | IStatusGeneric AddErrorString(LocalizeKeyData localizeKey, string errorMessage,
23 | params string[] propertyNames);
24 |
25 | ///
26 | /// This adds an error to the status using a s, when you don't have and properties
27 | /// to add to the . Using allows you to place dynamic
28 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
29 | ///
30 | /// This is the key for finding the localized error in your respective resources / cultures.
31 | /// The error messages in the language / culture you defined when creating the
32 | /// StatusGenericLocalizer. NOTE: this allows multiple s to handle long messages.
33 | /// The StatusGenericLocalizer to allow fluent method calls.
34 | IStatusGeneric AddErrorFormatted(LocalizeKeyData localizeKey, params FormattableString[] errorMessages);
35 |
36 | ///
37 | /// This adds an error to the status using a s, when you don't have and properties
38 | /// to add to the . Using allows you to place dynamic
39 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
40 | ///
41 | /// This is the key for finding the localized error in your respective resources / cultures.
42 | /// The error message in the language / culture you defined when creating the
43 | /// StatusGenericLocalizer.
44 | /// optional. A list of property names that this error applies to
45 | /// The StatusGenericLocalizer to allow fluent method calls.
46 | IStatusGeneric AddErrorFormattedWithParams(LocalizeKeyData localizeKey, FormattableString errorMessage,
47 | params string[] propertyNames);
48 |
49 | ///
50 | /// This adds an error to the status using a s, when you don't have and properties
51 | /// to add to the . Using allows you to place dynamic
52 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
53 | ///
54 | /// This is the key for finding the localized error in your respective resources / cultures.
55 | /// This is an array of containing the error message i
56 | /// n the language / culture you defined when creating the StatusGenericLocalizer.
57 | /// NOTE: this allows multiple s to handle long messages.
58 | /// optional. A list of property names that this error applies to
59 | /// The StatusGenericLocalizer to allow fluent method calls.
60 | IStatusGeneric AddErrorFormattedWithParams(LocalizeKeyData localizeKey,
61 | FormattableString[] errorMessages, params string[] propertyNames);
62 |
63 | ///
64 | /// This allows you to set the with a localized string.
65 | ///
66 | /// This is the key for finding the localized message in your respective resources / cultures.
67 | /// string that can be localized to set the property
68 | IStatusGeneric SetMessageString(LocalizeKeyData localizeKey, string message);
69 |
70 | ///
71 | /// This allows you to set the with localized FormattableStrings.
72 | /// NOTE: this allows multiple s to handle long messages.
73 | ///
74 | /// This is the key for finding the localized message in your respective resources / cultures.
75 | /// A array of s that can be localized to
76 | /// set the property
77 | /// This takes one or more s. and concatenates them into one message.
78 | /// This allowed you to have multiple s to handle long messages.
79 | ///
80 | IStatusGeneric SetMessageFormatted(LocalizeKeyData localizeKey, params FormattableString[] formattableStrings);
81 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/LocalizeKeyClass.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This contains the parts to make a unique localize key for a message.
8 | /// It also holds information on where the message was added. This allows you to
9 | /// collect this information when running your unit tests
10 | ///
11 | public class LocalizeKeyData
12 | {
13 | ///
14 | /// ctor
15 | ///
16 | /// The unique localizeKey for a message/
17 | ///
18 | ///
19 | ///
20 | public LocalizeKeyData(string localizeKey, Type callingClass, string methodName, int sourceLineNumber)
21 | {
22 | LocalizeKey = localizeKey;
23 | CallingClass = callingClass;
24 | MethodName = methodName;
25 | SourceLineNumber = sourceLineNumber;
26 | }
27 |
28 | ///
29 | /// This contains the localization key for this message.
30 | ///
31 | public string LocalizeKey { get; }
32 |
33 | ///
34 | /// This contains a name that defines a Class of which the message was sent from.
35 | /// This is used to collect information during your unit tests on what localization resource you need
36 | ///
37 | public Type CallingClass { get; }
38 |
39 | ///
40 | /// This contains the name of the method in which the message was sent from.
41 | /// This is used to collect information during your unit tests on what localization resource you need
42 | ///
43 | public string MethodName { get; }
44 |
45 | ///
46 | /// This contains the line number where the LocalizeKeyExtensions were called.
47 | /// This is used to collect information during your unit tests on what localization resource you need
48 | ///
49 | public int SourceLineNumber { get; }
50 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/LocalizeMessagesAndErrors.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | README.md
7 | true
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | Net.LocalizeMessagesAndErrors
19 | 9.0.0
20 | 9.0.0
21 | Jon P Smith
22 | Provides extra features to .NET Localization that make it easier to add multiple languages to your app.
23 | false
24 |
25 | - .NET 9 version
26 |
27 | Copyright (c) 2022 Jon P Smith. Licenced under MIT licence
28 | Localization, Multilingual, Globalization, Status
29 | true
30 | true
31 | https://github.com/JonPSmith/Net.LocalizeMessagesAndErrors
32 | https://github.com/JonPSmith/Net.LocalizeMessagesAndErrors
33 | LocalizeMessagesAndErrorsNuGetIcon.png
34 | MIT
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/LocalizeMessagesAndErrorsNuGetIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JonPSmith/Net.LocalizeMessagesAndErrors/4020b2326ed7ff3af35f12ca6dc8ae4f61df934f/LocalizeMessagesAndErrors/LocalizeMessagesAndErrorsNuGetIcon.png
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/LocalizeSetClassNameAttribute.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This is used to provide a unique name instead of the fullname of a class, struct or interface
8 | /// if the nameIsUnique parameter in is false. Useful to make a unique localizeKey that is shorter.
9 | ///
10 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
11 | public class LocalizeSetClassNameAttribute : Attribute
12 | {
13 | ///
14 | /// ctor: define the replacement name of the class
15 | ///
16 | ///
17 | public LocalizeSetClassNameAttribute(string classUniqueName)
18 | {
19 | ClassUniqueName = classUniqueName;
20 | }
21 |
22 | ///
23 | /// Contains the replacement name of the class
24 | ///
25 | public string ClassUniqueName { get; }
26 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/LocalizedLog.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This class is used by the StubLocalizeDefaultLocalizerWithLogging found in
8 | /// https://github.com/JonPSmith/Net.LocalizeMessagesAndErrors/blob/main/Test/StubClasses
9 | /// which provides a way to capture information on each localized message.
10 | /// NOTE: The StubLocalizeDefaultLocalizerWithLogging isn't in the library because it uses EF Core,
11 | /// which is not needed in this library.
12 | ///
13 | public class LocalizedLog
14 | {
15 | private LocalizedLog()
16 | {
17 | } //Needed by EF Core
18 |
19 | ///
20 | /// ctor
21 | ///
22 | ///
23 | ///
24 | ///
25 | ///
26 | ///
27 | ///
28 | ///
29 | ///
30 | public LocalizedLog(Type resourceClass, string localizeKey, string cultureOfMessage,
31 | string actualMessage, string? messageFormat, string callingClassName, string callingMethodName,
32 | int sourceLineNumber)
33 | {
34 | ResourceClassFullName = resourceClass.FullName!;
35 | LocalizeKey = localizeKey;
36 | CultureOfMessage = cultureOfMessage;
37 | ActualMessage = actualMessage;
38 | MessageFormat = messageFormat;
39 | CallingClassName = callingClassName;
40 | CallingMethodName = callingMethodName;
41 | SourceLineNumber = sourceLineNumber;
42 | }
43 |
44 | ///
45 | /// Key
46 | ///
47 | public int Id { get; set; }
48 |
49 | ///
50 | /// The FullName of the resource class you used in localization code
51 | ///
52 | public string ResourceClassFullName { get; set; }
53 |
54 | ///
55 | /// This is the string that is used to match the resource file "Name" of the localized message
56 | ///
57 | public string LocalizeKey { get; set; }
58 |
59 | ///
60 | /// This contains the culture of the default message
61 | ///
62 | public string CultureOfMessage { get; set; }
63 |
64 | ///
65 | /// This contains the actual message
66 | ///
67 | public string ActualMessage { get; set; }
68 |
69 | ///
70 | /// If the has dynamic parts, then this contains the Format, otherwise null
71 | ///
72 | public string MessageFormat { get; set; }
73 |
74 | ///
75 | /// This will contain a string if:
76 | /// 1. It finds the same key, but different format
77 | /// 2. It find the same format, but different keys
78 | /// If no problems, then it is null
79 | ///
80 | public string PossibleErrors { get; set; }
81 |
82 | ///
83 | /// The name of the class where the LocalizeKey was created
84 | ///
85 | public string CallingClassName { get; set; }
86 |
87 | ///
88 | /// This contains the name of the method / member that created the LocalizeKey
89 | ///
90 | public string CallingMethodName { get; set; }
91 |
92 | ///
93 | /// This has the source line of where the LocalizeKey was created
94 | ///
95 | public int SourceLineNumber { get; set; }
96 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/NameExtension.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// Simple extension method to improve error feedback in ASP.NET Core
8 | ///
9 | public static class NameExtension
10 | {
11 | ///
12 | /// This converts a camel-cased string to Pascal-case
13 | /// This is used to convert method names into the name used in a class
14 | ///
15 | ///
16 | ///
17 | public static string CamelToPascal(this string name)
18 | {
19 | if (name == null) throw new ArgumentNullException(nameof(name));
20 |
21 | return name.Length == 0 ? "" : char.ToUpper(name[0]) + name.Substring(1);
22 | }
23 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/RegisterLocalizeExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace LocalizeMessagesAndErrors;
7 |
8 | ///
9 | /// Extension methods to register the and the
10 | ///
11 | public static class RegisterLocalizeExtensions
12 | {
13 | ///
14 | /// This registers the service. This service can handle multiple
15 | /// resource files.
16 | ///
17 | ///
18 | /// This defines the language of the messages you provide.
19 | /// Provide list of supported cultures. This is used to only log
20 | /// missing resource entries if its supported culture.
21 | /// 1. If null, then it will log every missing culture.
22 | /// 2. If empty array, then will not log any missing resource entries.
23 | ///
24 | public static IServiceCollection RegisterDefaultLocalizer(this IServiceCollection services,
25 | string defaultCulture, string[] supportedCultures)
26 | {
27 | if (string.IsNullOrWhiteSpace(defaultCulture))
28 | throw new ArgumentException("The DefaultCulture must be set to the culture of the default messages.", nameof(defaultCulture));
29 |
30 | services.AddSingleton(new DefaultLocalizerOptions
31 | {
32 | DefaultCulture = defaultCulture,
33 | SupportedCultures = supportedCultures
34 | });
35 | services.AddSingleton(typeof(IDefaultLocalizer<>), typeof(DefaultLocalizer<>));
36 | services.AddTransient();
37 | return services;
38 | }
39 |
40 | ///
41 | /// This registers the service.
42 | /// NOTE: You must have registered the service via the
43 | /// extension method to make the
44 | /// service work.
45 | ///
46 | /// This defines the start of the resource files that this service
47 | /// will use to look up localized languages.
48 | ///
49 | /// Use this to alter options in the class.
50 | ///
51 | public static IServiceCollection RegisterSimpleLocalizer(this IServiceCollection services,
52 | Action options = null)
53 | {
54 | var localOptions = new SimpleLocalizerOptions
55 | {
56 | ResourceType = typeof(TResource),
57 | };
58 | options?.Invoke(localOptions);
59 | if (localOptions.ResourceType == null) throw new ArgumentNullException(nameof(SimpleLocalizerOptions.ResourceType));
60 |
61 | services.AddSingleton(serviceProvider =>
62 | new SimpleLocalizer(serviceProvider.GetRequiredService(), localOptions));
63 | services.AddTransient();
64 | return services;
65 | }
66 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/SimpleLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | namespace LocalizeMessagesAndErrors;
7 |
8 | ///
9 | /// This is a simple localizer to handle simple messages, such as button names etc.
10 | /// It uses the message as part of the localize key.
11 | /// The limitation is this localizer are:
12 | /// 1. It only uses the one resource file for all of the localizations, which you define on registration.
13 | /// 2. The localize key is based on the message, i.e. {}_{message}
14 | ///
15 | public class SimpleLocalizer : ISimpleLocalizer
16 | {
17 | private readonly IDefaultLocalizer _localizerDefault;
18 | private readonly SimpleLocalizerOptions _options;
19 |
20 | ///
21 | /// This ctor will create the service
22 | /// using the resourceType that you provide.
23 | ///
24 | ///
25 | ///
26 | ///
27 | public SimpleLocalizer(IDefaultLocalizerFactory defaultLocalizerFactory, SimpleLocalizerOptions options)
28 | {
29 | if (options.ResourceType == null) throw new ArgumentNullException(nameof(options.ResourceType));
30 | _options = options;
31 |
32 | _localizerDefault = defaultLocalizerFactory.Create(options.ResourceType);
33 | }
34 |
35 | ///
36 | /// This provides the given message based on the culture give when registering the service
37 | /// If the current culture matches the register's culture, then the given message is returned.
38 | /// If the current culture does NOT match the register's culture, then it will look up
39 | /// in the resource file defined by the resource type give when registering the service
40 | /// using a localize key in the form {}_{message}
41 | ///
42 | /// The message to show when the app's culture matches
43 | /// The type of the class / struct you are calling from.
44 | /// DO NOT use. This a filled by the calling method name
45 | /// DO NOT use. This a filled by the calling line number
46 | /// localized string
47 | public string LocalizeString(string message, TThis callingClass,
48 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
49 | {
50 | return _localizerDefault.LocalizeStringMessage(
51 | FormLocalizeKey(message).JustThisLocalizeKey(callingClass, memberName, sourceLineNumber), message);
52 | }
53 |
54 | ///
55 | /// This provides the given message based on the culture give when registering the service
56 | /// If the current culture matches the register's culture, then the given message is returned.
57 | /// If the current culture does NOT match the register's culture, then it will look up
58 | /// in the resource file defined by the resource type give when registering the service
59 | /// using a localize key in the form {}_{message}
60 | ///
61 | /// The formattable message to show when the app's culture matches
62 | /// The type of the class / struct you are calling from.
63 | /// DO NOT use. This a filled by the calling method name
64 | /// DO NOT use. This a filled by the calling line number
65 | /// localized string
66 | public string LocalizeFormatted(FormattableString formatted, TThis callingClass,
67 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
68 | {
69 | return _localizerDefault.LocalizeFormattedMessage(
70 | FormLocalizeKey(formatted.Format).JustThisLocalizeKey(
71 | callingClass, memberName, sourceLineNumber), formatted);
72 | }
73 |
74 | ///
75 | /// This is useful when working in static methods or where it hard to obtain this.
76 | /// It provides the given message based on the culture give when registering the service
77 | /// If the current culture matches the register's culture, then the given message is returned.
78 | /// If the current culture does NOT match the register's culture, then it will look up
79 | /// in the resource file defined by the resource type give when registering the service
80 | /// using a localize key in the form {}_{message}
81 | ///
82 | /// The message to show when the app's culture matches
83 | /// The type of the class / struct you are calling from
84 | /// DO NOT use. This a filled by the calling method name
85 | /// DO NOT use. This a filled by the calling line number
86 | /// localized string
87 | public string StaticLocalizeString(string message, Type callingClassType,
88 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
89 | {
90 | return _localizerDefault.LocalizeStringMessage(
91 | FormLocalizeKey(message).StaticJustThisLocalizeKey(
92 | callingClassType, memberName, sourceLineNumber), message);
93 | }
94 |
95 | ///
96 | /// This is useful when working in static methods or where it hard to obtain this.
97 | /// It provides the given message based on the culture give when registering the service
98 | /// If the current culture matches the register's culture, then the given message is returned.
99 | /// If the current culture does NOT match the register's culture, then it will look up
100 | /// in the resource file defined by the resource type give when registering the service
101 | /// using a localize key in the form {}_{message}
102 | ///
103 | /// The formattable message to show when the app's culture matches
104 | /// The type of the class / struct you are calling from
105 | /// DO NOT use. This a filled by the calling method name
106 | /// DO NOT use. This a filled by the calling line number
107 | /// localized string
108 | public string StaticLocalizeFormatted(FormattableString formatted, Type callingClassType,
109 | [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
110 | {
111 | return _localizerDefault.LocalizeFormattedMessage(
112 | FormLocalizeKey(formatted.Format).StaticJustThisLocalizeKey(
113 | callingClassType, memberName, sourceLineNumber), formatted);
114 | }
115 |
116 | private string FormLocalizeKey(string message)
117 | {
118 | return _options.PrefixKeyString == null
119 | ? message
120 | : $"{_options.PrefixKeyString}({message})";
121 | }
122 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/SimpleLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Collections.Concurrent;
5 | using LocalizeMessagesAndErrors.UnitTestingCode;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Microsoft.Extensions.Localization;
8 |
9 | namespace LocalizeMessagesAndErrors;
10 |
11 | ///
12 | /// This allows you to create a using a resource type
13 | /// provided by you at runtime.
14 | ///
15 | public class SimpleLocalizerFactory : ISimpleLocalizerFactory
16 | {
17 | private static readonly ConcurrentDictionary CreateCache = new ();
18 |
19 | ///
20 | /// This is used if there is no localization or null resource
21 | ///
22 | private static readonly ISimpleLocalizer StubSimpleLocalizer = new StubSimpleLocalizer();
23 |
24 | private readonly IServiceProvider _serviceProvider;
25 |
26 | ///
27 | /// ctor
28 | ///
29 | ///
30 | public SimpleLocalizerFactory(IServiceProvider serviceProvider)
31 | {
32 | _serviceProvider = serviceProvider;
33 | }
34 |
35 | ///
36 | /// This with create a linked to the TResource type
37 | ///
38 | /// type of the resource class defining the localization resource files
39 | ///
40 | ///
41 | public ISimpleLocalizer Create(Type resourceSource)
42 | {
43 | var options = new SimpleLocalizerOptions { ResourceType = resourceSource };
44 | if (resourceSource == null)
45 | //If the resourceSource is null (which means DefaultLocalizer isn't set up), then return a stub version
46 | return StubSimpleLocalizer;
47 |
48 | var localizeFactory = _serviceProvider.GetService();
49 |
50 | if (localizeFactory == null)
51 | //If the localizeFactory is null (which means that StringLocalizer isn't configured), then return a stub version
52 | return StubSimpleLocalizer;
53 |
54 | return CreateCache.GetOrAdd(resourceSource, newValue =>
55 | new SimpleLocalizer(new DefaultLocalizerFactory(_serviceProvider), options));
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/SimpleLocalizerOptions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors;
5 |
6 | ///
7 | /// This contains the options that the needs to work.
8 | ///
9 | public class SimpleLocalizerOptions
10 | {
11 | ///
12 | /// THis holds the type used to define the start of the resource file name holding the different languages
13 | ///
14 | public Type ResourceType { get; set; }
15 |
16 | ///
17 | /// This holds a string which prefixes the localize key, i.e. $"{PrefixKeyString}({message})"
18 | /// If null, then just the message is used as the localize key, i.e. "message"
19 | ///
20 | public string PrefixKeyString { get; set; } = "SimpleLocalizer";
21 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/StatusGenericLocalizer.Generic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 |
5 | using StatusGeneric;
6 | using System.ComponentModel.DataAnnotations;
7 |
8 | namespace LocalizeMessagesAndErrors;
9 |
10 | ///
11 | /// This contains the error handling part of the GenericBizRunner
12 | ///
13 | public class StatusGenericLocalizer : StatusGenericLocalizer, IStatusGeneric
14 | {
15 | private readonly IDefaultLocalizer _defaultLocalizer;
16 |
17 | private TReturn _result;
18 |
19 | ///
20 | /// Constructor to set up the StatusGenericLocalizer with Result
21 | ///
22 | /// Uses the to handle the localization.
23 | ///
24 | public StatusGenericLocalizer(IDefaultLocalizer defaultLocalizer)
25 | : base(defaultLocalizer)
26 | {
27 | _defaultLocalizer = defaultLocalizer;
28 | }
29 |
30 | ///
31 | /// This is the returned result
32 | ///
33 | public TReturn Result => IsValid ? _result : default;
34 |
35 | ///
36 | /// This sets the result to be returned
37 | ///
38 | ///
39 | ///
40 | public IStatusGeneric SetResult(TReturn result)
41 | {
42 | _result = result;
43 | return this;
44 | }
45 |
46 | ///
47 | /// This adds an error to the status using a string. Don't use this if you have dynamic values in the message.
48 | ///
49 | /// This is a key for the localized message in the respective resource / culture.
50 | /// If null, then the message won't get localized
51 | /// The error message in the language / culture you defined when creating the
52 | /// StatusGenericLocalizer.
53 | /// optional. A list of property names that this error applies to
54 | /// The StatusGenericLocalizer to allow fluent method calls.
55 | public new IStatusGeneric AddErrorString(LocalizeKeyData localizeKey, string errorMessage,
56 | params string[] propertyNames)
57 | {
58 | var errorString = _defaultLocalizer.LocalizeStringMessage(localizeKey, errorMessage);
59 | _errors.Add(new ErrorGeneric(Header, new ValidationResult(errorString, propertyNames)));
60 | return this;
61 | }
62 |
63 | ///
64 | /// This adds an error to the status using a s, when you don't have and properties
65 | /// to add to the . Using allows you to place dynamic
66 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
67 | ///
68 | /// This is a key for the localized message in the respective resource / culture.
69 | /// If null, then the message won't get localized
70 | /// The error messages in the language / culture you defined when creating the
71 | /// StatusGenericLocalizer. NOTE: this allows multiple s to handle long messages.
72 | /// The StatusGenericLocalizer to allow fluent method calls.
73 | public new IStatusGeneric AddErrorFormatted(LocalizeKeyData localizeKey,
74 | params FormattableString[] errorMessages)
75 | {
76 | var errorString = _defaultLocalizer.LocalizeFormattedMessage(localizeKey, errorMessages);
77 | _errors.Add(new ErrorGeneric(Header, new ValidationResult(errorString)));
78 | return this;
79 | }
80 |
81 | ///
82 | /// This adds an error to the status using a s, when you don't have and properties
83 | /// to add to the . Using allows you to place dynamic
84 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
85 | ///
86 | /// This is a key for the localized message in the respective resource / culture.
87 | /// If null, then the message won't get localized
88 | /// The error message in the language / culture you defined when creating the
89 | /// StatusGenericLocalizer.
90 | /// optional. A list of property names that this error applies to
91 | /// The StatusGenericLocalizer to allow fluent method calls.
92 | public new IStatusGeneric AddErrorFormattedWithParams(LocalizeKeyData localizeKey,
93 | FormattableString errorMessage,
94 | params string[] propertyNames)
95 | {
96 | var errorString = _defaultLocalizer.LocalizeFormattedMessage(localizeKey, errorMessage);
97 | _errors.Add(new ErrorGeneric(Header, new ValidationResult(errorString, propertyNames)));
98 | return this;
99 | }
100 |
101 | ///
102 | /// This adds an error to the status using a s, when you don't have and properties
103 | /// to add to the . Using allows you to place dynamic
104 | /// values (e.g. $"The time is {DateTime.Now:T}") that are also sent to the localizer.
105 | ///
106 | /// This is a key for the localized message in the respective resource / culture.
107 | /// If null, then the message won't get localized
108 | /// This is an array of containing the error message i
109 | /// n the language / culture you defined when creating the StatusGenericLocalizer.
110 | /// NOTE: this allows multiple s to handle long messages.
111 | /// optional. A list of property names that this error applies to
112 | /// The StatusGenericLocalizer to allow fluent method calls.
113 | public new IStatusGeneric AddErrorFormattedWithParams(LocalizeKeyData localizeKey,
114 | FormattableString[] errorMessages, params string[] propertyNames)
115 | {
116 | var errorString = _defaultLocalizer.LocalizeFormattedMessage(localizeKey, errorMessages);
117 | _errors.Add(new ErrorGeneric(Header, new ValidationResult(errorString, propertyNames)));
118 | return this;
119 | }
120 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/StubDefaultLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using LocalizeMessagesAndErrors.UnitTestingCode;
5 |
6 | namespace LocalizeMessagesAndErrors;
7 |
8 | ///
9 | /// This is used to test the
10 | ///
11 | public class StubDefaultLocalizerFactory : IDefaultLocalizerFactory
12 | {
13 | ///
14 | /// Ctor: provide a stub
15 | ///
16 | ///
17 | public StubDefaultLocalizerFactory(StubDefaultLocalizer stubDefaultLocalizer)
18 | {
19 | StubDefaultLocalizer = stubDefaultLocalizer;
20 | }
21 |
22 | ///
23 | /// This allows you to access the
24 | ///
25 | public StubDefaultLocalizer StubDefaultLocalizer { get; }
26 |
27 | ///
28 | /// This with create a linked to the TResource type
29 | ///
30 | /// type of the resource class defining the localization resource files
31 | ///
32 | ///
33 | public IDefaultLocalizer Create(Type resourceSource)
34 | {
35 | return StubDefaultLocalizer;
36 | }
37 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubDefaultLocalizer.Generic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using Microsoft.Extensions.Localization;
5 |
6 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
7 |
8 | ///
9 | /// This is a replacement for the service
10 | /// which allows you to provide a dictionary to mimic the resource files.
11 | /// Its very simple, and only uses the name of the localization, and not the culture, to lookup value.
12 | ///
13 | ///
14 | public class StubDefaultLocalizer : StubDefaultLocalizer
15 | {
16 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubDefaultLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
5 |
6 | ///
7 | /// This stub simply returns the default message. Used in
8 | /// if .NET localization is not set up.
9 | ///
10 | public class StubDefaultLocalizer : IDefaultLocalizer
11 | {
12 | ///
13 | /// This holds the of the last localize call
14 | ///
15 | public LocalizeKeyData LastKeyData { get; set; }
16 |
17 | ///
18 | /// Returns the default string
19 | ///
20 | ///
21 | ///
22 | ///
23 | public string LocalizeStringMessage(LocalizeKeyData localizeKey, string message)
24 | {
25 | LastKeyData = localizeKey;
26 | return message;
27 | }
28 |
29 | ///
30 | /// Returns the default formatted string
31 | ///
32 | ///
33 | ///
34 | ///
35 | public string LocalizeFormattedMessage(LocalizeKeyData localizeKey,
36 | params FormattableString[] formattableStrings)
37 | {
38 | LastKeyData = localizeKey;
39 | return string.Join(string.Empty, formattableStrings.Select(x => x.ToString()).ToArray());
40 | }
41 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubSimpleLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 |
5 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
6 |
7 | ///
8 | /// This stub simply returns the default message. Used in
9 | /// if .NET localization is not set up and in unit testing.
10 | ///
11 | public class StubSimpleLocalizer : ISimpleLocalizer
12 | {
13 | public StubSimpleLocalizer(string prefixKeyString = "SimpleLocalizer")
14 | {
15 | PrefixKeyString = prefixKeyString;
16 | }
17 |
18 | ///
19 | /// This holds a string which prefixes the localize key, i.e. $"{PrefixKeyString}({message})"
20 | /// If null, then just the message is used as the localize key, i.e. "message"
21 | ///
22 | private string PrefixKeyString { get; set; }
23 |
24 | ///
25 | /// This holds the of the last localize call
26 | ///
27 | public LocalizeKeyData LastKeyData { get; set; }
28 |
29 | ///
30 | /// This provides the given message based on the culture give when registering the service
31 | /// If the current culture matches the register's culture, then the given message is returned.
32 | /// If the current culture does NOT match the register's culture, then it will look up
33 | /// in the resource file defined by the resource type give when registering the service
34 | /// using a localize key in the form {}_{message}
35 | ///
36 | /// The message to show when the app's culture matches
37 | /// The type of the class / struct you are calling from.
38 | /// DO NOT use. This a filled by the calling method name
39 | /// DO NOT use. This a filled by the calling line number
40 | /// localized string
41 | public string LocalizeString(string message, TThis callingClass, string memberName = "", int sourceLineNumber = 0)
42 | {
43 | LastKeyData = new LocalizeKeyData(FormLocalizeKey(message), callingClass.GetType(),
44 | memberName, sourceLineNumber);
45 | return message;
46 | }
47 |
48 | ///
49 | /// This provides the given message based on the culture give when registering the service
50 | /// If the current culture matches the register's culture, then the given message is returned.
51 | /// If the current culture does NOT match the register's culture, then it will look up
52 | /// in the resource file defined by the resource type give when registering the service
53 | /// using a localize key in the form {}_{message}
54 | ///
55 | /// The formattable message to show when the app's culture matches
56 | /// The type of the class / struct you are calling from.
57 | /// DO NOT use. This a filled by the calling method name
58 | /// DO NOT use. This a filled by the calling line number
59 | /// localized string
60 | public string LocalizeFormatted(FormattableString formatted, TThis callingClass, string memberName = "",
61 | int sourceLineNumber = 0)
62 | {
63 | LastKeyData = new LocalizeKeyData(FormLocalizeKey(formatted.ToString()),
64 | callingClass.GetType(), memberName, sourceLineNumber);
65 | return formatted.ToString();
66 | }
67 |
68 | ///
69 | /// This is useful when working in static methods or where it hard to obtain this.
70 | /// It provides the given message based on the culture give when registering the service
71 | /// If the current culture matches the register's culture, then the given message is returned.
72 | /// If the current culture does NOT match the register's culture, then it will look up
73 | /// in the resource file defined by the resource type give when registering the service
74 | /// using a localize key in the form {}_{message}
75 | ///
76 | /// The message to show when the app's culture matches
77 | /// The type of the class / struct you are calling from
78 | /// DO NOT use. This a filled by the calling method name
79 | /// DO NOT use. This a filled by the calling line number
80 | /// localized string
81 | public string StaticLocalizeString(string message, Type callingClassType, string memberName = "", int sourceLineNumber = 0)
82 | {
83 | LastKeyData = new LocalizeKeyData(FormLocalizeKey(message), callingClassType,
84 | memberName, sourceLineNumber);
85 | return message;
86 | }
87 |
88 | ///
89 | /// This is useful when working in static methods or where it hard to obtain this.
90 | /// It provides the given message based on the culture give when registering the service
91 | /// If the current culture matches the register's culture, then the given message is returned.
92 | /// If the current culture does NOT match the register's culture, then it will look up
93 | /// in the resource file defined by the resource type give when registering the service
94 | /// using a localize key in the form {}_{message}
95 | ///
96 | /// The formattable message to show when the app's culture matches
97 | /// The type of the class / struct you are calling from
98 | /// DO NOT use. This a filled by the calling method name
99 | /// DO NOT use. This a filled by the calling line number
100 | /// localized string
101 | public string StaticLocalizeFormatted(FormattableString formatted, Type callingClassType, string memberName = "",
102 | int sourceLineNumber = 0)
103 | {
104 | LastKeyData = new LocalizeKeyData(FormLocalizeKey(formatted.ToString()),
105 | callingClassType, memberName, sourceLineNumber);
106 | return formatted.ToString();
107 | }
108 |
109 | private string FormLocalizeKey(string message)
110 | {
111 | return PrefixKeyString == null
112 | ? message
113 | : $"{PrefixKeyString}({message})";
114 | }
115 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubStringLocalizer.Generic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using Microsoft.Extensions.Localization;
5 |
6 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
7 |
8 | ///
9 | /// This is a replacement for the service
10 | /// which allows you to provide a dictionary to mimic the resource files.
11 | /// Its very simple, and only uses the name of the localization, and not the culture, to lookup value.
12 | ///
13 | ///
14 | public class StubStringLocalizer : StubStringLocalizer, IStringLocalizer
15 | {
16 | ///
17 | /// This allows you to provide the localized name + value entries you would
18 | ///
19 | ///
20 | /// If name not found, then throw exception. Defaults onto true
21 | ///
22 | public StubStringLocalizer(Dictionary resource, bool throwExceptionIfNoEntry = true)
23 | : base(resource, throwExceptionIfNoEntry)
24 | {
25 | }
26 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubStringLocalizer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using Microsoft.Extensions.Localization;
5 |
6 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
7 |
8 | ///
9 | /// This is a replacement for the service
10 | /// which allows you to provide a dictionary to mimic the resource files.
11 | /// Its very simple, and only uses the name of the localization, and not the culture, to lookup value.
12 | ///
13 | public class StubStringLocalizer : IStringLocalizer
14 | {
15 | ///
16 | /// This allows you to provide the localized name + value entries to return
17 | ///
18 | ///
19 | /// If name not found, then throw exception. Defaults onto true
20 | ///
21 | public StubStringLocalizer(Dictionary resource, bool throwExceptionIfNoEntry = true)
22 | {
23 | Resource = resource ?? new Dictionary();
24 | ThrowExceptionIfNoEntry = throwExceptionIfNoEntry;
25 | }
26 |
27 | ///
28 | /// Useful if you want to access the name / value you added to this class
29 | ///
30 | public Dictionary Resource { get; set; }
31 |
32 | ///
33 | /// The last LocalizeKey
34 | ///
35 | public string LastLocalizeKey { get; private set; }
36 |
37 | ///
38 | /// If true, then throw exception if no entry
39 | ///
40 | public bool ThrowExceptionIfNoEntry { get; set; }
41 |
42 | /// Gets all string resources.
43 | ///
44 | /// A indicating whether to include strings from parent cultures.
45 | ///
46 | /// The strings.
47 | public IEnumerable GetAllStrings(bool includeParentCultures)
48 | {
49 | return Resource.Select(x => new LocalizedString(x.Key, x.Value));
50 | }
51 |
52 | /// Gets the string resource with the given name.
53 | /// The name of the string resource.
54 | /// The string resource as a .
55 | public LocalizedString this[string name]
56 | {
57 | get
58 | {
59 | LastLocalizeKey = name;
60 | if (Resource.ContainsKey(name))
61 | {
62 | return new LocalizedString(name, Resource[name], false, "dummy searched location");
63 | }
64 |
65 | if (ThrowExceptionIfNoEntry)
66 | throw new MissingFieldException($"There was no entry with the name '{name} in the dictionary.");
67 |
68 | return new LocalizedString(name, "", true, "dummy searched location");
69 | }
70 | }
71 |
72 | ///
73 | /// Gets the string resource with the given name and formatted with the supplied arguments.
74 | ///
75 | /// The name of the string resource.
76 | /// The values to format the string with.
77 | /// The formatted string resource as a .
78 | public LocalizedString this[string name, params object[] arguments]
79 | {
80 | get
81 | {
82 | LastLocalizeKey = name;
83 | if (Resource.ContainsKey(name))
84 | {
85 | var message = string.Format(Resource[name], arguments);
86 |
87 | return new LocalizedString(name, message, false, "dummy searched location");
88 | }
89 |
90 | if (ThrowExceptionIfNoEntry)
91 | throw new MissingFieldException($"There was no entry with the name '{name} in the dictionary.");
92 |
93 | return new LocalizedString(name, "", true, "dummy searched location");
94 | }
95 | }
96 | }
--------------------------------------------------------------------------------
/LocalizeMessagesAndErrors/UnitTestingCode/StubStringLocalizerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using Microsoft.Extensions.Localization;
5 |
6 | namespace LocalizeMessagesAndErrors.UnitTestingCode;
7 |
8 | ///
9 | /// This is used for testing the
10 | ///
11 | public class StubStringLocalizerFactory : IStringLocalizerFactory
12 | {
13 | private readonly StubStringLocalizer _stubStringLocalizer;
14 |
15 | ///
16 | /// This allows you to provide the localized name + value entries you would
17 | ///
18 | ///
19 | /// If name not found, then throw exception. Defaults onto true
20 | ///
21 | public StubStringLocalizerFactory(Dictionary resource, bool throwExceptionIfNoEntry = true)
22 | {
23 | _stubStringLocalizer = new StubStringLocalizer(resource, throwExceptionIfNoEntry);
24 | }
25 |
26 | ///
27 | /// Creates an using the and
28 | /// of the specified .
29 | ///
30 | /// The .
31 | /// The .
32 | public IStringLocalizer Create(Type resourceSource)
33 | {
34 | return _stubStringLocalizer;
35 | }
36 |
37 | ///
38 | /// Creates an .
39 | ///
40 | /// The base name of the resource to load strings from.
41 | /// The location to load resources from.
42 | /// The .
43 | public IStringLocalizer Create(string baseName, string location)
44 | {
45 | throw new NotImplementedException();
46 | }
47 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Controllers/DefaultLocalizerController.cs:
--------------------------------------------------------------------------------
1 | using LocalizeMessagesAndErrors;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.Extensions.Localization;
4 |
5 | namespace LocalizedWebApp.Controllers;
6 |
7 | public class DefaultLocalizerController : Controller
8 | {
9 | private readonly IDefaultLocalizer _defaultLocalizer;
10 |
11 | public DefaultLocalizerController(
12 | IDefaultLocalizer defaultLocalizer)
13 | {
14 | _defaultLocalizer = defaultLocalizer;
15 | }
16 |
17 | public IActionResult Index()
18 | {
19 | var nameOfService = nameof(IStringLocalizer);
20 | var cultureName = Thread.CurrentThread.CurrentUICulture.Name;
21 |
22 | return View((object)_defaultLocalizer.LocalizeFormattedMessage(
23 | "ExampleMessage".MethodLocalizeKey(this),
24 | $"Localized via {nameOfService} service with culture '{cultureName}' on {DateTime.Now:M}." //Message, using FormattableString
25 | ));
26 | }
27 |
28 | public IActionResult StringMessage()
29 | {
30 | return View((object)_defaultLocalizer.LocalizeStringMessage(
31 | "ExampleMessage".MethodLocalizeKey(this),
32 | "Hello from me!" //static Message, using string
33 | ));
34 | }
35 |
36 | public IActionResult MissingResourceEntry()
37 | {
38 | return View((object)_defaultLocalizer.LocalizeFormattedMessage(
39 | "MissingEntry".MethodLocalizeKey(this),
40 | $"LocalizeStringMessage: I forget to set up the resource entry. Time: {DateTime.Now:T}"
41 | ));
42 | }
43 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Controllers/HomeController.cs:
--------------------------------------------------------------------------------
1 | using LocalizedWebApp.Models;
2 | using Microsoft.AspNetCore.Mvc;
3 | using System.Diagnostics;
4 |
5 | namespace LocalizedWebApp.Controllers
6 | {
7 | public class HomeController : Controller
8 | {
9 | private readonly ILogger _logger;
10 |
11 | public HomeController(ILogger logger)
12 | {
13 | _logger = logger;
14 | }
15 |
16 | public IActionResult Index()
17 | {
18 | return View();
19 | }
20 |
21 | public IActionResult Privacy()
22 | {
23 | return View();
24 | }
25 |
26 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
27 | public IActionResult Error()
28 | {
29 | return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Controllers/StatusGenericLocalizerController.cs:
--------------------------------------------------------------------------------
1 | using GenericServices.AspNetCore;
2 | using LocalizedWebApp.Models;
3 | using LocalizeMessagesAndErrors;
4 | using Microsoft.AspNetCore.Mvc;
5 | using ServiceLayer;
6 |
7 | namespace LocalizedWebApp.Controllers;
8 |
9 | public class StatusGenericLocalizerController : Controller
10 | {
11 | private readonly ExamplesOfStatusGenericsLoc _exampleMethods;
12 |
13 | public StatusGenericLocalizerController(IDefaultLocalizer localizer)
14 | {
15 | _exampleMethods = new ExamplesOfStatusGenericsLoc(localizer);
16 | }
17 |
18 | public IActionResult Index(string? message)
19 | {
20 | ViewBag.Message = message;
21 | return View();
22 | }
23 |
24 | public IActionResult CheckNull()
25 | {
26 | return View();
27 | }
28 |
29 | [HttpPost]
30 | [ValidateAntiForgeryToken]
31 | public IActionResult CheckNull(string? month)
32 | {
33 | var status = _exampleMethods.CheckNull(month);
34 | if (status.IsValid)
35 | return RedirectToAction(nameof(Index), new { message = status.Message });
36 |
37 | status.CopyErrorsToModelState(ModelState);
38 | return View();
39 | }
40 |
41 | public IActionResult CreateDate()
42 | {
43 | return View();
44 | }
45 |
46 | [HttpPost]
47 | [ValidateAntiForgeryToken]
48 | public IActionResult CreateDate(CreateDateDto dto)
49 | {
50 | var status = _exampleMethods.CreateDate(dto.Day, dto.Month, dto.Year);
51 | if (status.IsValid)
52 | return RedirectToAction(nameof(Index), new { message = status.Message });
53 |
54 | status.CopyErrorsToModelState(ModelState, dto);
55 | return View();
56 | }
57 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Controllers/StringLocalizerController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Localization;
3 |
4 | namespace LocalizedWebApp.Controllers;
5 |
6 | public class StringLocalizerController : Controller
7 | {
8 | private readonly IStringLocalizer _localizer;
9 |
10 | public StringLocalizerController(IStringLocalizer localizer)
11 | {
12 | _localizer = localizer;
13 | }
14 |
15 | public IActionResult Index()
16 | {
17 | var nameOfService = nameof(IStringLocalizer);
18 | var cultureName = Thread.CurrentThread.CurrentUICulture.Name;
19 |
20 | return View((object)_localizer["Index_ExampleMessage",
21 | nameOfService,
22 | cultureName,
23 | DateTime.Now].Value);
24 | }
25 |
26 | public IActionResult StringMessage()
27 | {
28 | return View((object)_localizer["StringMessage_ExampleMessage"].Value);
29 | }
30 |
31 | public IActionResult MissingResourceEntry()
32 | {
33 | return View((object)_localizer["MissingEntry_ExampleMessage", DateTime.Now].Value);
34 | }
35 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/LocalizedWebApp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/LocalizedWebApp/Models/CreateDateDto.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace LocalizedWebApp.Models;
5 |
6 | public class CreateDateDto
7 | {
8 | public int Day { get; set; }
9 | public string? Month { get; set; }
10 | public int Year { get; set; }
11 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Models/ErrorViewModel.cs:
--------------------------------------------------------------------------------
1 | namespace LocalizedWebApp.Models
2 | {
3 | public class ErrorViewModel
4 | {
5 | public string? RequestId { get; set; }
6 |
7 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8 | }
9 | }
--------------------------------------------------------------------------------
/LocalizedWebApp/Program.cs:
--------------------------------------------------------------------------------
1 |
2 | using LocalizedWebApp.Controllers;
3 | using LocalizeMessagesAndErrors;
4 |
5 | var builder = WebApplication.CreateBuilder(args);
6 |
7 | // Add services to the container.
8 | builder.Services.AddControllersWithViews();
9 |
10 | #region REGISTERING .NET Localization
11 | builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
12 | #endregion
13 |
14 | #region localization - defining the cultures
15 | //see https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization#localization-middleware
16 | var supportedCultures = new[] { "en", "fr" };
17 | var localizationOptions = new RequestLocalizationOptions()
18 | .SetDefaultCulture(supportedCultures[0])
19 | .AddSupportedCultures(supportedCultures)
20 | .AddSupportedUICultures(supportedCultures);
21 | #endregion
22 |
23 | #region REGISTERING DefaultLocalizer and SimpleLocalizer
24 | //This registers the DefaultLocalizer with the culture that the messages will use
25 | builder.Services.RegisterDefaultLocalizer("en", supportedCultures);
26 | //This registers the SimpleLocalizer, which provides a simpler interface to the DefaultLocalizer.
27 | builder.Services.RegisterSimpleLocalizer();
28 | #endregion
29 |
30 | var app = builder.Build();
31 |
32 | #region SETUP locatization
33 |
34 | app.UseRequestLocalization(localizationOptions);
35 | #endregion
36 |
37 | // Configure the HTTP request pipeline.
38 | if (!app.Environment.IsDevelopment())
39 | {
40 | app.UseExceptionHandler("/Home/Error");
41 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
42 | app.UseHsts();
43 | }
44 |
45 | app.UseHttpsRedirection();
46 | app.UseStaticFiles();
47 |
48 | app.UseRouting();
49 |
50 | app.UseAuthorization();
51 |
52 | app.MapControllerRoute(
53 | name: "default",
54 | pattern: "{controller=Home}/{action=Index}/{id?}");
55 |
56 | app.Run();
57 |
--------------------------------------------------------------------------------
/LocalizedWebApp/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:11985",
7 | "sslPort": 44392
8 | }
9 | },
10 | "profiles": {
11 | "LocalizedWebApp": {
12 | "commandName": "Project",
13 | "dotnetRunMessages": true,
14 | "launchBrowser": true,
15 | "applicationUrl": "https://localhost:7213;http://localhost:5095",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "IIS Express": {
21 | "commandName": "IISExpress",
22 | "launchBrowser": true,
23 | "environmentVariables": {
24 | "ASPNETCORE_ENVIRONMENT": "Development"
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/LocalizedWebApp/Resources/Controllers.HomeController.en.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | Successful completion.
122 |
123 |
124 | The day {0}, month {1}, year {2} doesn't turn into a valid date.
125 |
126 |
127 | Successfully created the date {0:D}.
128 |
129 |
130 | Localized via {0} service with culture '{1}' on {2:M}.
131 |
132 |
133 | The input must not be null.
134 |
135 |
136 | Retour à la page d'accueil {0}
137 |
138 |
139 | Failed with {0} errors.
140 |
141 |
142 | Failed with 1 error.
143 |
144 |
145 | The property should not be negative.
146 |
147 |
148 | Hello from me!
149 |
150 |
--------------------------------------------------------------------------------
/LocalizedWebApp/Resources/Controllers.HomeController.fr.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | Le jour {0}, mois {1}, année {2} ne se transforme pas en une date valide.
122 |
123 |
124 | La date {0:D} a été créée avec succès.
125 |
126 |
127 | Localisé via {0} le service avec culture '{1}' sur {2:M}.
128 |
129 |
130 | Définir la chaîne
131 |
132 |
133 | L'entrée ne doit pas être nulle.
134 |
135 |
136 | Retour à la page d'accueil {0}
137 |
138 |
139 | Fournissez une chaîne (peut être nulle)
140 |
141 |
142 | Exécutez CheckNull
143 |
144 |
145 | Définir la chaîne
146 |
147 |
148 | Réussite.
149 |
150 |
151 | Échec avec {0} erreurs.
152 |
153 |
154 | Échec avec 1 erreur.
155 |
156 |
157 | La propriété ne doit pas être négative.
158 |
159 |
160 | Bonjour de ma part !
161 |
162 |
--------------------------------------------------------------------------------
/LocalizedWebApp/Views/DefaultLocalizer/Index.cshtml:
--------------------------------------------------------------------------------
1 | @model string
2 | @{
3 | ViewData["Title"] = "Index";
4 | }
5 |
6 |
DefaultLocalizerLocalizer Controller
7 |
8 |
Message = "@Model"
9 |
10 | Back to Home
--------------------------------------------------------------------------------
/LocalizedWebApp/Views/DefaultLocalizer/MissingResourceEntry.cshtml:
--------------------------------------------------------------------------------
1 | @model string
2 | @{
3 | ViewData["Title"] = "MissingResourceEntry";
4 | }
5 |
6 |
DefaultLocalizerLocalizer Controller
7 |
8 |
Message = "@Model"
9 |
10 |
Note that the DefaultLocalizerLocalizer service provides the default message if there isn't entry in the resources. It also logs a warning.
11 |
12 | Back to Home
--------------------------------------------------------------------------------
/LocalizedWebApp/Views/DefaultLocalizer/StringMessage.cshtml:
--------------------------------------------------------------------------------
1 | @model string
2 | @{
3 | ViewData["Title"] = "StringMessage";
4 | }
5 |
6 |
DefaultLocalizerLocalizer Controller
7 |
8 |
Message = "@Model"
9 |
10 | Back to Home
--------------------------------------------------------------------------------
/LocalizedWebApp/Views/Home/Index.cshtml:
--------------------------------------------------------------------------------
1 | @{
2 | ViewData["Title"] = "Home Page";
3 | }
4 |
5 |
18 | Swapping to Development environment will display more detailed information about the error that occurred.
19 |
20 |
21 | The Development environment shouldn't be enabled for deployed applications.
22 | It can result in displaying sensitive information from exceptions to end users.
23 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development
24 | and restarting the app.
25 |