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");
        }
Пример #2
0
        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>();
        }
Пример #3
0
        public void StringLocalizerSelfReturn()
        {
            var localizer = new StringLocalizer();

            Assert.AreEqual("A", localizer["A"]);
            Assert.AreEqual("A B", localizer["A B"]);
        }
            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);
            }
Пример #5
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);
        }
        public static string LocalizeEnum <T>(T value)
            where T : struct
        {
            string enumName = typeof(T).Name;
            string fullKey  = string.Format("E_{0}_{1}", enumName, value.ToString());

            return(StringLocalizer.Localize(fullKey));
        }
Пример #7
0
        public AddPlotPageViewModel(
            INavigationService navigationService,
            IStringLocalizer <AddPlotPageViewModel> stringLocalizer,
            IAppDataService appDataService) : base(navigationService, stringLocalizer)
        {
            randomColor    = new Random();
            AppDataService = appDataService;

            Plot              = new Core.Entities.Plot();
            PlantingDate      = DateTime.Today;
            CropSelected      = false;
            CropPickerEnabled = true;

            PickerCropTypesSelectedIndex       = -1;
            PickerClimateTypesSelectedIndex    = -1;
            PickerMaturityClassesSelectedIndex = -1;

            ClimateTypes = new List <string>
            {
                StringLocalizer.GetString("cold"),
                StringLocalizer.GetString("tempered"),
                StringLocalizer.GetString("tropical"),
                StringLocalizer.GetString("hybrid")
            };

            CropTypes = new List <string>
            {
                StringLocalizer.GetString("none"),
                StringLocalizer.GetString("maize"),
                StringLocalizer.GetString("barley"),
                StringLocalizer.GetString("bean"),
                StringLocalizer.GetString("wheat"),
                StringLocalizer.GetString("triticale"),
                StringLocalizer.GetString("sorghum"),
                StringLocalizer.GetString("alfalfa"),
                StringLocalizer.GetString("oats"),
                StringLocalizer.GetString("sesame"),
                StringLocalizer.GetString("amaranth"),
                StringLocalizer.GetString("rice"),
                StringLocalizer.GetString("canola"),
                StringLocalizer.GetString("cartamo"),
                StringLocalizer.GetString("zucchini"),
                StringLocalizer.GetString("chickpea"),
                StringLocalizer.GetString("havabean"),
                StringLocalizer.GetString("soy"),
                StringLocalizer.GetString("other")
            };

            MaturityClasses = new List <string>
            {
                StringLocalizer.GetString("early"),
                StringLocalizer.GetString("semi_early"),
                StringLocalizer.GetString("intermediate"),
                StringLocalizer.GetString("semi_late"),
                StringLocalizer.GetString("late")
            };
        }
        public UserMailServiceIT()
        {
            var options = Options.Create(new LocalizationOptions {
                ResourcesPath = "Resources"
            });
            var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

            _tenantFrameworkSl = new StringLocalizer <TenantFrameworkResource>(factory);
        }
        public void AllSupportedCulturesShouldHaveNativeNameLocalized()
        {
            Assert.All(StringLocalizer.SupportedCultures(), c =>
            {
                var translation = StringLocalizer.Instance.GetText(NativeName, c);

                Assert.NotEqual(translation, NativeName);
            });
        }
Пример #10
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);
        }
Пример #11
0
        public static string LocalizeModel <T>(string key)
            where T : class
        {
            string modelName = typeof(T).Name;

            modelName = modelName.Remove(modelName.Length - 9);
            string fullKey = string.Format("M_{0}_{1}", modelName, key);

            return(StringLocalizer.Localize(fullKey));
        }
Пример #12
0
        public static string LocalizeController <T>(string key)
            where T : ControllerBase
        {
            string controllerName = typeof(T).Name;

            controllerName = controllerName.Remove(controllerName.Length - 10);
            string fullKey = string.Format("C_{0}_{1}", controllerName, key);

            return(StringLocalizer.Localize(fullKey));
        }
Пример #13
0
    public void Constructor_ResolvesLocalizerFromFactory()
    {
        // Arrange
        var factory = new Mock <IStringLocalizerFactory>();

        // Act
        _ = new StringLocalizer <object>(factory.Object);

        // Assert
        factory.Verify(mock => mock.Create(typeof(object)), Times.Once());
    }
        public void NoneOfTheUnsupportedCulturesShouldProvideATextDifferentThanDefaultCulture()
        {
            var unsupportedCultures = AllCultures.Except(StringLocalizer.SupportedCultures());

            Assert.All(unsupportedCultures, c =>
            {
                var cultureSpecificText = StringLocalizer.Instance.GetText(NativeName, c);
                var defaultTranslation  = StringLocalizer.Instance.GetText(NativeName, StringLocalizer.DefaultCulture);

                Assert.Equal(cultureSpecificText, defaultTranslation);
            });
        }
Пример #15
0
    public void Indexer_ThrowsAnExceptionForNullName()
    {
        // Arrange
        var factory        = new Mock <IStringLocalizerFactory>();
        var innerLocalizer = new Mock <IStringLocalizer>();

        factory.Setup(mock => mock.Create(typeof(object)))
        .Returns(innerLocalizer.Object);

        var localizer = new StringLocalizer <object>(factory.Object);

        // Act and assert
        var exception = Assert.Throws <ArgumentNullException>(() => localizer[name: null !]);
Пример #16
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!");
        }
Пример #17
0
        public override void InitPlugin()
        {
            Logger.LogInformation($"init tmp plugin {Guid.NewGuid()}");
            Logger.LogInformation(StringLocalizer.GetString("hello"));

            var sb = new StringBuilder("===================\nall strings:\n");

            foreach (var str in StringLocalizer.GetAllStrings(true))
            {
                sb.AppendLine($"{str.Name}: {str.Value} ({str.SearchedLocation})");
            }

            Logger.LogInformation(sb.ToString());

            Logger.LogInformation(StringLocalizer.GetString("bye"));
        }
Пример #18
0
 public WeatherHistoryPageViewModel(INavigationService navigationService,
                                    IStringLocalizer <WeatherHistoryPageViewModel> stringLocalizer)
     : base(navigationService, stringLocalizer)
 {
     DatasetNames = new List <string>
     {
         StringLocalizer.GetString("precip"),
         StringLocalizer.GetString("rhh"),
         StringLocalizer.GetString("rhl"),
         StringLocalizer.GetString("sr"),
         StringLocalizer.GetString("tl"),
         StringLocalizer.GetString("th"),
         StringLocalizer.GetString("wa"),
         StringLocalizer.GetString("wdh"),
         StringLocalizer.GetString("wmh")
     };
     SelectedDataset = -1;
 }
            public TestEnvironment()
            {
                RealtimeService = new SFMemoryRealtimeService();
                RealtimeService.AddRepository("users", OTType.Json0, new MemoryRepository <User>(new[]
                {
                    new User
                    {
                        Id    = User01,
                        Email = "*****@*****.**",
                        Sites = new Dictionary <string, Site>
                        {
                            { SiteId, new Site {
                                  Projects = { Project01, Project03 }
                              } }
                        }
                    },
                    new User
                    {
                        Id    = User02,
                        Email = "*****@*****.**",
                        Sites = new Dictionary <string, Site>
                        {
                            { SiteId, new Site {
                                  Projects = { Project01, Project02, Project03 }
                              } }
                        }
                    },
                    new User
                    {
                        Id    = User03,
                        Email = "*****@*****.**",
                        Sites = new Dictionary <string, Site> {
                            { SiteId, new Site() }
                        }
                    },
                    new User
                    {
                        Id    = User04,
                        Email = "*****@*****.**",
                        Sites = new Dictionary <string, Site>(),
                        Role  = SystemRole.SystemAdmin
                    }
                }));
                RealtimeService.AddRepository("sf_projects", OTType.Json0, new MemoryRepository <SFProject>(
                                                  new[]
                {
                    new SFProject
                    {
                        Id              = Project01,
                        ParatextId      = "paratext_" + Project01,
                        Name            = "project01",
                        ShortName       = "P01",
                        TranslateConfig = new TranslateConfig
                        {
                            TranslationSuggestionsEnabled = true,
                            Source = new TranslateSource
                            {
                                ParatextId    = "paratextId",
                                Name          = "Source",
                                ShortName     = "SRC",
                                WritingSystem = new WritingSystem
                                {
                                    Tag = "qaa"
                                }
                            }
                        },
                        CheckingConfig = new CheckingConfig
                        {
                            ShareEnabled = false
                        },
                        UserRoles = new Dictionary <string, string>
                        {
                            { User01, SFProjectRole.Administrator },
                            { User02, SFProjectRole.CommunityChecker }
                        },
                        Texts =
                        {
                            new TextInfo
                            {
                                BookNum  = 40,
                                Chapters =
                                {
                                    new Chapter {
                                        Number = 1, LastVerse = 3, IsValid = true, Permissions ={                                                  }
                                    }
                                }
                            },
                            new TextInfo
                            {
                                BookNum  = 41,
                                Chapters =
                                {
                                    new Chapter {
                                        Number = 1, LastVerse = 3, IsValid = true, Permissions ={                                                  }
                                    },
                                    new Chapter {
                                        Number = 2, LastVerse = 3, IsValid = true, Permissions ={                                                  }
                                    }
                                }
                            }
                        }
                    },
                    new SFProject
                    {
                        Id             = Project02,
                        Name           = "project02",
                        ShortName      = "P02",
                        CheckingConfig = new CheckingConfig
                        {
                            ShareEnabled = true,
                            ShareLevel   = CheckingShareLevel.Anyone
                        },
                        UserRoles =
                        {
                            { User02, SFProjectRole.Administrator }
                        },
                    },
                    new SFProject
                    {
                        Id             = Project03,
                        Name           = "project03",
                        ShortName      = "P03",
                        CheckingConfig = new CheckingConfig
                        {
                            ShareEnabled = true,
                            ShareLevel   = CheckingShareLevel.Specific
                        },
                        UserRoles =
                        {
                            { User01, SFProjectRole.Administrator },
                            { User02, SFProjectRole.Translator    }
                        }
                    },
                    new SFProject
                    {
                        Id         = Resource01,
                        ParatextId = "resid_is_16_char",
                        Name       = "resource project",
                        ShortName  = "RES",
                    }
                }));
                RealtimeService.AddRepository("sf_project_user_configs", OTType.Json0,
                                              new MemoryRepository <SFProjectUserConfig>(new[]
                {
                    new SFProjectUserConfig {
                        Id = SFProjectUserConfig.GetDocId(Project01, User01)
                    },
                    new SFProjectUserConfig {
                        Id = SFProjectUserConfig.GetDocId(Project01, User02)
                    },
                    new SFProjectUserConfig {
                        Id = SFProjectUserConfig.GetDocId(Project02, User02)
                    },
                    new SFProjectUserConfig {
                        Id = SFProjectUserConfig.GetDocId(Project03, User01)
                    },
                    new SFProjectUserConfig {
                        Id = SFProjectUserConfig.GetDocId(Project03, User02)
                    }
                }));
                var siteOptions = Substitute.For <IOptions <SiteOptions> >();

                siteOptions.Value.Returns(new SiteOptions
                {
                    Id      = SiteId,
                    Name    = "xForge",
                    Origin  = new Uri("http://localhost"),
                    SiteDir = "xforge"
                });
                var audioService = Substitute.For <IAudioService>();

                EmailService   = Substitute.For <IEmailService>();
                ProjectSecrets = new MemoryRepository <SFProjectSecret>(new[]
                {
                    new SFProjectSecret {
                        Id = Project01
                    },
                    new SFProjectSecret {
                        Id = Project02
                    },
                    new SFProjectSecret
                    {
                        Id        = Project03,
                        ShareKeys = new List <ShareKey>
                        {
                            new ShareKey {
                                Email = "*****@*****.**", Key = "key1111"
                            },
                            new ShareKey {
                                Email = "*****@*****.**", Key = "key1234"
                            },
                            new ShareKey {
                                Email = "*****@*****.**", Key = "key2222"
                            }
                        }
                    },
                });
                EngineService = Substitute.For <IEngineService>();
                SyncService   = Substitute.For <ISyncService>();
                SyncService.SyncAsync(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <bool>())
                .Returns(Task.CompletedTask);
                ParatextService = Substitute.For <IParatextService>();
                IReadOnlyList <ParatextProject> ptProjects = new[]
                {
                    new ParatextProject
                    {
                        ParatextId  = "changedId",
                        Name        = "NewSource",
                        LanguageTag = "qaa"
                    },
                    new ParatextProject
                    {
                        ParatextId = GetProject(Project01).ParatextId
                    },
                    new ParatextProject
                    {
                        ParatextId = "ptProject123"
                    }
                };

                ParatextService.GetProjectsAsync(Arg.Any <UserSecret>()).Returns(Task.FromResult(ptProjects));
                IReadOnlyList <ParatextResource> ptResources = new[]
                {
                    new ParatextResource
                    {
                        ParatextId  = "resource_project",
                        Name        = "ResourceProject",
                        LanguageTag = "qaa"
                    },
                    new ParatextResource
                    {
                        ParatextId = GetProject(Resource01).ParatextId
                    }
                };

                ParatextService.GetResources(Arg.Any <UserSecret>()).Returns(ptResources);
                var userSecrets = new MemoryRepository <UserSecret>(new[]
                {
                    new UserSecret {
                        Id = User01
                    },
                    new UserSecret {
                        Id = User02
                    },
                    new UserSecret {
                        Id = User03
                    }
                });
                var translateMetrics = new MemoryRepository <TranslateMetrics>();

                FileSystemService = Substitute.For <IFileSystemService>();
                var options = Options.Create(new LocalizationOptions {
                    ResourcesPath = "Resources"
                });
                var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);

                Localizer       = new StringLocalizer <SharedResource>(factory);
                SecurityService = Substitute.For <ISecurityService>();
                SecurityService.GenerateKey().Returns("1234abc");
                var transceleratorService = Substitute.For <ITransceleratorService>();

                Service = new SFProjectService(RealtimeService, siteOptions, audioService, EmailService, ProjectSecrets,
                                               SecurityService, FileSystemService, EngineService, SyncService, ParatextService, userSecrets,
                                               translateMetrics, Localizer, transceleratorService);
            }
Пример #20
0
 protected string Localize(string key, string defaultValue)
 {
     return(StringLocalizer.Localize(key, CurrentUserContext.CurrentLanguage.Id, defaultValue));
 }
 public LocalizedString GetString(string name)
 {
     return(StringLocalizer.GetString(name));
 }
Пример #22
0
        public static string LocalizeView(string key, object languageId, string defaultValue)
        {
            string fullKey = string.Format("V_{0}", key);

            return(StringLocalizer.Localize(fullKey, languageId, defaultValue));
        }
Пример #23
0
        public static string LocalizeView(string key)
        {
            string fullKey = string.Format("V_{0}", key);

            return(StringLocalizer.Localize(fullKey));
        }
Пример #24
0
 /// <summary>
 /// Gets localized string for given key name and current language.
 /// </summary>
 protected string L(string name) => StringLocalizer.GetString(name);
Пример #25
0
        public static string LocalizeBusiness(string key)
        {
            string fullKey = string.Format("B_{0}", key);

            return(StringLocalizer.Localize(fullKey));
        }
Пример #26
0
        private async Task <InstalledPackage> ConvertFrom(Package item, CancellationToken cancellationToken, IProgress <ProgressData> progress = default)
        {
            Logger.Debug("Getting details about package {0}...", item.Id.Name);
            string   installLocation;
            DateTime installDate;

            try
            {
                installLocation = item.InstalledLocation?.Path;
            }
            catch (Exception e)
            {
                Logger.Warn(e, "Installed location for package {0} is invalid. This may be expected for some installed packages.", item.Id.Name);
                installLocation = null;
            }

            if (installLocation != null)
            {
                try
                {
                    installDate = item.InstalledDate.LocalDateTime;
                }
                catch (Exception e)
                {
                    Logger.Warn(e, "Installed date for package {0} is invalid. This may be expected for some installed packages.", item.Id.Name);
                    installDate = DateTime.MinValue;
                }
            }
            else
            {
                installDate = DateTime.MinValue;
            }

            MsixPackageVisuals details;
            RegistryMountState hasRegistry;

            if (installLocation == null)
            {
                hasRegistry = RegistryMountState.NotApplicable;
                details     = new MsixPackageVisuals(item.Id.Name, item.Id.Publisher, null, null, "#000000", 0);
            }
            else
            {
                details = await GetVisualsFromManifest(installLocation, cancellationToken).ConfigureAwait(false);

                hasRegistry = await registryManager.GetRegistryMountState(installLocation, item.Id.Name, cancellationToken, progress).ConfigureAwait(false);
            }

            var pkg = new InstalledPackage
            {
                DisplayName          = details.DisplayName,
                Name                 = item.Id.Name,
                Image                = details.Logo,
                PackageId            = item.Id.FullName,
                InstallLocation      = installLocation,
                PackageFamilyName    = item.Id.FamilyName,
                Description          = details.Description,
                DisplayPublisherName = details.DisplayPublisherName,
                Publisher            = item.Id.Publisher,
                Architecture         = item.Id.Architecture.ToString(),
                IsFramework          = item.IsFramework,
                IsOptional           = item.IsOptional,
                TileColor            = details.Color,
                PackageType          = details.PackageType,
                Version              = new Version(item.Id.Version.Major, item.Id.Version.Minor, item.Id.Version.Build, item.Id.Version.Revision),
                SignatureKind        = Convert(item.SignatureKind),
                HasRegistry          = hasRegistry,
                InstallDate          = installDate,
                AppInstallerUri      = item.GetAppInstallerInfo()?.Uri
            };

            if (pkg.Architecture[0] == 'X')
            {
                pkg.Architecture = "x" + pkg.Architecture.Substring(1);
            }

            if (installLocation != null && (pkg.DisplayName?.StartsWith("ms-resource:", StringComparison.Ordinal) ??
                                            pkg.DisplayPublisherName?.StartsWith("ms-resource:", StringComparison.Ordinal) ??
                                            pkg.Description?.StartsWith("ms-resource:", StringComparison.Ordinal) == true))
            {
                var priFile = Path.Combine(installLocation, "resources.pri");

                pkg.DisplayName          = StringLocalizer.Localize(priFile, pkg.Name, pkg.PackageId, pkg.DisplayName);
                pkg.DisplayPublisherName = StringLocalizer.Localize(priFile, pkg.Name, pkg.PackageId, pkg.DisplayPublisherName);
                pkg.Description          = StringLocalizer.Localize(priFile, pkg.Name, pkg.PackageId, pkg.Description);

                if (string.IsNullOrEmpty(pkg.DisplayName))
                {
                    pkg.DisplayName = pkg.Name;
                }

                if (string.IsNullOrEmpty(pkg.DisplayPublisherName))
                {
                    pkg.DisplayPublisherName = pkg.Publisher;
                }
            }

            return(pkg);
        }
Пример #27
0
 public void OnGet()
 {
     ViewData["Title"] = StringLocalizer.GetString("Title");
 }
 public void LocalizerHomeController()
 {
     ViewData["Title"] = StringLocalizer.GetString("Title");
     ViewData["About"] = StringLocalizer.GetString("About");
 }