Identityserver3 get and change localization in runtime - asp.net

I used IdentityServer3.Contrib.Localization to provide translation to the identityserver.
IdentityServer3.Contrib.Localization provides only localization for scopes, messages, events but still there are missing texts to translate in login page and etc.
I think you should provide a custom views for every language using IViewService but i don't know if this is the correct path.
For example in order to provide a localization for a specific language i register this in startup class configuration:
// Register the localization service
idServerServiceFactory.Register(
new Registration<ILocalizationService>(r => new GlobalizedLocalizationService(
new LocaleOptions { Locale = "de-DE" })));
but now i want to change the language based on the language that user input or based on the browser accept-language, how can i change the localization for (scopes, events, messages, views) in run time.
some one mention that i can use OwinEnvironementService and inject it to the localization service to get the language but is there any example?
Also i think that i can provide an owin middleware in order to provide the needed change in localization based on the language but any suggestions?

The IdentityServer3.Localization(nuget.org) package can now do this:
var opts = new LocaleOptions
{
LocaleProvider = env =>
{
var owinContext = new OwinContext(env);
var owinRequest = owinContext.Request;
var headers = owinRequest.Headers;
var accept_language_header = headers["accept-language"].ToString();
var languages = accept_language_header
.Split(',')
.Select(StringWithQualityHeaderValue.Parse)
.OrderByDescending(s => s.Quality.GetValueOrDefault(1));
var locale = languages.First().Value;
return locale;
}
};
var factory = new IdentityServerServiceFactory();
factory.Register(new Registration<LocaleOptions>(opts));
factory.LocalizationService = new Registration<ILocalizationService, GlobalizedLocalizationService>();
=> Link to sample here.

Related

Simple Odata Client to consume Odata with Authentication not working

I m new to Simple.Odata.client. I had a problem to access the Odata Service with below code. The below code return null. but Postman return with result.
suspected Problem : How to pass a url string with '1000' &format=json
Is the below Simple odata client setup correctly?
There is no UrlBase in Simple Odata client, but there is BAseUri
Is this ODataClientSettings working??
var settings = new Simple.OData.Client.ODataClientSettings();
settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");
settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);
please help
Thanks
This worked for me
var credentials = new NetworkCredential(userName, password); //you can use the override with the domain too.
var settings = new ODataClientSettings(baseUrl, credentials) //baseUrl is a string.
{
IgnoreResourceNotFoundException = true,
OnTrace = (x, y) => Debug.WriteLine(x, y),
PayloadFormat = ODataPayloadFormat.Json, //here is where you specify the format
IgnoreUnmappedProperties = true,
RenewHttpConnection = true,
TraceFilter = ODataTrace.All,
PreferredUpdateMethod = ODataUpdateMethod.Merge
};
var client = new ODataClient(settings);
Your baseUrl should not contain all those OData tags but the endpoint of your service like https://myservice.mysite.com/api.svc. Then as you use the Simple.OData.Client the resource url will be automatically completed.
Please, take a look at the OData standard to figure out how it works and see the Simple.OData.Client repo's examples to better understand how to use it.
To better understand how to use the Windows Authentication you can check Authentication and Authorization with Windows Accounts and how to access website with Windows credential
Hope this help.

Firebase Rest Api setting language for user or app?

Firebase has option to set language code or app language for current user in order to get verification, password reset emails in defined language like below. below is from Android SDK implementation
Additionally you can localize the verification email by updating the
language code on the Auth instance before sending the email. For
example:
auth.setLanguageCode("fr"); // To apply the default app language
instead of explicitly setting it. // auth.useAppLanguage();
But i am using rest api within my uwp application and this option is not defined in rest api documentation
Does anybody know how to achieve this?
Anybody else is looking for solution. you need to add header as X-Firebase-Locale: 'fr'. C# code will look like as below. you can find the full implementation here
public async Task SendEmailVerificationAsync(string firebaseToken, string locale = null)
{
var content = $"{{\"requestType\":\"VERIFY_EMAIL\",\"idToken\":\"{firebaseToken}\"}}";
var StringContent = new StringContent(content, Encoding.UTF8, "application/json");
if (locale != null)
StringContent.Headers.Add("X-Firebase-Locale", locale);
var response = await this.client.PostAsync(new Uri(string.Format(GoogleGetConfirmationCodeUrl, this.authConfig.ApiKey)), StringContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
}

Route localization in ASP.NET Core 2

I am developing an online store using ASP.NET Core 2 and I am struggling with how to implement route localization, ex. depending from the country where user is from I want him to see /en/products or /pl/produkty.
I managed to implement culture as part of the url, like /en/...., and user can also change default language by clicking a button on the website. However, I have no idea how to localize whole urls. I don't want to put hundreds of urls in Startup.cs (MapRoute). I need a better solution, which is working automatically behind the scenes.
If someone change directly the url (ex. en/products) and put pl instead of en, I want him/her to be redirected to pl/produkty automatically.
I hope you can help me!
here's a very good ressource here:
Asp.Net core Localization deep dive
Precisely here's what you're looking for:
IList<CultureInfo> supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("fi-FI"),
};
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
var requestProvider = new RouteDataRequestCultureProvider();
localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en-US}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(localizationOptions);
subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture=en-US}/{controller=Home}/{action=Index}/{id?}");
});
});
});

How to change the default culture?

I created my first app with ASP.NET Core. When I debug it, I see a problem with words that have accents:
How can I correctly localize the application?
Update:
I tried to implement Joe's suggestion, but I didn't get the expected result as you can see in this image.
The strings displayed from the database are okay, but the strings used in the view template like title or text are displayed incorrectly.
I don't want a multi-language application, just one in português.
On the old asp.net this configurations was done on .config with element
text html
in project.json you need this dependency
"Microsoft.Extensions.Localization": "1.0.0-rc2-final",
in Startup.cs in ConfigureServices you need code like this:
services.AddLocalization(options => options.ResourcesPath = "GlobalResources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};
// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedCultures;
// You can change which providers are configured to determine the culture for requests, or even add a custom
// provider with your own logic. The providers will be asked in order to provide a culture for each request,
// and the first to provide a non-null result that is in the configured supported cultures list will be used.
// By default, the following built-in providers are configured:
// - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
// - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
// - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
//options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
//{
// // My custom request culture logic
// return new ProviderCultureResult("en");
//}));
});
in Configure you need code something like this:
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
I have some working demo code here, if you need more

ASP.NET Dynamic Data site within Umbraco 6

I have a Dynamic Data site in a folder called admin. This folder is in the root of the website and referenced in the reserved paths section of the web.config file.
After upgrading from Umbraco 4.7.2 to 6.0.5 I've noticed that the links in the Dynamic Data site that normally take me to my tables are now trying to hit the /umbraco/rendermvc/List controller and action. I'm assuming that somehow my routes have been changed, but being so new to MVC I have no idea how to restore these.
If it is any help, this is the section of my startup code that used to register the contexts correctly. Any help on how to restore these routes without breaking the routing of the new Umbraco version would be very appreciated!
public static void RegisterContext(RouteCollection routes, string dbName, Type contextType, string ddFolder)
{
var model = new MetaModel
{
DynamicDataFolderVirtualPath = ddFolder,
FieldTemplateFactory =
new FieldTemplateFactory()
{TemplateFolderVirtualPath = "~/admin/DynamicData/FieldTemplates",}
};
model.RegisterContext(contextType, new ContextConfiguration() {ScaffoldAllTables = true});
routes.Add(new DynamicDataRoute("admin/{dbname}/{table}/{action}.aspx")
{
Constraints = new RouteValueDictionary(new
{
action = "List|Details|Edit|Insert",
dbname = dbName
}),
Model = model
});
Models[dbName] = model;
}
I think you have to put your custom stuff in an override on the OnApplicationStarted event in a custom global.asax which inherits from Umbraco.Web.UmbracoApplication (I haven't tried it yet), see this blog (about half way down the page) and our.umbraco.

Resources