private static void ConfigureRequestLocalization(IApplicationBuilder app)
        {
            using (var languageManager = app.ApplicationServices.GetRequiredService<IIocResolver>().ResolveAsDisposable<ILanguageManager>())
            {
                var defaultLanguage = languageManager.Object
                    .GetLanguages()
                    .FirstOrDefault(l => l.IsDefault);

                if (defaultLanguage == null)
                {
                    return;
                }

                var supportedCultures = languageManager.Object
                    .GetLanguages()
                    .Select(l => new CultureInfo(l.Name))
                    .ToArray();

                var defaultCulture = new RequestCulture(defaultLanguage.Name);

                var options = new RequestLocalizationOptions
                {
                    DefaultRequestCulture = defaultCulture,
                    SupportedCultures = supportedCultures,
                    SupportedUICultures = supportedCultures
                };

                app.UseRequestLocalization(options);
            }
        }
            public void Can_Resolve_Path_To_Page_To_Specified_Culture()
            {
                // Arrange
                var trie = CreateTrie();
                var currentRequestCulture = new Mock<RequestCulture>("en");

                var trieResolver = new Mock<IRouteResolverTrie>(MockBehavior.Strict);
                trieResolver.Setup(t => t.LoadTrieAsync(It.IsAny<RequestCulture>()))
                    .ReturnsAsync(trie);

                var mapper = new Mock<IControllerMapper>(MockBehavior.Strict);

                var page = new Page
                {
                    Id = "articles/1"
                };

                var virtualPathResolver = new DefaultVirtualPathResolver(trieResolver.Object, mapper.Object);
                var virtualPathContext = CreateVirtualPathContext(new { page, culture = "sv" });
                var defaultRequestCulture = new RequestCulture("en");

                // Act
                var result = virtualPathResolver.Resolve(virtualPathContext, defaultRequestCulture, currentRequestCulture.Object);

                // Assert
                Assert.NotNull(result);
                Assert.True(result.HasValue);
                Assert.Equal("/sv/article", result.Value);
            }
Exemplo n.º 3
0
        public DefaultRouter(IRouter defaultHandler, IRouteResolver routeResolver, IVirtualPathResolver virtualPathResolver, RequestCulture defaultRequestCulture)
        {
            if (defaultHandler == null)
            {
                throw new ArgumentNullException(nameof(defaultHandler));
            }

            if (routeResolver == null)
            {
                throw new ArgumentNullException(nameof(routeResolver));
            }

            if (virtualPathResolver == null)
            {
                throw new ArgumentNullException(nameof(virtualPathResolver));
            }

            if (defaultRequestCulture == null)
            {
                throw new ArgumentNullException(nameof(defaultRequestCulture));
            }

            _defaultHandler = defaultHandler;
            _routeResolver = routeResolver;
            _virtualPathResolver = virtualPathResolver;
            _defaultRequestCulture = defaultRequestCulture;
        }
Exemplo n.º 4
0
        protected virtual void ConfigureRequestLocalization(IApplicationBuilder app)
        {
            using (var languageManager = AbpBootstrapper.IocManager.ResolveAsDisposable<ILanguageManager>())
            {
                var supportedCultures = languageManager.Object
                    .GetLanguages()
                    .Select(l => new CultureInfo(l.Name))
                    .ToArray();

                var defaultCulture = new RequestCulture(
                    languageManager.Object
                        .GetLanguages()
                        .FirstOrDefault(l => l.IsDefault)
                        ?.Name
                );

                var options = new RequestLocalizationOptions
                {
                    DefaultRequestCulture = defaultCulture,
                    SupportedCultures = supportedCultures,
                    SupportedUICultures = supportedCultures
                };

                app.UseRequestLocalization(options);
            }
        }
Exemplo n.º 5
0
 public async Task<Trie> LoadTrieAsync(RequestCulture requestCulture)
 {
     using (var session = _documentStore.OpenAsyncSession())
     {
         using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(60)))
         {
             var site = await session.LoadAsync<Site>("sites/" + requestCulture.Culture.TwoLetterISOLanguageName);
             return site.Trie;
         }
     }
 }
Exemplo n.º 6
0
    /// <summary>
    /// Creates a string representation of a <see cref="RequestCulture"/> for placement in a cookie.
    /// </summary>
    /// <param name="requestCulture">The <see cref="RequestCulture"/>.</param>
    /// <returns>The cookie value.</returns>
    public static string MakeCookieValue(RequestCulture requestCulture)
    {
        if (requestCulture == null)
        {
            throw new ArgumentNullException(nameof(requestCulture));
        }

        return(string.Join(_cookieSeparator,
                           $"{_culturePrefix}{requestCulture.Culture.Name}",
                           $"{_uiCulturePrefix}{requestCulture.UICulture.Name}"));
    }
Exemplo n.º 7
0
        // Pass the requestCultureFeature and requestCulture objects to the view
        // so we can get Culture/UICulture information.

        public IActionResult About()
        {
            IRequestCultureFeature requestCultureFeature = HttpContext.Features.Get <IRequestCultureFeature>();
            RequestCulture         requestCulture        = requestCultureFeature.RequestCulture;

            ViewData["requestCultureFeature"] = requestCultureFeature;
            ViewData["requestCulture"]        = requestCulture;
            ViewData["Message"] = _localizer["Your application description page."];

            return(View());
        }
Exemplo n.º 8
0
        public async Task <Trie> LoadTrieAsync(RequestCulture requestCulture)
        {
            using (var session = _documentStore.OpenAsyncSession())
            {
                using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(60)))
                {
                    var site = await session.LoadAsync <Site>("sites/" + requestCulture.Culture.TwoLetterISOLanguageName);

                    return(site.Trie);
                }
            }
        }
Exemplo n.º 9
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            SupportedCultures = new CultureInfo[]
            {
                new CultureInfo("pt-BR"),
                new CultureInfo("en-US")
            };

            DefaultRequestCulture = new RequestCulture("en-US", "en-US");
        }
Exemplo n.º 10
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                //app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseSession();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            // Add Documentation (MkDocs) Support
            app.UseFileServer(new FileServerOptions
            {
                FileProvider            = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Documentation/site/")),
                RequestPath             = "/documentation",
                EnableDirectoryBrowsing = false,
                EnableDefaultFiles      = true,
                DefaultFilesOptions     = { DefaultFileNames = { "index.html" } }
            });

            // Add Culture Detection Support
            var allCultures    = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList(); //.Where(x => !x.IsNeutralCulture)
            var defaultCulture = new RequestCulture("en-US");

            defaultCulture.UICulture.NumberFormat.CurrencySymbol = "$";
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = defaultCulture,
                SupportedCultures     = allCultures,
                SupportedUICultures   = allCultures
            });

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapHub <UpdateHub>("/update");
            });
        }
    public async Task GetCultureInfoFromPersistentCookie()
    {
        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                var options = new RequestLocalizationOptions
                {
                    DefaultRequestCulture = new RequestCulture("en-US"),
                    SupportedCultures     = new List <CultureInfo>
                    {
                        new CultureInfo("ar-SA")
                    },
                    SupportedUICultures = new List <CultureInfo>
                    {
                        new CultureInfo("ar-SA")
                    }
                };
                var provider = new CookieRequestCultureProvider
                {
                    CookieName = "Preferences"
                };
                options.RequestCultureProviders.Insert(0, provider);

                app.UseRequestLocalization(options);
                app.Run(context =>
                {
                    var requestCultureFeature = context.Features.Get <IRequestCultureFeature>();
                    var requestCulture        = requestCultureFeature.RequestCulture;
                    Assert.Equal("ar-SA", requestCulture.Culture.Name);
                    return(Task.FromResult(0));
                });
            });
        }).Build();

        await host.StartAsync();

        using (var server = host.GetTestServer())
        {
            var client         = server.CreateClient();
            var culture        = new CultureInfo("ar-SA");
            var requestCulture = new RequestCulture(culture);
            var value          = CookieRequestCultureProvider.MakeCookieValue(requestCulture);
            client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", value).ToString());
            var response = await client.GetAsync(string.Empty);

            Assert.Equal("c=ar-SA|uic=ar-SA", value);
        }
    }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a string representation of a <see cref="RequestCulture"/> for placement in a cookie.
        /// </summary>
        /// <param name="requestCulture">The <see cref="RequestCulture"/>.</param>
        /// <returns>The cookie value.</returns>
        public static string MakeCookieValue(RequestCulture requestCulture)
        {
            if (requestCulture == null)
            {
                throw new ArgumentNullException("requestCulture");
            }

            var seperator = _cookieSeparator[0].ToString();

            return string.Join(seperator,
                string.Format("{0}{1}", _culturePrefix, requestCulture.Culture.Name),
                string.Format("{0}{1}", _uiCulturePrefix, requestCulture.UICulture.Name));
        }
Exemplo n.º 13
0
 public static void SetCultureCookie(
     HttpContext httpContext,
     RequestCulture requestCulture)
 {
     httpContext.Response.Cookies.Append(
         CookieRequestCultureProvider.DefaultCookieName,
         CookieRequestCultureProvider.MakeCookieValue(requestCulture),
         new CookieOptions
     {
         Expires = DateTime.Now.AddYears(2)
     }
         );
 }
Exemplo n.º 14
0
        public IActionResult Set(string uiCulture, string returnUrl)
        {
            IRequestCultureFeature feature = HttpContext.Features.Get <IRequestCultureFeature>();

            RequestCulture request = new RequestCulture(feature.RequestCulture.Culture, new CultureInfo(uiCulture));

            string cookieValue = CookieRequestCultureProvider.MakeCookieValue(request);
            string cookieName  = CookieRequestCultureProvider.DefaultCookieName;

            Response.Cookies.Append(cookieName, cookieValue);

            return(LocalRedirect(returnUrl));
        }
Exemplo n.º 15
0
        public static RequestCulture AppendCookie(HttpResponse response, string culture)
        {
            RequestCulture requestCulture = new RequestCulture(culture);

            response.Cookies.Delete(CookieRequestCultureProvider.DefaultCookieName);
            response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(requestCulture),
                new CookieOptions {
                Expires = DateTimeOffset.UtcNow.AddYears(1), Secure = true, IsEssential = true
            });
            return(requestCulture);
        }
        public override Task <RequestCulture> DetermineRequestCulture(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return(Task.FromResult((RequestCulture)null));
            }

            string userCulture   = null;
            string userUICulture = null;

            string cultureClaim = httpContext.User.GetCulture();

            if (!string.IsNullOrWhiteSpace(cultureClaim))
            {
                userCulture = cultureClaim;
            }

            string uicultureClaim = httpContext.User.GetUICulture();

            if (!string.IsNullOrWhiteSpace(uicultureClaim))
            {
                userUICulture = uicultureClaim;
            }

            if (userCulture == null && userUICulture == null)
            {
                // No values specified for either so no match
                return(Task.FromResult((RequestCulture)null));
            }

            if (userCulture != null && userUICulture == null)
            {
                // Value for culture but not for UI culture so default to culture value for both
                userUICulture = userCulture;
            }

            if (userCulture == null && userUICulture != null)
            {
                // Value for UI culture but not for culture so default to UI culture value for both
                userCulture = userUICulture;
            }

            var requestCulture = new RequestCulture(new CultureInfo(userCulture), new CultureInfo(userUICulture));

            return(Task.FromResult(requestCulture));
        }
Exemplo n.º 17
0
        public void SetCulture(string culture)
        {
            var requestCulture = new RequestCulture(culture);
            var response       = m_httpContextAccessor.HttpContext.Response;

            response.Cookies.Append(
                CultureCookieName,
                requestCulture.Culture.Name,
                new CookieOptions
            {
                Expires = DateTimeOffset.UtcNow.AddYears(1)
            }
                );
        }
Exemplo n.º 18
0
        public static void SetCultureCookie(HttpContext context
                                            , string cookieName
                                            , string culture)
        {
            var requestCulture = new RequestCulture(culture);

            context.Response.Cookies.Append(
                cookieName
                , CookieRequestCultureProvider.MakeCookieValue(requestCulture)
                , new CookieOptions {
                Expires = DateTimeOffset.UtcNow.AddYears(1)
            }
                );
        }
Exemplo n.º 19
0
        private void SetApplicationCultures(RequestLocalizationOptions options)
        {
            var defaultCulture    = new RequestCulture("en");
            var supportedCultures = new[]
            {
                new CultureInfo("ro"),
                new CultureInfo("en"),
                new CultureInfo("fr")
            };

            options.DefaultRequestCulture = defaultCulture;
            options.SupportedCultures     = supportedCultures;
            options.SupportedUICultures   = supportedCultures;
        }
Exemplo n.º 20
0
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            var requestCulture = new RequestCulture(culture);

            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(requestCulture),
                new CookieOptions {
                IsEssential = true
            }
                );

            return(LocalRedirect(returnUrl));
        }
Exemplo n.º 21
0
        private void SetCookieValues(string culture = null)
        {
            var localizationCookie = GetCookieValue();

            if (culture != null)
            {
                var requestCulture = new RequestCulture(culture);
                localizationCookie.CurrentCulture = requestCulture.Culture.Name;
            }

            localizationCookie.DefaultCulture = m_autoLocalizationManager.GetDefaultCulture().Name;

            SetCookieValue(localizationCookie);
        }
        public void Create_ReturnsRequestLocalizationOptions(RequestLocalizationOptions options)
        {
            var requestCulture    = new RequestCulture("pt-BR");
            var supportedCultures = new List <CultureInfo> {
                new CultureInfo("pt-BR")
            };
            var action = RequestLocalizationOptionsFactory.Create();

            action.Invoke(options);

            // Asserts
            options.DefaultRequestCulture.Should().BeEquivalentTo(requestCulture);
            options.SupportedCultures.Should().BeEquivalentTo(supportedCultures);
        }
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            var requestCulture = new RequestCulture(culture);

            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(requestCulture),
                new CookieOptions {
                Expires = DateTimeOffset.UtcNow.AddYears(1)
            }
                );

            return(LocalRedirect(returnUrl));
        }
Exemplo n.º 24
0
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            var requestCulture = new RequestCulture(culture); //TODO validation of unsupported culture name

            HttpContext.Request.HttpContext.Response.Cookies.Append(
                "Localization.Culture",
                requestCulture.Culture.Name,
                new CookieOptions
            {
                Expires = DateTimeOffset.UtcNow.AddYears(1)
            }
                );

            return(LocalRedirect(returnUrl));
        }
Exemplo n.º 25
0
        private void SetPreferences(ApplicationUser user)
        {
            UserPreferencesViewModel preferences = UserPreferencesAppService.GetByUserId(new Guid(user.Id));

            if (preferences == null || preferences.Id == Guid.Empty)
            {
                RequestCulture    requestLanguage = Request.HttpContext.Features.Get <IRequestCultureFeature>().RequestCulture;
                SupportedLanguage lang            = base.SetLanguageFromCulture(requestLanguage.UICulture.Name);

                SetCookieValue(SessionValues.PostLanguage, lang.ToString(), 7);
            }
            else
            {
                SetCookieValue(SessionValues.PostLanguage, preferences.UiLanguage.ToString(), 7);
                SetSessionValue(SessionValues.JobProfile, preferences.JobProfile.ToString());
            }
        }
Exemplo n.º 26
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId, code },
                protocol: Request.Scheme);

            string         culture        = "";
            RequestCulture requestCulture = new RequestCulture("en-US");

            if (!_options.Value.DefaultRequestCulture.Equals(requestCulture))
            {
                culture = ".ru-RU";
            }

            string webRootPath     = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            var    file            = Path.Combine(contentRootPath, "wwwroot", "lib", "mtd-ordermaker", "emailform", $"userEmail{culture}.html");
            var    htmlArray       = System.IO.File.ReadAllText(file);
            string htmlText        = htmlArray.ToString();

            htmlText = htmlText.Replace("{link}", $"<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>{_localizer["Verify Email Address"]}</a>");
            await _emailSender.SendEmailAsync(email, _localizer["Email Verification"], htmlText);

            StatusMessage = "Verification email sent. Please check your email.";
            return(RedirectToPage());
        }
Exemplo n.º 27
0
        public async Task <IActionResult> OnPostAdminConfimEmailAsync()
        {
            IFormCollection requestForm = await Request.ReadFormAsync();

            string userName = requestForm["UserName"];
            var    user     = await _userManager.FindByNameAsync(userName);

            if (user == null)
            {
                return(NotFound());
            }

            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { area = "Identity", userId, code },
                protocol: Request.Scheme);

            string         culture        = "";
            RequestCulture requestCulture = new RequestCulture("en-US");

            if (!_options.Value.DefaultRequestCulture.Equals(requestCulture))
            {
                culture = ".ru-RU";
            }

            string webRootPath     = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            var    file            = Path.Combine(contentRootPath, "wwwroot", "lib", "mtd-ordermaker", "emailform", $"userEmail{culture}.html");
            var    htmlArray       = System.IO.File.ReadAllText(file);
            string htmlText        = htmlArray.ToString();

            htmlText = htmlText.Replace("{link}", $"<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>{_localizer["Verify Email Address"]}</a>");
            await _emailSender.SendEmailAsync(email, _localizer["Email Verification"], htmlText);

            user.EmailConfirmed = false;
            await _userManager.UpdateAsync(user);

            return(Ok());
        }
Exemplo n.º 28
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: Request.Scheme);

                string         culture        = "";
                RequestCulture requestCulture = new RequestCulture("en-US");
                if (!_options.Value.DefaultRequestCulture.Equals(requestCulture))
                {
                    culture = ".ru-RU";
                }

                string webRootPath     = _hostingEnvironment.WebRootPath;
                string contentRootPath = _hostingEnvironment.ContentRootPath;
                var    file            = Path.Combine(contentRootPath, "wwwroot", "lib", "mtd-ordermaker", "emailform", $"userPassword{culture}.html");
                var    htmlArray       = System.IO.File.ReadAllText(file);
                string htmlText        = htmlArray.ToString();

                htmlText = htmlText.Replace("{link}", $"<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>{_localizer["Create account password"]}</a>");
                htmlText = htmlText.Replace("{login}", user.UserName);

                await _emailSender.SendEmailAsync(Input.Email, _localizer["Password reset"], htmlText);

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Exemplo n.º 29
0
        /// <summary>
        /// Adds the <see cref="RequestLocalizationMiddleware"/> to automatically set culture information for
        /// requests based on information provided by the client using the default options.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="defaultRequestCulture">The default <see cref="RequestCulture"/> to use if none of the
        /// requested cultures match supported cultures.</param>
        /// <returns>The <see cref="IApplicationBuilder"/>.</returns>
        public static IApplicationBuilder UseRequestLocalization(
            this IApplicationBuilder app,
            RequestCulture defaultRequestCulture)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (defaultRequestCulture == null)
            {
                throw new ArgumentNullException(nameof(defaultRequestCulture));
            }

            var options = new RequestLocalizationOptions();

            return(UseRequestLocalization(app, options, defaultRequestCulture));
        }
Exemplo n.º 30
0
        public IActionResult Set(string uiCulture, string returnUrl)
        {
            var languages = Request.GetTypedHeaders()
                            .AcceptLanguage
                            ?.OrderByDescending(x => x.Quality ?? 1) // Quality defines priority from 0 to 1, where 1 is the highest.
                            .Select(x => x.Value.ToString())
                            .ToArray() ?? Array.Empty <string>();

            IRequestCultureFeature feature        = HttpContext.Features.Get <IRequestCultureFeature>();
            RequestCulture         requestCulture = new RequestCulture(feature.RequestCulture.Culture, new CultureInfo(uiCulture));

            string cookieValue = CookieRequestCultureProvider.MakeCookieValue(requestCulture);
            string cookieName  = CookieRequestCultureProvider.DefaultCookieName;

            Response.Cookies.Append(cookieName, cookieValue);

            return(LocalRedirect(returnUrl));
        }
Exemplo n.º 31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddControllers();
            services.AddSingleton <WeatherForecastService>();

            Language[] languages =
            {
                new Language
                {
                    LangId = "en-US",
                    Title  = "English"
                },
                new Language
                {
                    LangId = "it-IT",
                    Title  = "Italiano"
                }
            };

            CultureInfo[] supportedCultures = new CultureInfo[languages.Length];

            for (int i = 0; i < languages.Length; i++)
            {
                supportedCultures[i] = new CultureInfo(languages[i].LangId);
            }

            RequestCulture requestCulture = new RequestCulture("en-US");

            IRequestCultureProvider[] requestCultureProvider = new IRequestCultureProvider[]
            {
                new CookieRequestCultureProvider()
            };

            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.RequestCultureProviders = requestCultureProvider;
                options.DefaultRequestCulture   = requestCulture;
                options.SupportedCultures       = supportedCultures;
                options.SupportedUICultures     = supportedCultures;
            });
        }
Exemplo n.º 32
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            var cultures = new List <CultureInfo>
            {
                new CultureInfo("en-GB"),
                new CultureInfo("th-TH")
            };

            var requestCulture = new RequestCulture("en-GB", "en-GB");

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture   = requestCulture,
                SupportedCultures       = cultures,
                SupportedUICultures     = cultures,
                RequestCultureProviders = new List <IRequestCultureProvider>
                {
                    new CookieRequestCultureProvider
                    {
                        CookieName = "Web.Language"
                    }
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 33
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IStringLocalizer <Startup> sr)
        {
            app.UseIISPlatformHandler();
            var options = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")),
                SupportedCultures     = new CultureInfo[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-AT"),
                    new CultureInfo("de")
                },
                SupportedUICultures = new CultureInfo[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-AT"),
                    new CultureInfo("de")
                }
            };

            app.UseRequestLocalization(options);

            app.Run(async context =>
            {
                IRequestCultureFeature requestCultureFeature = context.Features.Get <IRequestCultureFeature>();
                RequestCulture requestCulture = requestCultureFeature.RequestCulture;



                var today = DateTime.Today;
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync("<h1>Sample Localization</h1>");
                await context.Response.WriteAsync(
                    $"<div>{requestCulture.Culture} {requestCulture.UICulture}</div>");
                await context.Response.WriteAsync($"<div>{today:D}</div>");
                await context.Response.WriteAsync($"<div>{sr["message1"]}</div>");
                await context.Response.WriteAsync($"<div>{sr.WithCulture(new CultureInfo("de-DE")).GetString("message1")}</div>");
                await context.Response.WriteAsync($"<div>{WebUtility.HtmlEncode(sr.GetString("message1"))}</div>");
                await context.Response.WriteAsync(
                    $"<div>{sr.GetString("message2", requestCulture.Culture, requestCulture.UICulture)}</div>");
            });
        }
Exemplo n.º 34
0
        private void SetLanguage()
        {
            PostFromHomeViewModel postModel = new PostFromHomeViewModel();

            RequestCulture requestLanguage = Request.HttpContext.Features.Get <IRequestCultureFeature>().RequestCulture;

            string lang = GetCookieValue(SessionValues.PostLanguage);

            if (lang != null)
            {
                SupportedLanguage langEnum = (SupportedLanguage)Enum.Parse(typeof(SupportedLanguage), lang);
                postModel.DefaultLanguage = langEnum;
            }
            else
            {
                if (!User.Identity.IsAuthenticated)
                {
                    SetAspNetCultureCookie(requestLanguage);
                    postModel.DefaultLanguage = base.SetLanguageFromCulture(requestLanguage.UICulture.Name);
                }
                else
                {
                    UserPreferencesViewModel userPrefs = userPreferencesAppService.GetByUserId(CurrentUserId);

                    if (userPrefs != null && userPrefs.Id != Guid.Empty)
                    {
                        SetAspNetCultureCookie(userPrefs.UiLanguage);

                        SetCookieValue(SessionValues.PostLanguage, postModel.DefaultLanguage.ToString(), 7);

                        postModel.DefaultLanguage = userPrefs.UiLanguage;
                    }
                    else
                    {
                        SetAspNetCultureCookie(requestLanguage);
                        postModel.DefaultLanguage = base.SetLanguageFromCulture(requestLanguage.UICulture.Name);
                    }
                }
            }

            ViewBag.PostFromHome = postModel;
        }
Exemplo n.º 35
0
        public JsonStringLocalizerFactory(
            IHostingEnvironment hostingEnvironment,
            IOptions <JsonLocalizationOptions> options,
            IOptions <RequestLocalizationOptions> requestLocalizationOptions,
            IActionContextAccessor actionContextAccessor,
            ILoggerFactory loggerFactory)
        {
            _options               = options.Value;
            _env                   = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
            _defaultCulture        = requestLocalizationOptions.Value.DefaultRequestCulture;
            _actionContextAccessor = actionContextAccessor ?? throw new ArgumentNullException(nameof(actionContextAccessor));
            _loggerFactory         = loggerFactory;

            _resourcesRelativePath = _options.ResourcesPath ?? string.Empty;
            if (!string.IsNullOrEmpty(_resourcesRelativePath))
            {
                _resourcesRelativePath = _resourcesRelativePath.Replace(Path.AltDirectorySeparatorChar, '.').Replace(Path.DirectorySeparatorChar, '.');
            }

            _globalResources = new JsonGlobalResources(hostingEnvironment, options, _defaultCulture, _loggerFactory);
        }
Exemplo n.º 36
0
        public static IApplicationBuilder UseRequestLocalization(
            this IApplicationBuilder app,
            RequestCulture defaultCulture,
            params RequestCulture[] supportedCultures)
        {
            if (app is null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return(app.UseRequestLocalization(options =>
            {
                options.DefaultRequestCulture = defaultCulture ?? throw new ArgumentNullException(nameof(defaultCulture));

                if (supportedCultures.IsNotNullOrEmpty())
                {
                    options.SupportedCultures = supportedCultures.Select(rc => rc.Culture).ToList();
                    options.SupportedUICultures = supportedCultures.Select(rc => rc.UICulture).ToList();
                }
            }));
        }
Exemplo n.º 37
0
            public void Can_Resolve(string path)
            {
                // Arrange
                var context = CreateRouteContext(path);
                var virtualPathContext = CreateVirtualPathContext(new { });

                var virtualPathResolver = new Mock<IVirtualPathResolver>(MockBehavior.Strict);
                var defaultRequestCulture = new RequestCulture("en");
                var requestCulture = new RequestCulture("en");
                virtualPathResolver.Setup(v => v.Resolve(virtualPathContext, defaultRequestCulture, requestCulture))
                    .Returns("/about");
                
                var route = CreateDefaultRouter(context, new RequestCulture("en"), virtualPathResolver.Object);

                // Act
                VirtualPathData data = route.GetVirtualPath(virtualPathContext);

                // Assert
                Assert.NotNull(data);
                Assert.Equal("/about", data.VirtualPath);
            }
            public async Task Can_Resolve_Home_Page_With_Custom_Action(string path)
            {
                // Arrange
                var context = CreateRouteContext(path);
                var trie = CreateTrie();
                var requestCulture = new RequestCulture("en");

                var trieResolver = new Mock<IRouteResolverTrie>(MockBehavior.Strict);
                trieResolver.Setup(t => t.LoadTrieAsync(requestCulture)).ReturnsAsync(trie);

                var mapper = new Mock<IControllerMapper>(MockBehavior.Strict);
                mapper.Setup(x => x.ControllerHasAction("Home", "about")).Returns(true);

                var routeResolver = new DefaultRouteResolver(trieResolver.Object, mapper.Object);

                // Act
                IResolveResult result = await routeResolver.Resolve(context, requestCulture);

                // Assert
                Assert.NotNull(result);
                Assert.Equal("Home", result.Controller);
                Assert.Equal("about", result.Action);
            }
        public PathString Resolve(VirtualPathContext virtualPathContext, RequestCulture defaultRequestCulture, RequestCulture requestCulture)
        {
            // Handle when the page is added as a route parameter
            object value;
            if (virtualPathContext.Values.TryGetValue("page", out value))
            {
                var page = value as Page;
                if (page == null) return null;

                object culture;
                if (virtualPathContext.Values.TryGetValue("culture", out culture))
                {
                    string cultureValue = culture as string;
                    if (cultureValue != null)
                    {
                        requestCulture = new RequestCulture(cultureValue);
                    }
                }

                var trie = _routeResolverTrie.LoadTrieAsync(requestCulture);
                trie.Wait();

                var node = trie.Result.FirstOrDefault(n => n.Value.PageId == page.Id);

                PathString path = new PathString();
                if (defaultRequestCulture.Culture.Name != requestCulture.Culture.Name)
                {
                    path = path.Add("/" + requestCulture.Culture.TwoLetterISOLanguageName);
                }

                return path.Add(node.Key);
            }

            if (virtualPathContext.Values.TryGetValue("id", out value))
            {
                var id = value as string;
                if (id == null) return null;

                object culture;
                if (virtualPathContext.Values.TryGetValue("culture", out culture))
                {
                    string cultureValue = culture as string;
                    if (cultureValue != null)
                    {
                        requestCulture = new RequestCulture(cultureValue);
                    }
                }

                var trie = _routeResolverTrie.LoadTrieAsync(requestCulture);
                trie.Wait();

                var node = trie.Result.FirstOrDefault(n => n.Value.PageId == id);

                PathString path = new PathString();
                if (defaultRequestCulture.Culture.Name != requestCulture.Culture.Name)
                {
                    path = path.Add("/" + requestCulture.Culture.TwoLetterISOLanguageName);
                }

                return path.Add(node.Key);
            }

            return null;
        }
Exemplo n.º 40
0
        private static DefaultRouter CreateDefaultRouter(RouteContext context, RequestCulture culture, IVirtualPathResolver virtualPathResolver)
        {
            var result = new Mock<IResolveResult>(MockBehavior.Strict);
            result.SetupGet(x => x.Controller).Returns("Home");
            result.SetupGet(x => x.Action).Returns("Index");

            var routeResolver = new Mock<IRouteResolver>(MockBehavior.Strict);
            routeResolver.Setup(x => x.Resolve(context, culture))
                .ReturnsAsync(result.Object);

            return new DefaultRouter(
                CreateTarget(),
                routeResolver.Object,
                virtualPathResolver,
                new RequestCulture("en"));
        }
Exemplo n.º 41
0
        public async Task<IResolveResult> Resolve(RouteContext context, RequestCulture requestCulture)
        {
            var trie = await _routeResolverTrie.LoadTrieAsync(requestCulture);

            if (trie == null || !trie.Any()) return null;

            // Set the default action to index
            var action = DefaultRouter.DefaultAction;

            PathString remaining = context.HttpContext.Request.Path;

            if (context.HttpContext.Request.Path.Value.StartsWith("/" + requestCulture.Culture.TwoLetterISOLanguageName))
            {
                remaining = remaining.Value.Substring(3);
            }

            var segments = remaining.Value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            TrieNode currentNode;

            // The requested url is for the start page with no action
            // so just return the start page
            if (!segments.Any())
            {
                trie.TryGetNode("/", out currentNode);
            }
            else
            {
                var requestPath = NormalizeRequestPath(remaining);

                // The normal behaviour is to load the page based on the incoming url
                trie.TryGetNode(requestPath, out currentNode);

                // Try to find the node without the last segment of the url and set the last segment as action
                if (currentNode == null)
                {
                    action = segments.Last();
                    requestPath = string.Join("/", segments, 0, (segments.Length - 1));
                    trie.TryGetNode("/" + requestPath, out currentNode);
                }
            }

            if (currentNode == null)
            {
                return null;
            }

            if(segments.Any()) { 
                // We always need to check if the last segment is a valid action on the controller for the node we found
                string possibleAction = segments.Last();
                if (_controllerMapper.ControllerHasAction(currentNode.ControllerName, possibleAction))
                {
                    action = possibleAction;
                }
            }

            if (!_controllerMapper.ControllerHasAction(currentNode.ControllerName, action))
            {
                return null;
            }

            return new ResolveResult(currentNode, currentNode.ControllerName, action);
        }