asp.net MVC: localization - asp.net-mvc

I have my target language in Session["lang"], which is either "en" or "it". I have added this to the Site.master:
<script runat="server">
void Page_Load(object sender, EventArgs e) {
string lang = Session["lang"].ToString();
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
}
</script>
Then I'd like to invoke a resource string like this:
<asp:Label ID="Label1" runat="server" Text="<%$ Resources:Global, test %>"></asp:Label>
I have two files in the App_GlobalResources, named Global.resx and Global.en.resx.
The problems is that no matter what is in the lang variable, I always get the results from the main Global.resx, and I never get the english version from Global.en.resx
I am doing this wrong entirely??
I tried putting the System.Threading... part in the Application_PreRequestHandlerExecute method in Global.asax.cs but the result was the same.
Thanks
PS: I am asking about a way to make this work in a simple way. If I was to use the complicate way, I'd go with this: http://helios.ca/2009/05/27/aspnet-mvc-and-localization/

i had the same dilema(how to implement localization) in my asp.net mvc app.
I followed the instructions posted here and it works like a charm.
So i created a folder named Localization under Content and then i create Resources resx files for each language i want to translate. Keep in mind that there is a convention for the resx file names. ie
Resources.resx is the default fall back for everything.
Resources.en-GB.resx is for english GB
Resources.en-US.resx is for english US
etc.
Just make sure you follow the instructions posted in the link to embed and make the Resources available in all places in your app (views, controllers etc)
Edit:
I want to add that i ommited this line from web.config since i wanted to manually set the local from my app.
<globalization uiCulture="auto" culture="auto"/>
Instead i have created the following class:
public class SmartController : Controller
{
public SmartController()
{
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
}
}
All controllers inherit from this class.
Since this is an administrative set of the locale i have to set it from my apps settings. You could read it from Cookies and set it, or otherwise. This is imo the simplest solution for localization that i have encountered so far.
Once implemented you can refer to any string you add by the following simple line of code, no extra code needed.
<%= Resources.Strings.TranslatedTerm %>

I bet this one is a duplicate.
Anyway - all you need is here (assuming that you are using webforms viewengine (might work with others too, haven't investigated)).
Oh well... here goes my 'summary':
Helpers are just a part. You need to do some modifications with your default view engine too . On createview/createpartialview it should return localizationwebformview which adds a path key to viewdata which is used by htmlhelper to find resourceexpressionsfields and pass them to localizationhelpers class which retrieves desired value.
Little bonus=>
This might be handy if you don't want to recreate resource folders for view subfolders
(in case you modify viewengine.view/partialviewlocationformats):
private static string ReformatVirtualPath(string virtualPath)
{
//This allows NOT to duplicate App_localResources directory
// ~/Views/Shared/Partial/Some/BulltihS/_View.ascx
// turns into =>
// ~/Views/Shared/_View.ascx
var start = #"(~(/?\w*/?){2})";
var end = #"(\w*.as(c|p)x)";
start = Regex.Match(virtualPath, start).Value;
end = Regex.Match(virtualPath, end).Value;
return start + end;
}
usage:
internal static ResourceExpressionFields GetResourceFields
(string expression, string virtualPath)
{
virtualPath = ReformatVirtualPath(virtualPath);
var context = new ExpressionBuilderContext(virtualPath);
var builder = new ResourceExpressionBuilder();
return (ResourceExpressionFields)
builder.ParseExpression(expression, typeof(string), context);
}
EDIT:
but it might be a good idea to avoid App_GlobalResources and App_LocalResources as K. Scott Allen suggests (check Konstantinos answer).

Related

Localize blazor with IStringLocalizer using a unique resource file per language

I'm trying to localize my Blazor app (.NET 5.0) using IStringLocalizer and user UI selection based on cookies. Following the documentation, it seems to work if I create a .resx file for each page in my Resources/Pages folder.
I'd like to group all key-value pairs within a single file as follows :
MyApp
|-- Resources
| MyResources.resx <--- set to public modifiers to generate class!!!
| MyResources.es.resx
| MyResources.fr.resx
...
|-- Resources
| Index.razor
So in Startup.cs I register the Resources folder:
services.AddControllers();
services.AddLocalization(options => options.ResourcesPath = "Resources");
I also added MapControllers in the configure method, as well as registering supported cultures. I also added the controller:
[Route("[controller]/[action]")]
public class CultureController : Controller {
public IActionResult SetCulture(string culture, string redirectUri) {
if (culture != null) {
HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)));
}
return LocalRedirect(redirectUri);
}
}
Now, on my main "index.razor" page I inject the IStringLocalizer<MyResources> as follows:
#page "/index"
#inject IStringLocalizer<Language> _localizer
<h2>#_localizer["hello_world"]</h2>
<h2>#DateTime.Now.ToShortDateString()</h2>
<h2>#DateTime.Now.ToLongDateString()</h2>
I make sure that all resx files actually contain the "hello_world" key with some values and added a language selector.
When I run the app, changing the language does change the displayed dates, however, the hello_world key is not found so the app displays the key instead. When exploring the _localizer variable, I see that the container is empty - none of the key-value pairs of the .resx are actually loaded.
Is it possible to get this to work? If so, what am I doing wrong here?
The mistake is because of naming here:
#inject IStringLocalizer<Language> _localizer
should be
#inject IStringLocalizer<MyResources> _localizer
And important is to add an empty file MyResources.razor at the root of the project.
Edit:
Another mistake I made is to add the myApp.Resources to _Imports.razor
...
#using myApp.Resources <==== do NOT add this
#neggenbe
Adding an empty razor(AppLang.razor) component at the root of my project with same name with my resource(AppLang.resx) file solved the challenge. I stumbled accross #neggenbe after over 48 hours trying to figure out what was wrong with my code.
If your project is purely blazor, you wont come accross this challenge but if its a mix of MVC and razor(blazor) components, then you'll definately need to do this.

HTML Extensions for wrapping other extensions

Most times when using DevEx MVC extensions, I find myself having to use repetitive code to generate the controls/layouts that I use on a regular basis. For example, I tend to prefer left-aligned captions to controls. Ideally, I'd be able to do something like this and have it "just work":
#Html.DevExpress().TextBoxFor(m => m.Notes).GetHtml()
However, in order to place the caption on the left, I need to also pass in a settings object for it, or dome something much more verbose such as:
#Html.DevExpress().TextBox(
s => {
// ...
s.Properties.CaptionCellStyle.Width = 100;
// ...
}
).Bind(Model.Notes).GetHtml()
What I thought to do was create my own set of extensions that would wrap the DevEx extensions, giving me some sort of common/core customization layer, so I could do something like this:
#Html.MyComponents().TextBoxFor(m => m.Notes)
This call would in turn call the DevExpress TextBoxExtension with a common set of settings and output the DevEx textbox as desired.
I've worked this up via custom html extensions (code below), but have two issues with this basic implementation:
The control renders at the very top of the Body element, not at the position in which it's placed in the view, and
There's a JavaScript error "ASPxClientTextBox" is not defined (this is part of the client-side scripting that DevEx uses with their controls).
I was hoping this would be an easy "wrap it and go" type of scenario. Is there some basic concept of these custom HTML extensions that I'm missing? Or does anyone know if this is a general limitation in trying to wrap another company's pre-existing extensions?
Here's the code I have implemented (which is not yet fully fleshed out, just trying for proof of concept here):
public static class HtmlHelpers
{
public static MyComponentsHtmlHelpers<TModel> MyComponents<TModel>(this HtmlHelper<TModel> html) {
return new MyComponentsHtmlHelpers<TModel>(html);
}
}
public class MyComponentsHtmlHelpers<TModel>
{
private HtmlHelper<TModel> html;
public MyComponentsHtmlHelpers(HtmlHelper<TModel> html) {
this.html = html;
}
public MvcHtmlString TextBoxFor<TValue>(Expression<Func<TModel, TValue>> expression) {
var data = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string propertyName = data.PropertyName;
System.Diagnostics.Debug.WriteLine("PROPERTY NAME: " + propertyName);
TextBoxSettings s = new TextBoxSettings();
s.Name = "textbox_" + propertyName;
s.Properties.Caption = propertyName;
s.Properties.CaptionCellStyle.Width = 100;
TextBoxExtension tb = new TextBoxExtension(s);
return tb.GetHtml();
}
}
Nevermind - cleaning the solution and rebuilding as well as force refreshing the test browser a few times and ensure there's no cache and... now everything works as intended.
(not sure if I ought to delete this question or leave it around in case someone wants to attempt the same... I'll leave it for now, feel free to remove)

Get physical of the root of the website from inside a class?

Hi,
I have a mailhandler class in my MVC webapplication and needs to get a physical path to the mailTemplate file (a couple of folders down the root). How do I do this? Do I have to send in some kind of httpContext? My mailHandler is a singelton so there is no constructor for parameters :
public static EmailHandler Instance
{
get {
if (EmailHandler._emailHandler == null)
EmailHandler._emailHandler = new EmailHandler();
return EmailHandler._emailHandler; }
set { EmailHandler._emailHandler = value; }
}
Any idea?
Personally, I would just tell it the base-path to use; then the same code can work in a number of environments, not just web. If you are web-bound, HttpContext.Current may help. If you want to pass it in, I would instead pass in the abstracted HttpContextBase, ala MVC.
But passing in a string of the base-path is a lot easier :)
you can store physical address of base folder in config file. Then do Path.Combine(baseFolder,templatefile) to get full path. This is preferred way, since it does not depend on having httpcontext accessible.
you can map that folder as virtual folder in IIS and then get physical path using Server.MapPath function
You could always abstract your application configuration :)
public interface IApplicationConfiguration
{
string EMailTemplateFolder { get; }
}
Then pass in an instance of a class implementing this interface into the relevant method. Passing in the instance to your EMailHandler is another option:
YourClassEMailHandlerContainer.Instance
.InitializeWith(new ApplicationConfiguration())
Where ApplicationConfiguration : IApplicationConfiguration.
After this you just call your method.
YourClassEMailHandlerContainer.Instance.ParseTemplate(name)
Where internally:
var templateFile =
Path.Combine(applicationConfiguration.EMailTemplateFolder, name);
Hope that makes sense.

URL-encode parameters in ActionLink?

I have the following route registered;
routes.MapRoute(
"LocationsByArea",
"Locations/{system}/{storage}/{area}",
new { controller = "StorageLocation", action = "Index" },
null
);
...and the following code in my view;
<%= Html.ActionLink("Platser", "Index", "StorageLocation", new { system = Model.System, storage = Model.Storage, area = item.Name }, null)%>
My problem is when the "area = item.Name" contains a colon, e.g. "Area 4:1". If I click the rendered link I get HTTP-error 400, Bad reqest. I guess I have to encode my area parameter in some way, but I cant figure out how. Any help is apreciated.
Thanks!
The built-in encoding/decoding does not work, so I suggest you roll your own, like this:
namespace MyProject.Helpers
{
public static class JobNameHelper
{
public static string JobNameEncode(string jobname)
{
return jobname.Replace(":", "---colon---");
}
public static string JobNameDecode(string jobname)
{
return jobname.Replace("---colon---", ":");
}
}
}
Can you not just use
Server.UrlEnconde(item.Name)
Or am I missing something?
In your routing you may have to use Server.UrlDecde as well although I think It should decode for you on request.
Try using the Routing Debugger to see what the url router is getting passed, then you can see where the decoding needs to happen
ASP.NET 3.5 SP1 and earlier have a number of restrictions on which URLs are valid. In ASP.NET 4 most of these issues have been fixes (or are at least customizable via web.config). I think that the colon character, even when encoded, might not be allowed in ASP.NET 3.5 SP1 and earlier due to security concerns. Allowing colons can be a security problem when performing file checks since they are a little-known syntax for NTFS Alternate Data Streams.
I recommend trying to choose a character other than a colon for these purposes. Maybe a comma, semi-colon, or equal sign might work instead?

ASP.NET MVC tests with MSpec. Is this correct or needs refactoring?

I'm new to MSpec and would like to know if the way I wrote my test for ASP.NET MVC is correct. The test passes but I don't really like the way it's written and it seems awkward. I'm certainly missing something.
public class AccountControllerTests3
{
protected static AccountController controller;
static IFormsAuthenticationService formsService;
static IMembershipService membershipService;
protected static ActionResult result;
protected static LogOnModel model;
Establish context = () =>
{
var controllerBuilder = new TestControllerBuilder();
formsService = MockRepository.GenerateStub<IFormsAuthenticationService>();
membershipService = MockRepository.GenerateStub<IMembershipService>();
model = MockRepository.GenerateStub<LogOnModel>();
controller =
controllerBuilder.CreateController<AccountController>(new object[]
{
formsService,
membershipService
});
};
Because user_logs = () =>
{
bool rememberMe = false;
membershipService.Stub(
x => x.ValidateUser("bdd", "mspec")).Return(true);
formsService.Stub(x => x.SignIn("bdd", rememberMe));
controller.ModelState.IsValid.ShouldBeTrue();
};
}
[Subject(typeof(AccountController), "LogInTests")]
public class When_logging_into_application_with_good_login_and_password : AccountControllerTests3
{
private It user_should_be_redirected_to_the_home_page = () =>
{
model.UserName = "bdd";
model.Password = "mspec";
result = controller.LogOn(model, string.Empty);
result.AssertActionRedirect().ToAction<HomeController>(
x => x.Index());
};
}
[Subject(typeof(AccountController), "LogInTests")]
public class When_logging_into_application_with_bad_login_and_password : AccountControllerTests3
{
It The_error_message_should_be_shown = () =>
{
model.UserName = "BAD";
model.Password = "BAD";
result = controller.LogOn(model, string.Empty);
controller.ModelState[""].Errors[0].ErrorMessage.ShouldEqual(
"The user name or password provided is incorrect.");
};
}
Thanks in advance,
Thomas
One of my goals when I write tests with MSpec is to get the "Assert" or the "It" down to one line. MSpec is not like NUnit in that it only executes the Context (made up of the Establish clauses from the current class and all base classes and the Because clause) once followed by all of the Specifications (It clauses).
This is designed explicitly to force you to not perform any behavior in the It clauses, but rather observe it.
What you're actually doing here is using MSpec like NUnit. Try and rewrite the tests in a single class (using no inheritance). Work backwards... in the It, place a single line that asserts what you want to assert. Perhaps the AssertRedirect. In the Because, try and put a single line that causes the observations to be observable. This would probably be your call to the controller's logon method. Finally, in the "Establish context" you'd want to put everything else.
After a while, you may want to pull some of the things in the Establish context only into a base class, but in doing so, be sure that your entire subclass stands alone in terms of understanding. A reader shouldn't need to read the base class in order to understand what the actual spec is doing. It's ok to hide ceremonial implementation details, but be sure to hide them behind descriptive method names.
There's another line I'm not sure about:
controller.ModelState.IsValid.ShouldBeTrue();
If this is a test, it should probably be in its own It clause. Though really, do you want to test this? What are you testing here? Shouldn't your controller take an action based on whether or not the model is valid? Shouldn't the result of that action be observable (validation error instead of login error). I just wonder if you really need to test this.
A few other things to check out, first for styling with R#, it seems your tests are falling victim to R#'s defaults. I posted about how to fight this here:
http://codebetter.com/blogs/aaron.jensen/archive/2008/10/19/getting-resharper-and-vs-to-play-nice-with-mspec.aspx
Also, James Broome has some nice MVC MSpec extensions that are worth checking out:
http://jamesbroo.me/introducing-machinespecificationsmvc/
Good luck and Enjoy! Feel free to ping me on twitter if you have any other unrelated questions.
Here's a remark: instead of using CreateController method use InitializeController, because it is compile-time safer and refactor friendlier.
Instead of:
controller = controllerBuilder.CreateController<AccountController>(
new object[] { formsService, membershipService });
Do:
controller = new AccountController(formsService, membershipService);
controllerBuilder.InitializeController(controller);
The first will still compile if you change the controller constructor arguments and it will blow at runtime, while the second will generate a compile-time error.

Resources