Blazor Serverside Localization with IStringLocalizer not taking correct resource file - blazor-server-side

I'm trying to add Localization in my serverside Blazor app.
I have a seperate project which contains my Resource files for NL and EN.
My Startup.cs of my UI project(ConfigureServices)
services.AddLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
List<CultureInfo> supportedCultures =
new List<CultureInfo>
{
new CultureInfo("nl"),
new CultureInfo("en")
};
options.DefaultRequestCulture = new RequestCulture("nl");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
Blazor file in my UI project:
#inject IStringLocalizer<Menu> MenuLocalizer
#MenuLocalizer["Overview"]
#MenuLocalizer["Add"]
But the Localization from the resources never gets taken. Changing the DefaultRequestCulture in startup doesn't also change anything.
I have searched on the net and it looks like I'm doing everything as it should, but no result.
EDIT:
I've made some changes to my resource files, added an explicit NL file.
It seems that the localization always takes the EN version although I specify NL in my StartUp.
So it looks like the localization is working, but not taking the correct file.
EDIT 2:
Fixed it by adding:
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
};
Now it takes the file defined in the startup.

Related

ASP.NET Core 6: Client-side localized number validation

I use ASP.NET Core 6.0 and want to create an exclusively German-language application. So far everything works fine, not least because of the good content here.
However, I now have a problem that the client-side validation of numbers in German notation ("1.234.567,89") simply doesn't work and only the US format ("1,234,567.89") is accepted. When entering dates, however, it works fine. I have also been able to successfully implement the German notifications.
The server-side validation also works when the form sends "1.234.567,89", this value is also properly recognized, etc. I also added the <html lang="de-de"> language tag to the main HTML file.
So far I've helped myself by turning off the client-side validation for the relevant fields with <input data-val="false" ..... />.
This code is also stored in Program.cs:
var supportedCultures = new[] { new CultureInfo("de-DE") };
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("de-DE"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("de-DE");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("de-DE");
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
Who can help me?
After I manually downloaded the appropriate jquery validation package, explicitly specified the German validation methods and languages and entered script snippets in the shared validation, it works wonderfully.
<script src="~/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="~/plugins/jquery-validation/localization/messages_de.min.js"></script>
<script src="~/plugins/jquery-validation/localization/methods_de.min.js"></script>
<script src="~/plugins/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

Add support for legacy behavior in ASP.NET Core 3.1 Razor Pages

I'm migrating an application based on .net framework to .net core.
There's a web application which hosts user provided templates which are cshtml files, like this:
/Template/A.cshtml
<!DOCTYPE html>
<html>
<head></head>
<body>
link</body>
</html>
This should be used inside the new application without modification. Because the files reference each other, I cannot change the urls. The routes matched the filenames before:
Route
Page
/Template/A.cshtml
/Template/A.cshtml
/Template/B.cshtml
/Template/B.cshtml
The templates can be added after compilation. So runtime compilation must be supported (AddRazorRuntimeCompilation).
I already mapped the static files:
// Server static files
// -- from wwwroot
app.UseStaticFiles();
// -- from Templates
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Templates")),
RequestPath = new PathString("/Templates")
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
Can razor pages be configured to support routes like
"Template/A.cshtml"?
The legacy templates do not contain a "#page"
directive. Is it possible to pretend it is there?
Update
It is possible to add some preprocessing to the files. Thus the #page directive can be added to the cshtml files in some automated processing step.
More difficult is to get the routes right. This should be possible by searching the files on disk and adding some endpoints. Then the actions must be created for each file. That's where runtime compilation comes into play.
/* Pseudocode */
app.UseEndpoints(endpoints => {
foreach (var filename in Directory.GetFiles(...)) {
var action = GetPageAction(filename);
endpoints.MapSomething(filename, action);
}
}
I don't like to search the files in Startup class. There has to be some logic for that in Razor Pages. So I'd like to know how to configure that.

How can i access wwwroot of other Project in .net core 3?

I have 2 projects:
1st: Administrator_Part
2nd: Client_part
I have some photos in wwwroot of Administrator_Part project and my question is how can I access the wwwroot of Administrator_Part from Client_part project razor page?
actually I find a way for solving my problem
just add code blow into your startup.cs
// Access wwwroot For Current Root Project
app.UseStaticFiles();
//Access wwwroot of External Project
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), #"./../Administrator_Part/wwwroot/uploadImage/resize")),
RequestPath = new PathString("/MyImages")
});
and any whare eg into razor page you can use it like this:
<img src="/MyImages/1.jpg" />
just change the path....!

Is there a way to package an ASP.NET Core app area as a NuGet package?

I'm working on an ASP.NET Core app that I would love to publish as a NuGet package that you can add to any Core web project. The app is actually entirely confined to an area (i.e., /Areas/MyArea) in the project, including controllers, views, service classes, models, views, etc., except for a few pieces. Really, these are the pieces that I'd love to magically add to an existing web app:
The area and everything in it
Its CSS and JS in wwwroot/lib/myapp
Entries in the Startup class
MyApp.json in the root
I know NuGet will restore the package dependencies, but I'm not sure how it would also consider the client-side packages.
Any suggestions? Is NuGet the wrong tool for this?
currently afaik it is not possible to deliver files into the web app from a nuget package. I think there is some discussion and work going on about making that possible in the future.
The way I'm handling that in my projects is to embed the views and the needed static js and css resources which is done like this in project.json:
"buildOptions": {
"embed": [ "Views/", "js/", "css/**" ]
},
I created a controller to serve my static resources:
public class cscsrController : Controller
{
private ContentResult GetContentResult(string resourceName, string contentType)
{
var assembly = typeof(cscsrController).GetTypeInfo().Assembly;
var resourceStream = assembly.GetManifestResourceStream(resourceName);
string payload;
using (var reader = new StreamReader(resourceStream, Encoding.UTF8))
{
payload = reader.ReadToEnd();
}
return new ContentResult
{
ContentType = contentType,
Content = payload,
StatusCode = 200
};
}
[HttpGet]
[AllowAnonymous]
public ContentResult bootstrapdatetimepickercss()
{
return GetContentResult(
"cloudscribe.Core.Web.css.bootstrap-datetimepicker.min.css",
"text/css");
}
[HttpGet]
[AllowAnonymous]
public ContentResult momentwithlocalesjs()
{
return GetContentResult(
"cloudscribe.Core.Web.js.moment-with-locales.min.js",
"text/javascript");
}
}
then I link to the controller action in the views where I need to load the js and/or css.
To make the embedded views work I created an extension method of RazorViewEngineOptions:
public static RazorViewEngineOptions AddEmbeddedViewsForCloudscribeCore(this RazorViewEngineOptions options)
{
options.FileProviders.Add(new EmbeddedFileProvider(
typeof(SiteManager).GetTypeInfo().Assembly,
"cloudscribe.Core.Web"
));
return options;
}
and this must be called from ConfigureServices in the web app Startup like this:
services.AddMvc()
.AddRazorOptions(options =>
{
options.AddEmbeddedViewsForCloudscribeCore();
})
;
this technique should work the same for areas. Note that one cool thing is that users can download the views and install them locally and that will override the use of the embedded views making it easy to customize some or all views. By overriding the views it is also possible to then manually install the js and css locally if desired and change the views to link to those local files if customization is needed. The end result is my nuget has everything it needs so there is just some startup configuration to get things working.
Years later, this is possible in ASP.NET Core > v2.x, by using a Razor class library.

ASP.NET 5 (MVC 6) - Resources Localization

I have spent about one week trying to understand how Localization is going to work in ASP.NET Core 1.0. I have tested a lot of options, but I can't make it working.
I have read about the bug in Visual Studio, I have read all articles about how it's working right now (Article1, Article2, Article3) and I have check and tested all about the example in the Official GitHub Repository.
My Goal:
I just want to make it works like I did in ASP.NET MVC 5.
I have configured my Startup.cs like this:
Configure Section:
var requestLocalizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
}
};
app.UseRequestLocalization(requestLocalizationOptions, defaultRequestCulture: new RequestCulture("en-US"));
Configure Services Section:
// Add MVC services to the services container.
services
.AddMvc()
.AddViewLocalization(options => options.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization();
In my folder Resources, I have my .resx files. I have copied it from the official example, but no way... No errors, just not working.
If I test the Localization example of the official Repo, it works. But I can't modified to adapt to MVC 6.
I have created a repository on GitHub for my code and test it. (https://github.com/chemitaxis/Localization.StackOverflow)
Can someone please help me? I think a lot of people is having these problems.
Thanks!!
Ok, I solved it... I will update my example on GitHub tomorrow.
I have created a _ViewImports, and add it:
#addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
#using System.Threading.Tasks
#using AspNet5Localization
#using AspNet5Localization.Resources
#using Microsoft.AspNet.Mvc.Localization
#using Microsoft.Extensions.Localization
#inject IStringLocalizer<AmazingResource> SR
After, I have created a HomeController and Views/Home/Index.cshtml file.
Like I have injected in my Views in _ViewImports the IStringLocalizer SR I can use it in my Razor Views using just:
#SR["Name"]
I don't know if it the best way to do that, but it works. If someone can explain the best way to do that, please answer this question.
Complete solution working: https://github.com/chemitaxis/Localization.StackOverflow
Thanks.