/// <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);
        }
 public async void GetDefaultCultureInfoIfUICultureIsInvalid()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions();
         app.UseRequestLocalization(options);
         app.Run(context =>
         {
             var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
             var requestCulture = requestCultureFeature.RequestCulture;
             Assert.Equal(options.DefaultRequestCulture.UICulture.Name, requestCulture.UICulture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-XY");
     }
 }
 public async void CustomRequestCultureProviderThatGetsCultureInfoFromUrl()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions();
         options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
         {
             var culture = GetCultureInfoFromUrl(context);
             var requestCulture = new RequestCulture(culture);
             return Task.FromResult(requestCulture);
         }));
         app.UseRequestLocalization(options);
         app.Run(context =>
         {
             var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
             var requestCulture = requestCultureFeature.RequestCulture;
             Assert.Equal("ar", requestCulture.Culture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync("/ar/page");
     }
 }
 public async void GetCultureInfoFromPersistentCookie()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions();
         var provider = new CookieRequestCultureProvider();
         provider.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);
         });
     }))
     {
         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);
     }
 }
 public async void GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguageListContainsSupportedCultures()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions
         {
             SupportedCultures = new List<CultureInfo>
             {
                 new CultureInfo("ar-SA"),
                 new CultureInfo("en-US")
             }
         };
         app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("fr-FR"));
         app.Run(context =>
         {
             var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
             var requestCulture = requestCultureFeature.RequestCulture;
             Assert.Equal("ar-SA", requestCulture.Culture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-SA,en-US");
         var count = client.DefaultRequestHeaders.AcceptLanguage.Count;
         var response = await client.GetAsync(string.Empty);
     }
 }
示例#6
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.MinimumLevel = LogLevel.Information;
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            var requestLocalizationOptions = new RequestLocalizationOptions
            {  
                SupportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),

                    new CultureInfo("it-CH")
                },
                SupportedUICultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                }
            };

            app.UseRequestLocalization(requestLocalizationOptions,  new RequestCulture("en-US"));

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

            app.UseMvc();
            app.UseStaticFiles();
        }
        public async void GetCultureInfoFromQueryString()
        {
            using (var server = TestServer.Create(app =>
            {
                var options = new RequestLocalizationOptions()
                {
                    SupportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("ar-SA")
                    },
                    SupportedUICultures = new List<CultureInfo>
                    {
                        new CultureInfo("ar-YE")
                    }
                };

                app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("en-US"));
                app.Run(context =>
                {
                    var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
                    var requestCulture = requestCultureFeature.RequestCulture;
                    Assert.Equal("ar-SA", requestCulture.Culture.Name);
                    Assert.Equal("ar-YE", requestCulture.UICulture.Name);
                    return Task.FromResult(0);
                });
            }))
            {
                var client = server.CreateClient();
                var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-YE");
            }
        }
        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);
            }
        }
        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 async void GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions()
         {
             SupportedCultures = new List<CultureInfo>
             {
                 new CultureInfo("ar-SA")
             },
             SupportedUICultures = new List<CultureInfo>
             {
                 new CultureInfo("ar-SA")
             }
         };
         var provider = new CookieRequestCultureProvider();
         provider.CookieName = "Preferences";
         options.RequestCultureProviders.Insert(0, provider);
         app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("en-US"));
         app.Run(context =>
         {
             var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
             var requestCulture = requestCultureFeature.RequestCulture;
             Assert.Equal("en-US", requestCulture.Culture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", "uic=ar-SA").ToString());
         var response = await client.GetAsync(string.Empty);
     }
 }
        public static void UseBrickPile(this IApplicationBuilder app, Action<RequestLocalizationOptions> configureOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            var options = new RequestLocalizationOptions();
            configureOptions(options);

            options.RequestCultureProviders.Insert(0, new RouteRequestCultureProvider
            {
                Options = options
            });

            app.UseRequestLocalization(options);

            var documentStore = app.ApplicationServices.GetRequiredService<IDocumentStore>();
            var controllerMapper = app.ApplicationServices.GetRequiredService<IControllerMapper>();

            new LocalizationTransformer().Execute(documentStore);
            //IndexCreation.CreateIndexes(typeof(Startup).Assembly, documentStore);

            app.UseMvc(routes =>
            {
                routes.Routes.Insert(0,
                    new DefaultRouter(
                        routes.DefaultHandler,
                        new DefaultRouteResolver(
                            new RouteResolverTrie(documentStore),
                            controllerMapper),
                        new DefaultVirtualPathResolver(
                            new RouteResolverTrie(documentStore),
                            controllerMapper),
                        new RequestCulture("sv")));

                //routes.MapRoute(
                //    name: "default_localization",
                //    template: "{culture?}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "AreasRoute",
                    template: "{area}/{controller=Dashboard}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");                

            });

            app.UseSampleData(options);

        }
示例#12
0
        public void Configure(IApplicationBuilder app)
        {
            // Default to en-CA locale and make sure nothing overrides that choice.
            var options = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-CA"),
            };
            options.RequestCultureProviders.Clear();
            app.UseRequestLocalization(options);

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
        /// <summary>
        /// Creates a new <see cref="RequestLocalizationMiddleware"/>.
        /// </summary>
        /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param>
        /// <param name="options">The <see cref="RequestLocalizationOptions"/> representing the options for the
        /// <see cref="RequestLocalizationMiddleware"/>.</param>
        public RequestLocalizationMiddleware(RequestDelegate next, IOptions<RequestLocalizationOptions> options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

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

            _next = next;
            _options = options.Value;
        }
        /// <summary>
        /// Adds the <see cref="RequestLocalizationMiddleware"/> to automatically set culture information for
        /// requests based on information provided by the client.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="options">The <see cref="RequestLocalizationOptions"/> to configure the middleware with.</param>
        /// <returns>The <see cref="IApplicationBuilder"/>.</returns>
        public static IApplicationBuilder UseRequestLocalization(
            this IApplicationBuilder app,
            RequestLocalizationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<RequestLocalizationMiddleware>(Options.Create(options));
        }
示例#15
0
        public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment)
        {
            applicationBuilder.UseSession();

              if (hostingEnvironment.IsEnvironment("Development"))
              {
            applicationBuilder.UseStatusCodePages();
            applicationBuilder.UseErrorPage();
            applicationBuilder.UseBrowserLink();
              }

              else
              {
            applicationBuilder.UseStatusCodePages();
            applicationBuilder.UseErrorHandler("/Default/Error");
              }

              applicationBuilder.UseStaticFiles();
              applicationBuilder.UseCookieAuthentication(options => {
            options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.AutomaticAuthentication = true;
            options.CookieName = "PLATFORMUS";
            options.ExpireTimeSpan = new System.TimeSpan(1, 0, 0);
            options.LoginPath = new PathString("/Backend/Account/SignIn");
              });

              RequestLocalizationOptions requestLocalizationOptions = new RequestLocalizationOptions();

              requestLocalizationOptions.RequestCultureProviders.Insert(0, new RouteValueRequestCultureProvider());
              applicationBuilder.UseRequestLocalization(requestLocalizationOptions);

              applicationBuilder.UseMvc(routes =>
            {
              // Backend
              routes.MapRoute(name: "Backend Create", template: "{area:exists}/{controller=Default}/create", defaults: new { action = "CreateOrEdit" });
              routes.MapRoute(name: "Backend Edit", template: "{area:exists}/{controller=Default}/edit/{id}", defaults: new { action = "CreateOrEdit" });
              routes.MapRoute(name: "Backend Default", template: "{area:exists}/{controller=Default}/{action=Index}/{id?}");

              // Frontend
              //routes.MapRoute(name: "Standard", template: "{controller=Default}/{action=Index}/{id?}", defaults: new { }, constraints: new { controller = " " });
              routes.MapRoute(name: "Default", template: "{culture=en}/{*url}", defaults: new { controller = "Default", action = "Index" });
            }
              );
        }
        public void Configure(IApplicationBuilder applicationBuilder)
        {
            RequestLocalizationOptions requestLocalizationOptions = new RequestLocalizationOptions();

              requestLocalizationOptions.SupportedCultures = new List<CultureInfo>
              {
            new CultureInfo("en"),
            new CultureInfo("uk")
              };

              requestLocalizationOptions.SupportedUICultures = new List<CultureInfo>
              {
            new CultureInfo("en"),
            new CultureInfo("uk")
              };

              requestLocalizationOptions.RequestCultureProviders.Insert(0, new RouteValueRequestCultureProvider());
              applicationBuilder.UseRequestLocalization(requestLocalizationOptions, new RequestCulture("en"));
        }
 public async void GetDefaultCultureInfoIfCultureKeysAreMissing()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions();
         app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("en-US"));
         app.Run(context =>
         {
             var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
             var requestCulture = requestCultureFeature.RequestCulture;
             Assert.Equal("en-US", requestCulture.Culture.Name);
             Assert.Equal("en-US", requestCulture.UICulture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync("/page");
     }
 }
示例#18
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseCultureReplacer();

            var options = new RequestLocalizationOptions
            {
                SupportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("fr"),
                    new CultureInfo("en-GB")
                },
                SupportedUICultures = new List<CultureInfo>
                {
                    new CultureInfo("fr"),
                    new CultureInfo("en-GB")
                }
            };
            app.UseRequestLocalization(options, new RequestCulture("en-US"));

            app.UseMvcWithDefaultRoute();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> sr)
        {
            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>");
            });
        }
        /// <summary>
        /// Adds the <see cref="RequestLocalizationMiddleware"/> to automatically set culture information for
        /// requests based on information provided by the client.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="options">The options to configure the middleware with.</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,
            RequestLocalizationOptions options,
            RequestCulture defaultRequestCulture)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

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

            return app.UseMiddleware<RequestLocalizationMiddleware>(options, defaultRequestCulture);
        }
        public async void CustomRequestCultureProviderThatGetsCultureInfoFromUrl()
        {
            var builder = new WebApplicationBuilder()
                .Configure(app =>
                {
                    var options = new RequestLocalizationOptions
                    {
                        DefaultRequestCulture = new RequestCulture("en-US"),
                        SupportedCultures = new List<CultureInfo>
                        {
                            new CultureInfo("ar")
                        },
                        SupportedUICultures = new List<CultureInfo>
                        {
                            new CultureInfo("ar")
                        }
                    };
                    options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
                    {
                        var culture = GetCultureInfoFromUrl(context, options.SupportedCultures);
                        var requestCulture = new ProviderCultureResult(culture);
                        return Task.FromResult(requestCulture);
                    }));
                    app.UseRequestLocalization(options);
                    app.Run(context =>
                    {
                        var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
                        var requestCulture = requestCultureFeature.RequestCulture;
                        Assert.Equal("ar", requestCulture.Culture.Name);
                        return Task.FromResult(0);
                    });
                });

            using (var server = new TestServer(builder))
            {
                var client = server.CreateClient();
                var response = await client.GetAsync("/ar/page");
            }
        }
 public async void GetDefaultCultureInfoIfCookieDoesNotExist()
 {
     using (var server = TestServer.Create(app =>
     {
         var options = new RequestLocalizationOptions();
         var provider = new CookieRequestCultureProvider();
         provider.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(options.DefaultRequestCulture.Culture.Name, requestCulture.Culture.Name);
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync(string.Empty);
     }
 }
        /// <summary>
        /// Creates a new <see cref="RequestLocalizationMiddleware"/>.
        /// </summary>
        /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param>
        /// <param name="options">The <see cref="RequestLocalizationOptions"/> representing the options for the
        /// <see cref="RequestLocalizationMiddleware"/>.</param>
        /// <param name="defaultRequestCulture">The default <see cref="RequestCulture"/> to use if none of the
        /// requested cultures match supported cultures.</param>
        public RequestLocalizationMiddleware(
            RequestDelegate next,
            RequestLocalizationOptions options,
            RequestCulture defaultRequestCulture)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

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

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

            _next = next;
            _options = options;
            _defaultRequestCulture = defaultRequestCulture;
        }
示例#24
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            var defaultCulture      = new CultureInfo("en-US");
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(defaultCulture),
                SupportedCultures     = new List <CultureInfo> {
                    defaultCulture
                },
                SupportedUICultures = new List <CultureInfo> {
                    defaultCulture
                }
            };

            app.UseRequestLocalization(localizationOptions);

            app.UseStaticFiles(); // włącza obsługę treści statycznej znajdującej się w katalogu wwwroot
            app.UseSession();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Error",
                    template: "Error",
                    defaults: new { controller = "Error", action = "Error" }
                    );

                routes.MapRoute(
                    name: null,
                    template: "{category}/Strona{productPage:int}",
                    defaults: new { controller = "Product", action = "List" }
                    );

                routes.MapRoute(
                    name: null,
                    template: "Strona{productPage:int}",
                    defaults: new { controller = "Product", action = "List", productPage = 1 }
                    );

                routes.MapRoute(
                    name: null,
                    template: "{category}",
                    defaults: new { controller = "Product", action = "List", productPage = 1 }
                    );

                routes.MapRoute(
                    name: null,
                    template: "",
                    defaults: new { controller = "Product", action = "List", productPage = 1 }
                    );

                routes.MapRoute(
                    name: null,
                    template: "{controller}/{action}/{id?}"
                    );
            });

            // Inicjowanie baz danych:

            // SeedData.EnsurePopulated(app);
            // IdentitySeedData.EnsurePopulated(app);
        }
示例#25
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="userRepository"></param>
        /// <param name="logger"></param>
        /// <param name="visitorRepository"></param>
        /// <param name="serviceProvider"></param>
        /// <param name="lifeTime"></param>
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            IUserRepository userRepository,
            ILogger <Startup> logger,
            IVisitorRepository visitorRepository,
            IServiceProvider serviceProvider,
            IHostApplicationLifetime lifeTime
            )
        {
            if (app is null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (env is null)
            {
                throw new ArgumentNullException(nameof(env));
            }

            if (userRepository is null)
            {
                throw new ArgumentNullException(nameof(userRepository));
            }

            var supportedCultures   = new[] { "en", "sk", "cs" };
            var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
                                      .AddSupportedCultures(supportedCultures)
                                      .AddSupportedUICultures(supportedCultures);

            app.UseRequestLocalization(localizationOptions);


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseCors();
            app.UseStaticFiles();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v1/swagger.json", "API V1");
            });
            app.UserRedisInformation();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            userRepository.CreateAdminUsersFromConfiguration().Wait();

            if (Configuration["SendResults"] == "1")
            {
                logger.LogInformation("SendResults starting..");

                watcher = Task.Factory.StartNew(() =>
                {
                    logger.LogInformation("SendResults acivated");
                    while (!AppExitCancellationTokenSource.IsCancellationRequested)
                    {
                        try
                        {
                            visitorRepository.ProcessSingle().Wait();

                            var random    = new Random();
                            var randDelay = TimeSpan.FromMilliseconds(random.Next(100, 2000));
                            Task.Delay(randDelay).Wait();
                            if (AppExitCancellationTokenSource.IsCancellationRequested)
                            {
                                logger.LogInformation("Exitting task processing");
                                Task.Delay(1000).Wait();
                                lifeTime.StopApplication();
                            }
                        }
                        catch (Exception exc)
                        {
                            logger.LogError(exc, "Error in main sending loop");
                        }
                    }
                    logger.LogInformation("Task processing exitted");
                }, TaskCreationOptions.LongRunning);
            }

            logger.LogInformation($"App started with db prefix {Configuration["db-prefix"]}");
            GC.Collect();
            try
            {
                // For kubernetes readines probe
                File.WriteAllText("ready.txt", DateTimeOffset.Now.ToString("o"));
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }

            if (Args?.Length > 0)
            {
                logger.LogInformation($"Executing task: {Args[0]}");

                switch (Args[0])
                {
                case "export":

                    var exporter = serviceProvider.GetService <ScheduledTasks.ExportTask>();
                    var ret      = exporter.Process().Result;
                    logger.LogInformation($"Export: {ret}");
                    break;
                }

                logger.LogInformation($"Finishing task: {Args[0]} Exitting application");
                lifeTime.StopApplication();

                //throw new Exception("Exit");
            }



            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            {
                logger.LogInformation("ProcessExit!");
                AppExitCancellationTokenSource.Cancel();
                Task.Delay(1000).Wait();
                lifeTime.StopApplication();
            };
        }
 public UrlRequestCultureProvider(RequestLocalizationOptions Options)
 {
     this.Options = Options;
 }
        /// <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="builder">The <see cref="IApplicationBuilder"/>.</param>
        /// <returns>The <see cref="IApplicationBuilder"/>.</returns>
        public static IApplicationBuilder UseRequestLocalization([NotNull] this IApplicationBuilder builder)
        {
            var options = new RequestLocalizationOptions();

            return UseRequestLocalization(builder, options);
        }
示例#28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IUserStore <AppUser>, UserStore>();
            services.AddTransient <IRoleStore <AppRole>, RoleStore>();
            services.AddTransient <IAccountRepository, AccountRepository>();
            services.AddTransient <IFunctionRepository, FunctionRepository>();
            services.AddTransient <IPermissionRepository, PermissionRepository>();
            services.AddTransient <IProductRepository, ProductRepository>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IUserRepository, UserRepository>();

            services.AddIdentity <AppUser, AppRole>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(opt =>
            {
                // Default Password settings.
                opt.Password.RequireDigit           = true;
                opt.Password.RequireLowercase       = false;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequiredLength         = 6;
                opt.Password.RequiredUniqueChars    = 1;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            // multi language
            var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("vi-VN"),
            };

            var options = new RequestLocalizationOptions()
            {
                DefaultRequestCulture = new RequestCulture(culture: "vi-VN", uiCulture: "vi-VN"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            options.RequestCultureProviders = new[]
            {
                new RouteDataRequestCultureProvider()
                {
                    Options = options
                }
            };
            services.AddSingleton(options);
            services.AddSingleton <LocalService>();

            services.AddLocalization(otp => otp.ResourcesPath = "Resources");

            //Add authen fixbug cannot get Claims
            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken            = true;

                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["Tokens:Issuer"],
                    ValidAudience    = Configuration["Tokens:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });

            services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization(otp =>
            {
                otp.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            // end multi language
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title       = "WebAPI Core & Dapper",
                    Version     = "v1",
                    Description = "GetStart API Swagger surface",
                    Contact     = new Contact
                    {
                        Name = "Sonlanggtu"
                    }
                });

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please insert JWT with Bearer into field",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });

                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } }
                });
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

            app.UseSession();

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("CreateUser", context =>
            {
                var firstName   = context.Request.Query["firstName"];
                var lastName    = context.Request.Query["lastName"];
                var email       = context.Request.Query["email"];
                var password    = context.Request.Query["password"];
                var userService = context.RequestServices.GetService <IUserService>();
                userService.RegisterUser(new UserModel {
                    FirstName = firstName, LastName = lastName, Email = email, Password = password
                });
                return(context.Response.WriteAsync($"User {firstName} {lastName} has been successfully created."));
            });

            var newUserRoutes = routeBuilder.Build();

            app.UseRouter(newUserRoutes);

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();

            app.UseWebSockets();

            app.UseCommunicationMiddleware();

            var supportedCultures =
                CultureInfo.GetCultures(CultureTypes.AllCultures);
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            localizationOptions.RequestCultureProviders.Clear();
            localizationOptions.RequestCultureProviders.Add(new
                                                            CultureProviderResolverService());

            app.UseRequestLocalization(localizationOptions);
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "LEARNING ASP.CORE 3.0 V1");
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapAreaControllerRoute(
                    name: "areas",
                    areaName: "Account",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    );
            });

            app.UseStatusCodePages("text/plain", "HTTP Error - Status Code: {0}");
            var provider     = app.ApplicationServices;
            var scopeFactory =
                provider.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
                using (var context = scope.ServiceProvider.GetRequiredService <GameDbContext>())
                {
                    context.Database.Migrate();
                }
        }
示例#30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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.UseStaticFiles();
            app.UseSession();

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("CreateUser", context =>
            {
                var firstName   = context.Request.Query["firstName"];
                var lastName    = context.Request.Query["lastName"];
                var email       = context.Request.Query["email"];
                var password    = context.Request.Query["password"];
                var userService = context.RequestServices.GetService <IUserService>();
                userService.RegisterUser(new UserModel {
                    FirstName = firstName, LastName = lastName, Email = email, Password = password
                });
                return(context.Response.WriteAsync($"User {firstName} {lastName} has been sucessfully created."));
            });

            var newUserRoutes = routeBuilder.Build();

            app.UseRouter(newUserRoutes);

            app.UseRouting();

            app.UseAuthorization();

            app.UseWebSockets();

            //app.UseCommunicationMiddleware();

            var supportedCultures   = CultureInfo.GetCultures(CultureTypes.AllCultures);
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            localizationOptions.RequestCultureProviders.Clear();
            localizationOptions.RequestCultureProviders.Add(new CultureProviderResolverService());

            app.UseRequestLocalization(localizationOptions);
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 public SelectLanguageController(IOptions <RequestLocalizationOptions> requestLocalizationOptions)
 {
     _requestLocalizationOptions = requestLocalizationOptions.Value;
 }
        public async void GetDefaultCultureInfoIfCookieDoesNotExist()
        {
            var builder = new WebApplicationBuilder()
                .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();
                    provider.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("en-US", requestCulture.Culture.Name);
                        return Task.FromResult(0);
                    });
                });

            using (var server = new TestServer(builder))
            {
                var client = server.CreateClient();
                var response = await client.GetAsync(string.Empty);
            }
        }
示例#33
0
        public async Task GetCultureInfo_FromRouteData_WithCustomKeys(
            string routeTemplate,
            string requestUrl,
            string expectedCulture,
            string expectedUICulture)
        {
            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseRouter(routes =>
                {
                    routes.MapMiddlewareRoute(routeTemplate, fork =>
                    {
                        var options = new RequestLocalizationOptions
                        {
                            DefaultRequestCulture = new RequestCulture("en-US"),
                            SupportedCultures     = new List <CultureInfo>
                            {
                                new CultureInfo("ar-SA")
                            },
                            SupportedUICultures = new List <CultureInfo>
                            {
                                new CultureInfo("ar-YE")
                            }
                        };
                        options.RequestCultureProviders = new[]
                        {
                            new RouteDataRequestCultureProvider()
                            {
                                Options              = options,
                                RouteDataStringKey   = "c",
                                UIRouteDataStringKey = "uic"
                            }
                        };
                        fork.UseRequestLocalization(options);

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

                            return(context.Response.WriteAsync(
                                       $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"));
                        });
                    });
                });
            })
                          .ConfigureServices(services =>
            {
                services.AddRouting();
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync(requestUrl);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                var data = await response.Content.ReadAsStringAsync();

                Assert.Equal($"{expectedCulture},{expectedUICulture}", data);
            }
        }
示例#34
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            //http://blog.getglimpse.com/2015/11/19/installing-glimpse-v2-beta1/
            bool enableGlimpse = Configuration.Get<bool>("DiagnosticOptions:EnableGlimpse", false);
            if(enableGlimpse)
            {
                app.UseGlimpse();
            }


            // LogLevels
            //Debug = 1,
            //Trace = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            
            // Add the console logger.
            loggerFactory.AddConsole(minLevel: LogLevel.Warning);
            
            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Warning;
            List<string> excludedLoggers = new List<string>();
            // add exclusions to remove noise in the logs

            // we need to filter out EF otherwise each time we persist a log item to the db more logs are generated
            // so it can become an infinite loop that keeps creating data
            // you can add any loggers that you want to exclude to reduce noise in the log
            excludedLoggers.Add("Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory");
            excludedLoggers.Add("Microsoft.Data.Entity.Query.Internal.QueryCompiler");
            excludedLoggers.Add("Microsoft.Data.Entity.DbContext");

            Func<string, LogLevel, bool> logFilter = delegate (string loggerName, LogLevel logLevel)
            {
                if (logLevel < minimumLevel) { return false; }
                if(excludedLoggers.Contains(loggerName)) { return false; }

                return true;
            };
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository, logFilter);
            


            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("it"),
                new CultureInfo("fr-FR")
            };

            var locOptions = new RequestLocalizationOptions
            {
                // You must explicitly state which cultures your application supports.
                // These are the cultures the app supports for formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                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
            //locOptions.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{
            //  // My custom request culture logic
            //  return new ProviderCultureResult("en");
            //}));
            //app.UseRequestLocalization(locOptions, 
            //    defaultRequestCulture: new RequestCulture(culture: "en-US", uiCulture: "en-US"));

            
            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();
                
                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                
                app.UseExceptionHandler("/Home/Error");

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            //app.UseIISPlatformHandler();
            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();
            
            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));

            app.UseMultitenancy<SiteSettings>();

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions,Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown

            
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and 
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a 
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better 
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use 
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                    name: "folderdefault",
                    template: "{sitefolder}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { name = new SiteFolderRouteConstraint() }
                    );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled 
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});

            DevOptions devOptions = Configuration.Get<DevOptions>("DevOptions");
            if (devOptions.DbPlatform == "ef7")
            {
                cloudscribe.Core.Repositories.EF.InitialData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
                // this is using EF for the logger but using EF for Core does not mean you must use EF for logging
                // one should be able to use the MSSQL Logger while still using EF for the core repos
                // one problem with EF logging is that EF logs a lot of information stuff and if we use EF for logigng
                // then every time a log item is inserted to the db it generates more logging events
                // and thus a continuous creation of data can result so the EF logger is designed to leave out
                // EF components from logging
                // by using the mssql logger instead then no extra log items will be created and you can more easily allow
                // EF to log things of its own
                // however the mssql logger depends on the setup system which is not used by EF components
                // this dependency is more practical than technical though, you could run the db setup script for mssql logging
                // manually instead of using the setup system.
                cloudscribe.Logging.EF.DbInitializer.InitializeDatabaseAsync(app.ApplicationServices).Wait();
            }



        }
示例#35
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            GetHabitsContext context, GetHabitsIdentity identContext, GoogleAuthHelper googleAuthHelper, ApplicationHelper appHelper)
        {
            if (env.IsProduction())
            {
                loggerFactory.AddConsole(LogLevel.Verbose);
            }
            else
            {
                loggerFactory.AddConsole(LogLevel.Verbose);
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage(opt => opt.EnableAll());
            }

            app.UseStaticFiles();

            //TODO do checks
            context.Database.Migrate();
            identContext.Database.Migrate();

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
                options.LoginPath = new PathString("/account/login");
                options.LogoutPath = new PathString("/account/logoff");
                options.AuthenticationScheme = appHelper.DefaultAuthScheme;
            });

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = false;
                options.AuthenticationScheme = appHelper.TempAuthScheme;
            });

            var clientId = Configuration.GetSection("Authentication:Google:ClientId").Value;
            var clientSecret = Configuration.GetSection("Authentication:Google:ClientSecret").Value;

            app.UseGoogleAuthentication(options =>
            {
                options.ClientId = clientId;
                options.ClientSecret = clientSecret;
                options.AuthenticationScheme = googleAuthHelper.ProviderName;
                options.AutomaticAuthenticate = false;
                options.SignInScheme = appHelper.TempAuthScheme;

                options.Events = new OAuthEvents()
                {
                    OnRemoteError = async errorContext =>
                    {
                        var error = errorContext.Error;
                        errorContext.Response.Redirect("/error?ErrorMessage=" + UrlEncoder.Default.UrlEncode(errorContext.Error.Message));
                        errorContext.HandleResponse();
                        await Task.FromResult(0);
                    }
                };
            });

            var localizationOptions = new RequestLocalizationOptions()
            {
                SupportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("ru-RU")
                },
                SupportedUICultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("ru-RU")
                }
            };

            localizationOptions.RequestCultureProviders.Insert(0, new FirstAddressSegmentCultureProvider(appHelper));

            app.UseRequestLocalization(localizationOptions, new RequestCulture("ru-RU"));

            app.UseIISPlatformHandler();

            app.UseMvc(routeBuilder =>
            {
                routeBuilder.MapRoute("applicationRoute", "app/{*all}", new { controller = "App", action = "Index"});
                routeBuilder.MapRoute("localizedRoute", "{langname}/{controller=Home}/{action=Index}/{id?}", null, new { langname = new RequestLocalizedRouteConstraint(appHelper.LangNameAndCultureNameCorresponding.Keys) });
                routeBuilder.MapRoute("unLocalizedRoute", "{*allPath}", new { controller = "Localize", action = "UnLocalizedRequest" }, new { allPath = new RequestUnLocalizedRouteConstraint(appHelper.LangNameAndCultureNameCorresponding.Keys) });
            });
        }
示例#36
0
        public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> SR)
        {
            var options = new RequestLocalizationOptions
            {
                // Set options here to change middleware behavior
                //SupportedCultures = new List<CultureInfo>
                //{
                //    new CultureInfo("en-US"),
                //    new CultureInfo("en-AU")
                //},
                //SupportedUICultures = new List<CultureInfo>
                //{
                //    new CultureInfo("en-US"),
                //    new CultureInfo("en-AU")
                //}
            };

            // Optionally create an app-specific provider with just a delegate, e.g. look up user preference from DB.
            // Inserting it as position 0 ensures it has priority over any of the default providers.
            //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{
                
            //}));

            app.UseRequestLocalization(options);

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.EndsWith("favicon.ico"))
                {
                    // Pesky browsers
                    context.Response.StatusCode = 404;
                    return;
                }

                context.Response.StatusCode = 200;
                context.Response.ContentType = "text/html; charset=utf-8";

                var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
                var requestCulture = requestCultureFeature.RequestCulture;

                await context.Response.WriteAsync(
$@"<!doctype html>
<html>
<head>
    <title>{SR["Request Localization"]}</title>
    <style>
        body {{ font-family: 'Segoe UI', Helvetica, Sans-Serif }}
        h1, h2, h3, h4, th {{ font-family: 'Segoe UI Light', Helvetica, Sans-Serif }}
        th {{ text-align: left }}
    </style>
    <script>
        function useCookie() {{
            var culture = document.getElementById('culture');
            var uiCulture = document.getElementById('uiCulture');
            var cookieValue = '{CookieRequestCultureProvider.DefaultCookieName}=c='+culture.options[culture.selectedIndex].value+'|uic='+uiCulture.options[uiCulture.selectedIndex].value;
            document.cookie = cookieValue;
            window.location = window.location.href.split('?')[0];
        }}

        function clearCookie() {{
            document.cookie='{CookieRequestCultureProvider.DefaultCookieName}=""""';
        }}
    </script>
</head>
<body>");
                await context.Response.WriteAsync($"<h1>{SR["Request Localization Sample"]}</h1>");
                await context.Response.WriteAsync($"<h1>{SR["Hello"]}</h1>");
                await context.Response.WriteAsync("<form id=\"theForm\" method=\"get\">");
                await context.Response.WriteAsync($"<label for=\"culture\">{SR["Culture"]}: </label>");
                await context.Response.WriteAsync("<select id=\"culture\" name=\"culture\">");
                await WriteCultureSelectOptions(context);
                await context.Response.WriteAsync("</select><br />");
                await context.Response.WriteAsync($"<label for=\"uiCulture\">{SR["UI Culture"]}: </label>");
                await context.Response.WriteAsync("<select id=\"uiCulture\" name=\"ui-culture\">");
                await WriteCultureSelectOptions(context);
                await context.Response.WriteAsync("</select><br />");
                await context.Response.WriteAsync("<input type=\"submit\" value=\"go QS\" /> ");
                await context.Response.WriteAsync($"<input type=\"button\" value=\"go cookie\" onclick='useCookie();' /> ");
                await context.Response.WriteAsync($"<a href=\"/\" onclick='clearCookie();'>{SR["reset"]}</a>");
                await context.Response.WriteAsync("</form>");
                await context.Response.WriteAsync("<br />");
                await context.Response.WriteAsync("<table><tbody>");
                await context.Response.WriteAsync($"<tr><th>Winning provider:</th><td>{requestCultureFeature.Provider.GetType().Name}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current request culture:"]}</th><td>{requestCulture.Culture.DisplayName} ({requestCulture.Culture})</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current request UI culture:"]}</th><td>{requestCulture.UICulture.DisplayName} ({requestCulture.UICulture})</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current thread culture:"]}</th><td>{CultureInfo.CurrentCulture.DisplayName} ({CultureInfo.CurrentCulture})</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current thread UI culture:"]}</th><td>{CultureInfo.CurrentUICulture.DisplayName} ({CultureInfo.CurrentUICulture})</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current date (invariant full):"]}</th><td>{DateTime.Now.ToString("F", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current date (invariant):"]}</th><td>{DateTime.Now.ToString(CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current date (request full):"]}</th><td>{DateTime.Now.ToString("F")}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current date (request):"]}</th><td>{DateTime.Now.ToString()}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current time (invariant):"]}</th><td>{DateTime.Now.ToString("T", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Current time (request):"]}</th><td>{DateTime.Now.ToString("T")}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Big number (invariant):"]}</th><td>{(Math.Pow(2, 42) + 0.42).ToString("N", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Big number (request):"]}</th><td>{(Math.Pow(2, 42) + 0.42).ToString("N")}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Big number negative (invariant):"]}</th><td>{(-Math.Pow(2, 42) + 0.42).ToString("N", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Big number negative (request):"]}</th><td>{(-Math.Pow(2, 42) + 0.42).ToString("N")}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Money (invariant):"]}</th><td>{2199.50.ToString("C", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Money (request):"]}</th><td>{2199.50.ToString("C")}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Money negative (invariant):"]}</th><td>{(-2199.50).ToString("C", CultureInfo.InvariantCulture)}</td></tr>");
                await context.Response.WriteAsync($"<tr><th>{SR["Money negative (request):"]}</th><td>{(-2199.50).ToString("C")}</td></tr>");
                await context.Response.WriteAsync("</tbody></table>");
                await context.Response.WriteAsync(
@"</body>
</html>");
            });
        }
示例#37
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            // LogLevels
            //Debug = 1,
            //Verbose = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            loggerFactory.MinimumLevel = LogLevel.Information;
            // Add the console logger.
            loggerFactory.AddConsole();
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository);

            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var localizationOptions = new RequestLocalizationOptions
            {
                // Set options here to change middleware behavior
                
                //DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")),
                SupportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                },
                SupportedUICultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                }
                

            };



            // Optionally create an app-specific provider with just a delegate, e.g. look up user preference from DB.
            // Inserting it as position 0 ensures it has priority over any of the default providers.
            //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{

            //}));

            //app.UseRequestLocalization(localizationOptions);
            var defaultCulture = new RequestCulture(new CultureInfo("en-US"));
            //app.UseRequestLocalization(localizationOptions, defaultCulture);


            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();
                
                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                //app.UseErrorHandler("/Home/Error");
                //app.UseErrorPage(ErrorPageOptions.ShowAll);

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            //app.UseIISPlatformHandler();
            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));
            

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions,Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown

            
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and 
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a 
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better 
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use 
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                    name: "folderdefault",
                    template: "{sitefolder}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { name = new SiteFolderRouteConstraint() }
                    );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled 
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});



        }
        public void Configure(
            IApplicationBuilder app,
            ILoggerFactory loggerFactory,
            IStringLocalizerFactory stringLocalizerFactory,
            IStringLocalizer<StartupResourcesInFolder> startupStringLocalizer,
            IStringLocalizer<Customer> custromerStringLocalizer)
        {
            loggerFactory.AddConsole(minLevel: LogLevel.Warning);

            var options = new RequestLocalizationOptions
            {
                SupportedCultures = new List<CultureInfo>()
                {
                    new CultureInfo("fr-FR")
                },
                SupportedUICultures = new List<CultureInfo>()
                {
                    new CultureInfo("fr-FR")
                }
            };

            app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("en-US"));

            var stringLocalizer = stringLocalizerFactory.Create("Test", location: null);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(startupStringLocalizer["Hello"]);
                await context.Response.WriteAsync(" ");
                await context.Response.WriteAsync(stringLocalizer["Hello"]);
                await context.Response.WriteAsync(" ");
                await context.Response.WriteAsync(custromerStringLocalizer["Hello"]);
            });
        }