Skip to content

Commit

Permalink
Got .NET localization working in Example1
Browse files Browse the repository at this point in the history
  • Loading branch information
JonPSmith committed Dec 15, 2022
1 parent f3ff0e1 commit ad9da57
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 113 deletions.
5 changes: 1 addition & 4 deletions AuthPermissions.AspNetCore/SetupExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Copyright (c) 2021 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading.Tasks;
using AuthPermissions.AdminCode;
using AuthPermissions.AdminCode.Services;
using AuthPermissions.AspNetCore.AccessTenantData;
Expand Down Expand Up @@ -266,7 +263,7 @@ private static void RegisterCommonServices(this AuthSetupData setupData)
setupData.Services.AddTransient<IBulkLoadUsersService, BulkLoadUsersService>();

//Localization services
//NOTE: The developer must register the .NET localization service and add
//NOTE: If you want to use the localization services you need to setup / register the .NET IStringLocalizer<TResource> service
setupData.Services.AddSingleton(typeof(ILocalizeWithDefault<>), typeof(LocalizeWithDefault<>));

//Other services
Expand Down
2 changes: 1 addition & 1 deletion Example1.RazorPages.IndividualAccounts/Model/AppSummary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ public class AppSummary
"Individual accounts: InMemoryDatabase",
"AuthPermissions: In-memory database (uses SQLite in-memory)"
};
public string Note { get; } = "This is a basic example of AuthPermissions Roles and permissions.";
public string Note { get; } = "Shows basics of Roles and permissions, plus multi-language support.";
}
}
5 changes: 3 additions & 2 deletions Example1.RazorPages.IndividualAccounts/Pages/Index.cshtml
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
@page
@using Example1.RazorPages.IndividualAccounts.Model
@using Microsoft.AspNetCore.Identity
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

<div class="text-center">
<h1>Example1 - looking at Roles and Permissions</h1>
<h2>Example1 - looking at Roles/Permissions, plus localization</h2>
</div>
<h4>Application summary</h4>
<ul>
Expand Down Expand Up @@ -34,7 +35,7 @@
NOTE: The Email address is also the password in these cases.
</p>
<ul>
@foreach (var user in @Model.Users)
@foreach (var user in @Model.Users ?? new List<IdentityUser>() )
{
<li><strong>@user.UserName</strong></li>
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
@page
@model SetCultureModel
@{
}

<h3>Select the culture you want</h3>

<form method="post">
<div class="col-md-4">
<select name="SetLanguage" asp-items="Model.CultureList"></select>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-primary"/>
</div>
</form>
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Options;

namespace Example1.RazorPages.IndividualAccounts.Pages.Localization;

public class SetCultureModel : PageModel
{
private readonly IOptions<RequestLocalizationOptions> _locOptions;

public SetCultureModel(IOptions<RequestLocalizationOptions> locOptions)
{
_locOptions = locOptions;
}

[BindProperty] public List<SelectListItem> CultureList { get; set; }
[BindProperty] public string SetLanguage { get; set; }

public void OnGet()
{
CultureList = _locOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
}

public IActionResult OnPost()
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(SetLanguage))
);

return RedirectToPage("/Index");
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<!DOCTYPE html>
@using System.Threading
@using Microsoft.Net.Http.Headers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down Expand Up @@ -32,6 +34,12 @@
<a class="dropdown-item" asp-area="" asp-page="/UserInfo/UserClaims">User's claims</a>
</div>
</li>
<li class="nav-link text-dark">
Current culture = @Thread.CurrentThread.CurrentUICulture.DisplayName
</li>
<li>
<a class="btn btn-primary btn-sm" asp-area="" asp-page="/Localization/SetCulture">Change</a>
</li>
</ul>
<partial name="_LoginPartial" />
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static class AppAuthSetupData
public static readonly List<BulkLoadUserWithRolesTenant> UsersWithRolesDefinition = new()
{
new ("[email protected]", null, "Role1"),
new ("Mananger@g1.com", null, "Role2"),
new ("Manager@g1.com", null, "Role2"),
new ( "[email protected]", null, "SuperAdmin"),
};
}
Expand Down
113 changes: 102 additions & 11 deletions Example1.RazorPages.IndividualAccounts/Program.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,111 @@
using Example1.RazorPages.IndividualAccounts.PermissionsCode;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using System.Globalization;
using AuthPermissions;
using AuthPermissions.AspNetCore;
using AuthPermissions.AspNetCore.Services;
using AuthPermissions.AspNetCore.StartupServices;
using Example1.RazorPages.IndividualAccounts.Data;
using Microsoft.EntityFrameworkCore;
using RunMethodsSequentially;
using Microsoft.Extensions.Options;

namespace Example1.RazorPages.IndividualAccounts
namespace Example1.RazorPages.IndividualAccounts;

public class Program
{
public class Program
public static void Main(string[] args)
{
public static void Main(string[] args)
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDbContext<ApplicationDbContext>(opt =>
opt.UseInMemoryDatabase(nameof(ApplicationDbContext)));

builder.Services.AddDefaultIdentity<IdentityUser>(
options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();

//Example of configure a page as only shown if you log in
builder.Services.AddRazorPages(options =>
{
CreateHostBuilder(args).Build().Run();
}
options.Conventions.AuthorizePage("/AuthBuiltIn/LoggedInConfigure");
})
#region localization
.AddViewLocalization(options => options.ResourcesPath = "Resources");
#endregion

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
#region localization
builder.Services.Configure<RequestLocalizationOptions>(options => {
List<CultureInfo> supportedCultures = new List<CultureInfo>
{
webBuilder.UseStartup<Startup>();
});
new ("en"),
new ("fr"),
};
options.DefaultRequestCulture = new RequestCulture("en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;

options.RequestCultureProviders = new List<IRequestCultureProvider>()
{
new CookieRequestCultureProvider(),
//new AcceptLanguageHeaderRequestCultureProvider(),
//new QueryStringRequestCultureProvider()
};
});
#endregion

builder.Services.RegisterAuthPermissions<Example1Permissions>()
.UsingInMemoryDatabase()
.IndividualAccountsAuthentication()
.AddRolesPermissionsIfEmpty(AppAuthSetupData.RolesDefinition)
.AddAuthUsersIfEmpty(AppAuthSetupData.UsersWithRolesDefinition)
.RegisterAuthenticationProviderReader<SyncIndividualAccountUsers>()
.RegisterFindUserInfoService<IndividualAccountUserLookup>()
.AddSuperUserToIndividualAccounts()
.SetupAspNetCoreAndDatabase(options =>
{
//Migrate individual account database
options.RegisterServiceToRunInJob<StartupServiceMigrateAnyDbContext<ApplicationDbContext>>();
//Add demo users to the database
options.RegisterServiceToRunInJob<StartupServicesIndividualAccountsAddDemoUsers>();
});


var app = builder.Build();

#region localization

var options = app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(options);

#endregion

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
}
}

}
91 changes: 0 additions & 91 deletions Example1.RazorPages.IndividualAccounts/Startup.cs

This file was deleted.

4 changes: 2 additions & 2 deletions Example1.RazorPages.IndividualAccounts/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Example1.RazorPages.IndividualAccounts;Trusted_Connection=True;MultipleActiveResultSets=true"
//Example1 uses Sqlite in-memory database
},
"Logging": {
"LogLevel": {
Expand All @@ -15,5 +15,5 @@
"Email": "[email protected]",
"Password": "[email protected]"
},
"DemoUsers": "[email protected],[email protected],Mananger@g1.com"
"DemoUsers": "[email protected],[email protected],Manager@g1.com"
}

0 comments on commit ad9da57

Please sign in to comment.