public void Repository_should_save_translate()
        {
            var repository = new TranslationRepository(DbContext);

            var phraseType   = new PhraseType(7, "commodity", "کالا");
            var phrase       = new Phrase(15, "گندم", phraseType);
            var language     = new Language(1, "انگلیسی", "English", "EN");
            var translations = new List <Domain.Entities.Translation>()
            {
                new Domain.Entities.Translation(0, language, "Wheat")
            };
            var translatedPhrase = new TranslateBuilder()
                                   .WithPhrase(phrase)
                                   .WithTranslations(translations).Build();

            repository.Save(translatedPhrase);

            var id = translatedPhrase.Id;

            DbContext.ClearChangeTracker();


            var result = repository.GetById(id);

            Assert.Equal(result, translatedPhrase, new TranslatorEqualityComparer());
        }
Exemplo n.º 2
0
        public async Task GetByLanguage_ShouldReturnAllTranslations_InEnglish()
        {
            // Arrange
            const int languageId = 1;

            Mock<DbSet<Translation>> translationDbSetMock = _translations
                .AsQueryable()
                .BuildMockDbSet();

            Mock<IChatContext> contextMock = new Mock<IChatContext>();
            contextMock
                .Setup(m => m.Translations)
                .Returns(translationDbSetMock.Object);

            ITranslationRepository translationRepository = new TranslationRepository(contextMock.Object);

            // Act
            IEnumerable<Translation> actualTranslations = await translationRepository
                .GetByLanguage(languageId)
                .ToListAsync();

            // Assert
            Assert.NotNull(actualTranslations);
            Assert.NotEmpty(actualTranslations);

            Assert.Equal(2, actualTranslations.Count());
            Assert.All(actualTranslations, translation => Assert.Equal(1, translation.LanguageId));
        }
Exemplo n.º 3
0
        private static void CreateDatabaseSchemaAndDemoData()
        {
            CreateDatabaseSchema();

            var session                = NHibernateHelper.SessionFactory.OpenSession();
            var passwordPolicy         = new RegularExpressionPasswordPolicy(".{5,}$");
            var translationsRepository = new TranslationRepository(session, new InMemoryKeyValueCache());
            var applicationSettings    = new ApplicationSettings();
            var encryptor              = new DefaultEncryptor();

            var userRepository = new UserRepository(session, passwordPolicy, applicationSettings, encryptor);

            // Create administrators
            PocoGenerator.CreateAdministrators(userRepository);

            // Create users
            PocoGenerator.CreateUsers(100, userRepository);

            session.Transaction.Begin();

            // Create translations
            PocoGenerator.CreateTranslations(translationsRepository);

            session.Transaction.Commit();

            // Create logitems
            PocoGenerator.CreateLogItems(new NLogLogger(applicationSettings, "Console.Admin"));
        }
Exemplo n.º 4
0
        public async Task GetByLanguage_ShouldReturnFilteredLanguages_WhenPatternIsProvided()
        {
            // Arrange
            const int languageId = 1;
            const string pattern = "Page.Group.LabelTwo";

            Mock<DbSet<Translation>> translationDbSetMock = _translations
                .AsQueryable()
                .BuildMockDbSet();

            Mock<IChatContext> contextMock = new Mock<IChatContext>();
            contextMock
                .Setup(m => m.Translations)
                .Returns(translationDbSetMock.Object);

            ITranslationRepository translationRepository = new TranslationRepository(contextMock.Object);

            // Act
            IEnumerable<Translation> actualTranslations = await translationRepository
                .GetByLanguage(languageId, pattern)
                .ToListAsync();

            // Assert
            Assert.NotEmpty(actualTranslations);
            Assert.Single(actualTranslations);
        }
Exemplo n.º 5
0
        public async Task GetByLanguage_ShouldReturnEmptyList_WhenPatternDoesNotMatch()
        {
            // Arrange
            const int languageId = 1;
            const string pattern = "unmatchable_pattern";

            Mock<DbSet<Translation>> translationDbSetMock = _translations
                .AsQueryable()
                .BuildMockDbSet();

            Mock<IChatContext> contextMock = new Mock<IChatContext>();
            contextMock
                .Setup(m => m.Translations)
                .Returns(translationDbSetMock.Object);

            ITranslationRepository translationRepository = new TranslationRepository(contextMock.Object);

            // Act
            IEnumerable<Translation> actualTranslations = await translationRepository
                .GetByLanguage(languageId, pattern)
                .ToListAsync();

            // Assert
            Assert.Empty(actualTranslations);
        }
Exemplo n.º 6
0
        public Loader(TranslationRepository repository)
        {
            this.repository = repository;

            FileExtensions          = GetFileExtensions();
            repository.DataChanged += delegate { FileExtensions = GetFileExtensions(); };
        }
Exemplo n.º 7
0
        public TranslationController()
        {
            var connectionString = Settings.GetStringDB();

            translationRepository = new TranslationRepository(connectionString);
            userRepository        = new UserRepository(connectionString);
            _userActionRepository = new UserActionRepository(connectionString);
        }
Exemplo n.º 8
0
        public TranslationWriter(string localDefault)
        {
            _localDefault = localDefault;
            var connectionString = Settings.GetStringDB();

            translationRep = new TranslationRepository(connectionString);
            localeRep      = new LocaleRepository(connectionString);

            ts = new TranslationSubstringRepository(connectionString);
        }
Exemplo n.º 9
0
        public static void Seed(TranslationDb context)
        {
            ContainerRepository.AddTestData(context);
            LanguageRepository.AddTestData(context);
            ClientRepository.AddTestData(context);
            TranslationRepository.AddTestData(context);

            context.SaveChanges();
            context.Dispose();
        }
Exemplo n.º 10
0
        public ReadWriteFileController()
        {
            string connectionString = Settings.GetStringDB();

            _localizationProjectRepository = new LocalizationProjectRepository(connectionString);
            _localeRepository               = new LocaleRepository(connectionString);
            _translationRepository          = new TranslationRepository(connectionString);
            _translationSubstringRepository = new TranslationSubstringRepository(connectionString);
            _IXmlNodeExtensions             = new IXmlNodeExtensions(connectionString);
            _glossaryRepository             = new GlossaryRepository(connectionString);
            _partOfSpeechRepository         = new PartOfSpeechRepository(connectionString);
        }
        private async Task <string> CheckFieldTranslations()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

            string operation = string.Format(Properties.OperationNames.CheckingFieldTranslationsFormat2, Connection1.Name, Connection2.Name);

            content.AppendLine(_iWriteToOutput.WriteToOutputStartOperation(null, operation));

            var task1 = TranslationRepository.GetFieldTranslationFromCacheAsync(Connection1.ConnectionId, _comparerSource.Service1);
            var task2 = TranslationRepository.GetFieldTranslationFromCacheAsync(Connection2.ConnectionId, _comparerSource.Service2);

            var translation1 = await task1;

            if (translation1 != null)
            {
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings in {0}: {1}", Connection1.Name, translation1.DisplayStrings.Count()));
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Localized Labels in {0}: {1}", Connection1.Name, translation1.LocalizedLabels.Count()));
            }
            else
            {
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Field Translations not finded in {0}", Connection1.Name));
            }

            var translation2 = await task2;

            if (translation2 != null)
            {
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings in {0}: {1}", Connection2.Name, translation2.DisplayStrings.Count()));
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Localized Labels in {0}: {1}", Connection2.Name, translation2.LocalizedLabels.Count()));
            }
            else
            {
                content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Field Translations not finded in {0}", Connection2.Name));
            }

            if (translation1 != null && translation2 != null)
            {
                CompareTranslations(content, translation1, translation2);
            }

            content.AppendLine().AppendLine().AppendLine(_iWriteToOutput.WriteToOutputEndOperation(null, operation));

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "Field Translations");

            string filePath = Path.Combine(_folder, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            return(filePath);
        }
Exemplo n.º 12
0
 static int Main(string[] args)
 {
     //
     translationRepository = new TranslationRepository();
     loader = new Medusa.Analyze1553B.Loader.BMD.Loader(translationRepository);
     try
     {
         StartListener(1234).Wait();
         return(0);
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine(ex);
         return(-1);
     }
 }
Exemplo n.º 13
0
        public void TestModelLanguageToLanguage()
        {
            TranslationJob trj = new TranslationJob()
            {
                Id              = Guid.NewGuid(),
                FileContent     = Encoding.UTF8.GetBytes("This is the first translation job."),
                UserId          = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension   = "txt",
                FileName        = "test",
                MimeType        = "text/plain",
                Status          = JobStatus.Started,
                SubmitTime      = DateTime.Now,
                DownloadCounter = 0,
                InputFileHash   = new byte[8],
                SourceLanguage  = Language.enGB.ToString(),
                TargetLanguage  = Language.daDK.ToString()
            };
            var repo = new TranslationRepository();

            var jobID = repo.SubmitWorkItem(trj).Result;

            while (repo.GetWorkStatus(jobID) == 2)
            {
                //wait
                Task.Delay(200);
            }
            byte[] res = null;
            if (repo.GetWorkStatus(jobID) == 1)
            {
                //sucess
                FileResult result = repo.GetResultContents(jobID);
                res = result.getFileContents();
            }
            else
            {
                //fail
                throw new Exception("Task with job ID: " + jobID + " failed");
            }

            NUnit.Framework.Assert.AreEqual("This is the first translation job.", Encoding.UTF8.GetString(res));
        }
Exemplo n.º 14
0
 public TranslationController(TranslationRepository translationRepository)
 {
     _translationRepository = translationRepository;
 }
Exemplo n.º 15
0
        public void TestPostLanguageToLanguage()
        {
            //init
            var mockJobs         = new Mock <DbSet <Job> >();
            var mockServiceUsers = new Mock <DbSet <ServiceUser> >();
            var mockContext      = new Mock <RoboBrailleDataContext>();

            // arrange
            var users = new List <ServiceUser> {
                new ServiceUser
                {
                    EmailAddress = "*****@*****.**",
                    UserId       = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                    ApiKey       = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"),
                    FromDate     = new DateTime(2015, 1, 1),
                    ToDate       = new DateTime(2020, 1, 1),
                    UserName     = "******",
                    Jobs         = null
                }
            }.AsQueryable();

            TranslationJob trj = new TranslationJob()
            {
                Id              = Guid.NewGuid(),
                FileContent     = Encoding.UTF8.GetBytes("This is the first translation job."),
                UserId          = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension   = "txt",
                FileName        = "test",
                MimeType        = "text/plain",
                Status          = JobStatus.Started,
                SubmitTime      = DateTime.Now,
                DownloadCounter = 0,
                InputFileHash   = new byte[8],
                SourceLanguage  = Language.enGB.ToString(),
                TargetLanguage  = Language.daDK.ToString()
            };
            TranslationJob trj2 = new TranslationJob()
            {
                Id              = Guid.NewGuid(),
                FileContent     = Encoding.UTF8.GetBytes("This is the second translation job."),
                UserId          = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension   = "txt",
                FileName        = "test2",
                MimeType        = "text/plain",
                Status          = JobStatus.Done,
                SubmitTime      = DateTime.Now,
                DownloadCounter = 2,
                InputFileHash   = new byte[2],
                SourceLanguage  = Language.enGB.ToString(),
                TargetLanguage  = Language.svSE.ToString()
            };
            var jobs = new List <TranslationJob> {
                trj2
            }.AsQueryable();

            mockJobs.As <IDbAsyncEnumerable <Job> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <Job>(jobs.GetEnumerator()));
            mockJobs.As <IQueryable <Job> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <Job>(jobs.Provider));

            mockJobs.As <IQueryable <Job> >().Setup(m => m.Expression).Returns(jobs.Expression);
            mockJobs.As <IQueryable <Job> >().Setup(m => m.ElementType).Returns(jobs.ElementType);
            mockJobs.As <IQueryable <Job> >().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator());

            mockServiceUsers.As <IDbAsyncEnumerable <ServiceUser> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <ServiceUser>(users.GetEnumerator()));
            mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <ServiceUser>(users.Provider));
            mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.Expression).Returns(users.Expression);
            mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.ElementType).Returns(users.ElementType);
            mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());

            mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object);
            mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object);

            var repo    = new TranslationRepository(mockContext.Object);
            var request = new HttpRequestMessage();

            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\"");
            var serviceController = new TranslationController(repo);

            serviceController.Request = request;
            //call
            var jobid = serviceController.Post(trj).Result;

            //test
            mockJobs.Verify(m => m.Add(It.IsAny <Job>()), Times.Once());

            mockContext.Verify(m => m.SaveChanges(), Times.Exactly(1));
            //twice if it is synced
            //mockContext.Verify(m => m.SaveChanges(), Times.Exactly(2));
        }
 private void btnClearCacheTranslations_Click(object sender, RoutedEventArgs e)
 {
     TranslationRepository.ClearCache();
 }
Exemplo n.º 17
0
 public TranslationService(TranslationRepository translationRepository)
 {
     _translationRepository = translationRepository;
 }
        public static List <Translation> CreateTranslations(TranslationRepository translationsRepository)
        {
            var english = new CultureInfo("en-US");
            var dutch   = new CultureInfo("nl-NL");

            var translations = new List <Translation>
            {
                // en-US
                new Translation("Login", "Login", english),
                new Translation("Logout", "Logout", english),
                new Translation("Home", "Home", english),
                new Translation("Users", "Users", english),
                new Translation("SendEmail", "Send email", english),
                new Translation("FlashMessages", "Flash messages", english),
                new Translation("Unauthorized", "Unauthorized", english),
                new Translation("Forbidden", "Forbidden", english),
                new Translation("PageNotFound", "Page not found", english),
                new Translation("InternalServerError", "Internal server error", english),
                new Translation("DearSirOrMadam", "Dear sir or madam", english),
                new Translation("KindRegards", "Kind regards", english),
                new Translation("ResetPassword", "Reset password", english),
                new Translation("ResetPasswordMailMessage", "We received a request to change your password. By clicking the link below you are able to reset your password.\r\nIn case you did not initiate this request, you can simply ignore this message, your password will remain unchanged.\r\n", english),
                new Translation("ResetPasswordMailMessageText", "We received a request to change your password. By using the link below you are able to reset your password.\r\nIn case you did not initiate this request, you can simply ignore this message, your password will remain unchanged.\r\n", english),
                new Translation("Required", "Required", english),
                new Translation("Email", "Email", english),
                new Translation("Password", "Password", english),
                new Translation("RepeatPassword", "Repeat password", english),
                new Translation("SignIn", "Sign in", english),
                new Translation("EmailAndPasswordCombinationNotValid", "Email and/or password is not valid", english),
                new Translation("InvalidEmailAddress", "Emailaddress is not valid", english),
                new Translation("UserWithEmailAddressWasNotFound", "User with emailaddress '{0}' was not found", english),
                new Translation("Send", "Send", english),
                new Translation("Back", "Back", english),
                new Translation("ChangePassword", "Change password", english),
                new Translation("PasswordsDoNotMatch", "Passwords do not match", english),
                new Translation("RequestToResetYourPassword", "Request to reset your password", english),
                new Translation("Success", "Success", english),
                new Translation("Info", "Info", english),
                new Translation("Warning", "Warning", english),
                new Translation("Error", "Error", english),
                new Translation("AnEmailWasSendToYourEmailaddressWithInstructionsOnHowToResetYourPassword", "An email was send to your emailaddress with instructions on how to reset your password", english),
                new Translation("YourPasswordWasChangedSuccessfully", "Your password was changed successfully", english),
                new Translation("ChuckNorrisFacts", "Chuck Norris Facts", english),
                new Translation("Shortcuts", "Shortcuts", english),
                new Translation("MorePages", "More pages", english),
                new Translation("PasswordShouldContainAtLeast5Characters", "Password should contain at least 5 characters", english),
                new Translation("ClientSideFlashMessages", "Client side flash messages", english),
                new Translation("InlineClientSideFlashMessages", "Inline client side flash messages", english),
                new Translation("EmailSuccessfullySend", "Email successfully send", english),

                // nl-NL
                new Translation("Login", "Inloggen", dutch),
                new Translation("Logout", "Uitloggen", dutch),
                new Translation("Home", "Thuis", dutch),
                new Translation("Users", "Gebruikers", dutch),
                new Translation("SendEmail", "Verstuur e-mail", dutch),
                new Translation("FlashMessages", "Notificatie berichten", dutch),
                new Translation("Unauthorized", "Onbevoegd", dutch),
                new Translation("Forbidden", "Verboden", dutch),
                new Translation("PageNotFound", "Pagina niet gevonden", dutch),
                new Translation("InternalServerError", "Interne server fout", dutch),
                new Translation("DearSirOrMadam", "Geachte heer, mevrouw", dutch),
                new Translation("KindRegards", "Vriendelijke groeten", dutch),
                new Translation("ResetPassword", "Reset wachtwoord", dutch),
                new Translation("ResetPasswordMailMessage", "Een aanvraag voor wijziging van uw wachtwoord is bij ons aangekomen. Door op onderstaande link te klikken kunt u een nieuw wachtwoord opgeven.\r\nIndien u geen verzoek tot wijziging heeft gedaan kunt u deze email als niet verzonden beschouwen, uw bestaande wachtwoord blijft dan intact.\r\n", dutch),
                new Translation("ResetPasswordMailMessage", "Een aanvraag voor wijziging van uw wachtwoord is bij ons aangekomen. Door onderstaande link te gebruiken kunt u een nieuw wachtwoord opgeven.\r\nIndien u geen verzoek tot wijziging heeft gedaan kunt u deze email als niet verzonden beschouwen, uw bestaande wachtwoord blijft dan intact.\r\n", dutch),
                new Translation("Required", "Verplicht", dutch),
                new Translation("Email", "Email", dutch),
                new Translation("Password", "Wachtwoord", dutch),
                new Translation("RepeatPassword", "Herhaal wachtwoord", dutch),
                new Translation("SignIn", "Inloggen", dutch),
                new Translation("EmailAndPasswordCombinationNotValid", "Email en/of wachtwoord is niet geldig", dutch),
                new Translation("InvalidEmailAddress", "Emailadres is niet geldig", dutch),
                new Translation("UserWithEmailAddressWasNotFound", "Gebruiker met emailadres '{0}' is niet gevonden", dutch),
                new Translation("Send", "Verzenden", dutch),
                new Translation("Back", "Terug", dutch),
                new Translation("ChangePassword", "Wachtwoord wijzigen", dutch),
                new Translation("PasswordsDoNotMatch", "Wachtwoorden komen niet overeen", dutch),
                new Translation("RequestToResetYourPassword", "Verzoek om uw wachtwoord te wijzigen", dutch),
                new Translation("Success", "Succes", dutch),
                new Translation("Info", "Info", dutch),
                new Translation("Warning", "Pas op", dutch),
                new Translation("Error", "Fout", dutch),
                new Translation("AnEmailWasSendToYourEmailaddressWithInstructionsOnHowToResetYourPassword", "Een email is naar u toegestuurd met instructies hoe u uw wachtwoord kunt resetten.", dutch),
                new Translation("YourPasswordWasChangedSuccessfully", "Uw wachtwoord is succesvol aangepast", dutch),
                new Translation("ChuckNorrisFacts", "Chuck Norris Feiten", dutch),
                new Translation("Shortcuts", "Shortcuts", dutch),
                new Translation("MorePages", "Meer pagina's", dutch),
                new Translation("PasswordShouldContainAtLeast5Characters", "Wachtwoord dient minimaal 5 tekens te bevatten", dutch),
                new Translation("ClientSideFlashMessages", "Client side flash berichten", dutch),
                new Translation("InlineClientSideFlashMessages", "Inline client side flash berichten", dutch),
                new Translation("EmailSuccessfullySend", "Email succesvol verzonden", dutch),
            };

            translations.ForEach(translationsRepository.Save);

            return(translations);
        }