public AuthenticationServiceIT()
 {
     var options = Options.Create(new LocalizationOptions { ResourcesPath = "Resources" });
     var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
     _stringLocalizer = new StringLocalizer<UserResource>(factory);
     _tenantFrameworkSl = new StringLocalizer<TenantFrameworkResource>(factory);
 }
        public static void ConfigureServices(IServiceCollection services)
        {
            CultureInfo.CurrentCulture   = CultureInfo.GetCultureInfo("en-US");
            CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");

            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            services.Configure <MongoDbSettings>(configuration.GetSection(nameof(MongoDbSettings)));

            services.AddSingleton(sp =>
                                  sp.GetRequiredService <IOptions <MongoDbSettings> >().Value);

            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory         = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var stringLocalizer = new StringLocalizer <TenantFrameworkResource>(factory);

            services.AddSingleton <IStringLocalizer <TenantFrameworkResource> >(stringLocalizer);

            services.AddSingleton <ITenantAccessService, TestTenantAccessService>();

            services.AddSingleton <DbFixture, DbFixture>();
            services.AddSingleton <ITenantRepository, TenantRepository>();
        }
Exemple #3
0
        public UserControllerTests()
        {
            var _config = new ConfigurationBuilder().AddUserSecrets <UserControllerTests>().Build();

            var _logger = new Mock <ILogger <UsersController> >();

            _userSecretSetting = new UserSecretSetting()
            {
                EncryptionKey      = _config["EncryptionKey"],
                GoogleClientId     = _config["Authentication:Google:ClientId"],
                GoogleClientSecret = _config["Authentication:Google:ClientSecret"]
            };
            var userSettingOption  = Options.Create(_userSecretSetting);
            var userRepositoryMock = new Mock <IUserRepository>();
            var builder            = new ConfigurationBuilder().AddUserSecrets <UserControllerTests>();
            var options            = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            _localizer = new StringLocalizer <UsersController>(factory);
            var usersDbOptions = new DbContextOptionsBuilder <UserContext>().UseInMemoryDatabase(databaseName: "GmailPOC").Options;

            _userContext = new UserContext(usersDbOptions);
            TestHelper.AddDummyEventData(_userContext);
            TestHelper.AddDummyEventAttendee(_userContext);
            TestHelper.AddDummyRecurringEvent(_userContext);
            _userRepository = new UserRepository(_userContext);
            _userService    = new UserService(_userServiceLogger, _userRepository);
            _userController = new UsersController(_userService, _logger.Object, userSettingOption, _localizer);
        }
        public void VerifyAllSharedPropsAreInEnglishResx()
        {
            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory   = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var localizer = new StringLocalizer <SharedResource>(factory);

            var sharedResourceAsm = Assembly.Load("SIL.XForge.Scripture");

            Assert.NotNull(sharedResourceAsm, "Um, what did you refactor?");
            var sharedResourceClass = sharedResourceAsm.GetType("SIL.XForge.Scripture.SharedResource");
            var sharedKeys          = sharedResourceClass?.GetNestedType("Keys");

            Assert.NotNull(sharedKeys, "Um, what did you refactor?");
            // grab all the localization keys from SharedResource.Keys static class
            var publicProps = sharedKeys.GetFields(BindingFlags.Public | BindingFlags.Static);

            foreach (var propInfo in publicProps.Where(x => x.FieldType == typeof(string)))
            {
                var keyValue = (string)propInfo.GetValue(null);
                var englishStringFromResource = localizer.GetString(keyValue);
                // verify that each key is found
                Assert.IsFalse(englishStringFromResource.ResourceNotFound,
                               "Missing english string from .resx for " + propInfo.Name);
            }

            Assert.AreEqual(publicProps.Length, localizer.GetAllStrings().Count(),
                            "There are extra strings in the SharedResources.en.resx which are not in the SharedResource.Keys class");
        }
        private static void Example(string culture)
        {
            var cultureInfo = CultureInfo.GetCultureInfo(culture);

            Console.Out.WriteLine($"{cultureInfo.EnglishName}:");
            Thread.CurrentThread.CurrentUICulture = cultureInfo;

            try
            {
                ThrowException();
            }
            catch (Exception exception)
            {
                if (exception is ITranslatableException translatableException)
                {
                    var x = new ResourceManagerStringLocalizerFactory(Options.Create(new LocalizationOptions()), NullLoggerFactory.Instance);
                    Console.Error.WriteLine(translatableException.GetMessage(x));
                }
                else
                {
                    throw new NotSupportedException();
                }
                Console.Error.WriteLine();
            }
        }
        public AccountControllerTest()
        {
            var dataContext = TestHelpers.GetDataContext();

            AutoMapperConfig.Initialize();
            var mapper = AutoMapperConfig.GetMapper();

            var options = Options.Create(new LocalizationOptions());  // you should not need any params here if using a StringLocalizer<T>
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            var defaultHttpContext = new DefaultHttpContext();
//                TestHelpers.GetTestHttpContext();
            //Mock IHttpContextAccessor
            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();

            mockHttpContextAccessor.Setup(m => m.HttpContext).Returns(defaultHttpContext);
            var httpContextAccessor = mockHttpContextAccessor.Object;

            IUserService userService = new UserService(dataContext, mapper);
            ILocalizationService <UserResource> localizerService      = new LocalizationService <UserResource>(factory);
            IUserAuthenticationService          authenticationService = new UserAuthenticationService(httpContextAccessor);

//            var httpContext = new DefaultHttpContext();
            var tempData = new TempDataDictionary(defaultHttpContext, Mock.Of <ITempDataProvider>());

            _accountController = new AccountController(userService, localizerService, authenticationService)
            {
                TempData = tempData
            };
        }
            public TestEnvironment()
            {
                UserSecrets = new MemoryRepository <UserSecret>(new[]
                {
                    new UserSecret {
                        Id = "user01"
                    },
                    new UserSecret {
                        Id = "user03"
                    }
                });

                RealtimeService = new SFMemoryRealtimeService();

                ParatextService = Substitute.For <IParatextService>();
                ParatextService.GetParatextUsername(Arg.Is <UserSecret>(u => u.Id == "user01")).Returns("PT User 1");
                ParatextService.GetParatextUsername(Arg.Is <UserSecret>(u => u.Id == "user03")).Returns("PT User 3");
                var options = Microsoft.Extensions.Options.Options.Create(new LocalizationOptions
                {
                    ResourcesPath = "Resources"
                });
                var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

                Localizer = new StringLocalizer <SharedResource>(factory);
                var siteOptions = Substitute.For <IOptions <SiteOptions> >();

                siteOptions.Value.Returns(new SiteOptions
                {
                    Name = "xForge",
                });
                Mapper = new ParatextNotesMapper(UserSecrets, ParatextService, Localizer, siteOptions);
            }
Exemple #8
0
        static LocalizationUtils()
        {
            var options = Options.Create(new LocalizationOptions());
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var type    = typeof(TEntity);

            _localizer = factory.Create(type);
        }
Exemple #9
0
        public TestHelper()
        {
            var options = Options.Create(new LocalizationOptions());
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            Localizer          = new StringLocalizer <Localization>(factory);
            CuesheetController = new CuesheetController(Localizer);
        }
        private static List <SimpleMenu> GetAllMenus(List <SimpleModule> allModule, Configs ConfigInfo)
        {
            var localizer = new ResourceManagerStringLocalizerFactory(Options.Create <LocalizationOptions>(new LocalizationOptions {
                ResourcesPath = "Resources"
            }), new Microsoft.Extensions.Logging.LoggerFactory()).Create(typeof(KnifeZ.Virgo.Core.CoreProgram));
            var menus = new List <SimpleMenu>();

            if (ConfigInfo.IsQuickDebug)
            {
                menus = new List <SimpleMenu>();
                var areas = allModule.Where(x => x.NameSpace != "KnifeZ.Virgo.Admin.Api").Select(x => x.Area?.AreaName).Distinct().ToList();
                foreach (var area in areas)
                {
                    var modelmenu = new SimpleMenu
                    {
                        ID       = Guid.NewGuid(),
                        PageName = area ?? localizer["Sys.DefaultArea"]
                    };
                    menus.Add(modelmenu);
                    var pages = allModule.Where(x => x.NameSpace != "KnifeZ.Virgo.Admin.Api" && x.Area?.AreaName == area).SelectMany(x => x.Actions).Where(x => x.MethodName.ToLower() == "index").ToList();
                    foreach (var page in pages)
                    {
                        var url = page.Url;
                        menus.Add(new SimpleMenu
                        {
                            ID       = Guid.NewGuid(),
                            ParentId = modelmenu.ID,
                            PageName = page.Module.ActionDes == null ? page.Module.ModuleName : page.Module.ActionDes.Description,
                            Url      = url
                        });
                    }
                }
            }
            else
            {
                try
                {
                    using (var dc = ConfigInfo.Connections.Where(x => x.Key.ToLower() == "default").FirstOrDefault().CreateDC())
                    {
                        menus.AddRange(dc?.Set <FrameworkMenu>()
                                       .OrderBy(x => x.DisplayOrder)
                                       .Select(x => new SimpleMenu
                        {
                            ID           = x.ID,
                            ParentId     = x.ParentId,
                            PageName     = x.PageName,
                            Url          = x.Url,
                            DisplayOrder = x.DisplayOrder,
                            ShowOnMenu   = x.ShowOnMenu,
                            Icon         = x.ICon,
                        })
                                       .ToList());
                    }
                }
                catch { }
            }
            return(menus);
        }
Exemple #11
0
        private StringLocalizer <EnterResultViewModel> CreateModelStringLocalizer()
        {
            // no need for any params if using a StringLocalizer<T>
            var options = Microsoft.Extensions.Options.Options.Create(new LocalizationOptions());
            var factory = new ResourceManagerStringLocalizerFactory(options, Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance);

            // Note: The resource is also used by System.ComponentModel.DataAnnotations
            return(new StringLocalizer <EnterResultViewModel>(factory));
        }
Exemple #12
0
 public Index(IOptions <AbpLocalizationOptions> abpLocalizationOptions,
              ResourceManagerStringLocalizerFactory innerFactory,
              ILanguageProvider languageProvider, IVirtualFileProvider virtualFileProvider) : this()
 {
     this.abpLocalizationOptions = abpLocalizationOptions;
     InnerFactory        = innerFactory;
     LanguageProvider    = languageProvider;
     VirtualFileProvider = virtualFileProvider;
 }
Exemple #13
0
        /// <summary>
        /// Creates <see cref="ResourceManagerStringLocalizerFactory"/> and then adapts it into <see cref="IAsset"/>.
        ///
        /// This asset serves keys that have Assembly and Resource hints, or Type{T}() hint.
        /// <code>
        ///  var resx_key = root.Assembly("MyAssembly").Resource("Resources").Type("localization");
        ///  var key = resx_key["Success"];
        /// </code>
        ///
        /// This asset is needed if <see cref="ILineRoot"/> is converted to <see cref="IStringLocalizerFactory" />.
        /// </summary>
        /// <param name="resourcePath"></param>
        /// <param name="loggerFactory"></param>
        /// <returns></returns>
        public static IAsset CreateFactory(string resourcePath, ILoggerFactory loggerFactory)
        {
            IOptions <LocalizationOptions> options = Options.Create(new LocalizationOptions {
                ResourcesPath = resourcePath
            });
            ResourceManagerStringLocalizerFactory factory = new ResourceManagerStringLocalizerFactory(options, loggerFactory);

            return(new StringLocalizerFactoryAsset(factory));
        }
        public AuthenticationControllerIT()
        {
            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            _stringLocalizer = new StringLocalizer <UserResource>(factory);
        }
Exemple #15
0
        /// <summary>
        /// Creates <see cref="ResourceManagerStringLocalizer"/> and then adapts it into <see cref="IAsset"/>.
        ///
        /// Search path = Assembly.RootNameSpace + [.resourcesPath] + filename + [.culture] + ".resx"
        /// </summary>
        /// <param name="asmRef">"Location" assembly name, short name or full name.</param>
        /// <param name="resourcePath">(optional) embedded resource folder, e.g. "Resources"</param>
        /// <param name="filename">"basename" name of the resx file, e.g. "localization", searches for "localization.xx.resx"</param>
        /// <param name="loggerFactory"></param>
        /// <exception cref="ArgumentNullException">assemblyRef is null</exception>
        /// <exception cref="FileNotFoundException">assemblyRef is not found.</exception>
        /// <exception cref="FileLoadException">A file that was found could not be loaded.</exception>
        /// <exception cref="BadImageFormatException">assemblyRef is not a valid assembly</exception>
        public static IAsset Create(string asmRef, string resourcePath, string filename, ILoggerFactory loggerFactory)
        {
            IOptions <LocalizationOptions> options = Options.Create(new LocalizationOptions {
                ResourcesPath = resourcePath
            });
            ResourceManagerStringLocalizerFactory factory = new ResourceManagerStringLocalizerFactory(options, loggerFactory);
            IStringLocalizer stringLocalizer = factory.Create(filename, asmRef);

            return(new StringLocalizerAsset.Location(stringLocalizer, filename, asmRef, null));
        }
Exemple #16
0
        /// <summary>
        /// Creates <see cref="ResourceManagerStringLocalizer"/> and then adapts it into <see cref="IAsset"/>.
        ///
        /// Search path = Assembly.RootNameSpace + [.resourcesPath] + filename + [.culture] + ".resx"
        /// </summary>
        /// <param name="resourcePath">(optional) embedded resource folder, e.g. "Resources"</param>
        /// <param name="type">type searches for "typename.xx.resx"</param>
        /// <param name="loggerFactory"></param>
        /// <exception cref="ArgumentNullException">assemblyRef is null</exception>
        /// <exception cref="FileNotFoundException">assemblyRef is not found.</exception>
        /// <exception cref="FileLoadException">A file that was found could not be loaded.</exception>
        /// <exception cref="BadImageFormatException">assemblyRef is not a valid assembly</exception>
        public static IAsset Create(string resourcePath, Type type, ILoggerFactory loggerFactory)
        {
            IOptions <LocalizationOptions> options = Options.Create(new LocalizationOptions {
                ResourcesPath = resourcePath
            });
            ResourceManagerStringLocalizerFactory factory = new ResourceManagerStringLocalizerFactory(options, loggerFactory);
            IStringLocalizer stringLocalizer = factory.Create(type);

            return(new StringLocalizerAsset.Type(stringLocalizer, type, null));
        }
Exemple #17
0
        public static IStringLocalizer <SharedResource> GetLocalization()
        {
            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory   = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var localizer = new StringLocalizer <SharedResource>(factory);

            return(localizer);
        }
Exemple #18
0
 public MutilStringLocalizerFactory(
     SqlStringLocalizerFactory sqlStringLocalizerFactory,
     ResourceManagerStringLocalizerFactory resourceManagerStringLocalizerFactory)
 {
     _stringLocalizerFactories = new IStringLocalizerFactory[]
     {
         sqlStringLocalizerFactory,
         resourceManagerStringLocalizerFactory,
     };
 }
        public TenantToolsTest(ILogger <TenantToolsTest> logger)
        {
            _logger = logger;

            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            _sl = new StringLocalizer <TenantFrameworkResource>(factory);
        }
Exemple #20
0
        static SR()
        {
            var locOptions = new LocalizationOptions()
            {
                ResourcesPath = "resources"
            };
            var options         = Options.Create <LocalizationOptions>(locOptions);
            var resourceFactory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            localizer = resourceFactory.Create(typeof(SR));
        }
Exemple #21
0
        internal static IValidationLocalizer GetValidationLocalizer()
        {
            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = ""
            });
            var factory        = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var fieldLocalizer = new OwnLocalizer <FieldNameConstants>(factory);
            var localizer      = new OwnLocalizer <ValidationConstants>(factory);

            return(new ValidationLocalizer(localizer, fieldLocalizer));
        }
        //TODO: It's better to use decorator pattern for IStringLocalizerFactory instead of getting ResourceManagerStringLocalizerFactory as a dependency.
        public AbpStringLocalizerFactory(
            ResourceManagerStringLocalizerFactory innerFactory,
            IOptions <AbpLocalizationOptions> abpLocalizationOptions,
            IServiceProvider serviceProvider)
        {
            InnerFactory           = innerFactory;
            ServiceProvider        = serviceProvider;
            AbpLocalizationOptions = abpLocalizationOptions.Value;

            LocalizerCache = new ConcurrentDictionary <Type, StringLocalizerCacheItem>();
        }
Exemple #23
0
        //TODO: It's better to use decorator pattern for IStringLocalizerFactory instead of getting ResourceManagerStringLocalizerFactory as a dependency.
        public AbpStringLocalizerFactory(
            ResourceManagerStringLocalizerFactory innerFactory,
            IOptions <AbpLocalizationOptions> abpLocalizationOptions,
            IServiceProvider serviceProvider)
        {
            _innerFactory           = innerFactory;
            _serviceProvider        = serviceProvider;
            _abpLocalizationOptions = abpLocalizationOptions.Value;

            _localizerCache = new ConcurrentDictionary <Type, AbpDictionaryBasedStringLocalizer>();
        }
Exemple #24
0
        public void RootNamespace()
        {
            var locOptions = new LocalizationOptions();
            var options    = new Mock <IOptions <LocalizationOptions> >();

            options.Setup(o => o.Value).Returns(locOptions);
            var factory = new ResourceManagerStringLocalizerFactory(options.Object, NullLoggerFactory.Instance);

            var valuesLoc = factory.Create(typeof(ValuesController));

            Assert.Equal("ValFromResource", valuesLoc["String1"]);
        }
Exemple #25
0
        public void RootNamespace()
        {
            var locOptions = new LocalizationOptions();
            var options    = new Mock <IOptions <LocalizationOptions> >();

            options.Setup(o => o.Value).Returns(locOptions);
            var factory = new ResourceManagerStringLocalizerFactory(options.Object, NullLoggerFactory.Instance);

            var    valuesLoc = factory.Create(typeof(ValuesController));
            string value     = valuesLoc["String1"]; // Note: Tests nullable analysis of implicit string conversion operator.

            Assert.Equal("ValFromResource", value);
        }
Exemple #26
0
            public MessageOfTheDayControllerEnglishTests()
            {
                var options = Options.Create(new LocalizationOptions {
                    ResourcesPath = "Resources"
                });
                var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

                _localizer = new StringLocalizer <MessageOfTheDayController>(factory);

                _mockMessageOfTheDayService = new Mock <IMessageOfTheDayService>();

                _sut = new MessageOfTheDayController(_mockMessageOfTheDayService.Object, _localizer);
            }
        public void Create_FromNameLocation_NullLocationThrows()
        {
            // Arrange
            var locOptions = new LocalizationOptions();
            var options    = new Mock <IOptions <LocalizationOptions> >();

            options.Setup(o => o.Value).Returns(locOptions);
            var loggerFactory = NullLoggerFactory.Instance;
            var factory       = new ResourceManagerStringLocalizerFactory(localizationOptions: options.Object, loggerFactory: loggerFactory);

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => factory.Create("baseName", location: null !));
        }
Exemple #28
0
 public void Constructor_IfTheLoggerFactoryParameterIsNull_ShouldThrowAnArgumentNullException()
 {
     try
     {
         var _ = new ResourceManagerStringLocalizerFactory(Mock.Of <IOptions <LocalizationOptions> >(), null);
     }
     catch (ArgumentNullException argumentNullException)
     {
         if (argumentNullException.ParamName.Equals("loggerFactory", StringComparison.Ordinal))
         {
             throw;
         }
     }
 }
Exemple #29
0
        private static IStringLocalizer InitializeStringLocalizer()
        {
            IOptions <LocalizationOptions> options = Options.Create(new LocalizationOptions()
            {
                ResourcesPath = "Resources"
            });
            ResourceManagerStringLocalizerFactory factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            System.Type      type         = typeof(TokenTracker);
            AssemblyName     assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
            IStringLocalizer localizer    = factory.Create("TokenTracker", assemblyName.Name);

            return(localizer);
        }
Exemple #30
0
        public async void CanRetrieveTranslations()
        {
            var options   = Options.Create(new LocalizationOptions());
            var factory   = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
            var localizer = new StringLocalizer <TranslationTests>(factory);

            var translator = new Translator <TranslationTests>(localizer);

            var en = await translator.TranslateString("test-value", "en");

            var pl = await translator.TranslateString("test-value", "pl");

            en.Should().Be("A test value!");
            pl.Should().Be("Testowa wartosc!");
        }
        public void Create_FromType_ReturnsNewResultForDifferentType()
        {
            // Arrange
            var appEnv = new Mock<IApplicationEnvironment>();
            appEnv.SetupGet(a => a.ApplicationName).Returns("TestApplication");
            var locOptions = new LocalizationOptions();
            var options = new Mock<IOptions<LocalizationOptions>>();
            options.Setup(o => o.Value).Returns(locOptions);
            var factory = new ResourceManagerStringLocalizerFactory(appEnv.Object, localizationOptions: options.Object);

            // Act
            var result1 = factory.Create(typeof(ResourceManagerStringLocalizerFactoryTest));
            var result2 = factory.Create(typeof(LocalizationOptions));

            // Assert
            Assert.NotSame(result1, result2);
        }
        public void Create_FromNameLocation_ReturnsCachedResultForSameNameLocation()
        {
            // Arrange
            var appEnv = new Mock<IApplicationEnvironment>();
            appEnv.SetupGet(a => a.ApplicationName).Returns("TestApplication");
            var locOptions = new LocalizationOptions();
            var options = new Mock<IOptions<LocalizationOptions>>();
            options.Setup(o => o.Value).Returns(locOptions);
            var factory = new ResourceManagerStringLocalizerFactory(appEnv.Object, localizationOptions: options.Object);
            var location = typeof(ResourceManagerStringLocalizer).GetTypeInfo().Assembly.FullName;

            // Act
            var result1 = factory.Create("baseName", location);
            var result2 = factory.Create("baseName", location);

            // Assert
            Assert.Same(result1, result2);
        }