Exemple #1
0
        public async Task SingleSourceSingleTargetWithSuffixTest()
        {
            Uri sourceUri = await CreateSourceContainerAsync(twoTestDocuments);

            Uri targetUri = await CreateTargetContainerAsync();

            DocumentTranslationClient client = GetClient();

            var source = new TranslationSource(sourceUri)
            {
                Suffix = "1.txt"
            };

            var targets = new List <TranslationTarget> {
                new TranslationTarget(targetUri, "fr")
            };
            var input = new DocumentTranslationInput(source, targets);
            DocumentTranslationOperation operation = await client.StartTranslationAsync(input);

            await operation.WaitForCompletionAsync();

            if (operation.DocumentsSucceeded < 1)
            {
                await PrintNotSucceededDocumentsAsync(operation);
            }

            Assert.IsTrue(operation.HasCompleted);
            Assert.IsTrue(operation.HasValue);
            Assert.AreEqual(1, operation.DocumentsTotal);
            Assert.AreEqual(1, operation.DocumentsSucceeded);
            Assert.AreEqual(0, operation.DocumentsFailed);
            Assert.AreEqual(0, operation.DocumentsCancelled);
            Assert.AreEqual(0, operation.DocumentsInProgress);
            Assert.AreEqual(0, operation.DocumentsNotStarted);
        }
Exemple #2
0
        private void FormatFileStatus()
        {
            var item = SelectedSearchResult;

            if (item != null)
            {
                string matchStr   = string.Empty;
                string lineStr    = string.Empty;
                int    matchCount = item.Matches == null ? 0 : item.Matches.Count;
                if (matchCount > 0)
                {
                    var lineCount = item.Matches.Where(r => r.LineNumber > 0)
                                    .Select(r => r.LineNumber).Distinct().Count();

                    matchStr = matchCount.ToString("N0", CultureInfo.CurrentCulture);
                    lineStr  = lineCount.ToString("N0", CultureInfo.CurrentCulture);
                }

                string formattedText = TranslationSource.Format(Resources.Replace_FileNumberOfCountName,
                                                                FileNumber, FileCount, item.FileNameReal, matchStr, lineStr);

                if (Utils.IsReadOnly(item))
                {
                    formattedText += " " + Resources.Replace_ReadOnly;
                }

                FileStatus = formattedText;
            }
            else
            {
                FileStatus = string.Empty;
            }
        }
Exemple #3
0
        private void SearchPowerPoint(Stream stream, string file, string searchPattern, GrepSearchOption searchOptions, SearchDelegates.DoSearch searchMethod, List <GrepSearchResult> searchResults)
        {
            try
            {
                var slides = PowerPointReader.ExtractPowerPointText(stream);

                foreach (var slide in slides)
                {
                    var lines = searchMethod(-1, 0, slide.Item2, searchPattern, searchOptions, true);
                    if (lines.Count > 0)
                    {
                        GrepSearchResult result = new GrepSearchResult(file, searchPattern, lines, Encoding.Default)
                        {
                            AdditionalInformation = " " + TranslationSource.Format(Resources.Main_PowerPointSlideNumber, slide.Item1)
                        };

                        using (StringReader reader = new StringReader(slide.Item2))
                        {
                            result.SearchResults = Utils.GetLinesEx(reader, result.Matches, initParams.LinesBefore, initParams.LinesAfter);
                        }
                        result.ReadOnly = true;
                        searchResults.Add(result);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, string.Format("Failed to search inside PowerPoint file '{0}'", file));
            }
        }
        private static void LoadSettings()
        {
            if (File.Exists(SettingsFullPath))
            {
                try
                {
                    var bytes = Convert.FromBase64String(File.ReadAllText(SettingsFullPath));
                    using (var s = new MemoryStream(bytes))
                    {
                        Settings = (AppSettings) new BinaryFormatter().Deserialize(s);
                        if (!Settings.UserHasRated)
                        {
                            Settings.LaunchCount++;
                        }
                    }
                    return;
                }
                catch (Exception e) { Logger.Error("Failed to load settings file", e); }
            }

            //write default values to file on first launch or if config file doesn't exist or deserialization failed
            Settings = new AppSettings
            {
                CurrentAppTheme = SystemColorHelper.WindowsTheme,
                FirstLaunchDate = DateTime.Today
            };
            Settings.AppLanguage = TranslationSource.GetSystemLanguage();
            SaveSettings().GetAwaiter().GetResult();
        }
Exemple #5
0
 public WordDictionary(string enWord, string translation, string transcription, TranslationSource sourse)
 {
     EnWord        = enWord;
     Transcription = transcription;
     RuWord        = translation;
     Sourse        = sourse;
 }
Exemple #6
0
 private void SearchExcel(Stream stream, string file, string searchPattern, GrepSearchOption searchOptions, SearchDelegates.DoSearch searchMethod, List <GrepSearchResult> searchResults)
 {
     try
     {
         var sheets = ExcelReader.ExtractExcelText(stream);
         foreach (var kvPair in sheets)
         {
             var lines = searchMethod(-1, 0, kvPair.Value, searchPattern, searchOptions, true);
             if (lines.Count > 0)
             {
                 GrepSearchResult result = new GrepSearchResult(file, searchPattern, lines, Encoding.Default)
                 {
                     AdditionalInformation = " " + TranslationSource.Format(Resources.Main_ExcelSheetName, kvPair.Key)
                 };
                 using (StringReader reader = new StringReader(kvPair.Value))
                 {
                     result.SearchResults = Utils.GetLinesEx(reader, result.Matches, initParams.LinesBefore, initParams.LinesAfter);
                 }
                 result.ReadOnly = true;
                 searchResults.Add(result);
             }
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex, string.Format("Failed to search inside Excel file '{0}'", file));
     }
 }
        private async Task SaveTranslationsToCacheAsync(string word, IReadOnlyCollection <string> translations,
                                                        TranslationSource source)
        {
            if (translations.Count == 0)
            {
                return;
            }

            // Delete if exist
            var existing = await _translationsRepository.GetAll().Where(t => t.Word == word).ToListAsync();

            foreach (var translation in existing)
            {
                _translationsRepository.Delete(translation);
            }

            // Save translations
            var translationsCaches = translations.Select(translation => new Translation
            {
                Word      = word,
                Translate = translation,
                AddDate   = DateTime.Now,
                Source    = source
            }).ToList();

            foreach (var translationsCache in translationsCaches)
            {
                await _translationsRepository.InsertAsync(translationsCache);
            }

            await CurrentUnitOfWork.SaveChangesAsync();
        }
Exemple #8
0
        private void FormatCaptureGroups(Paragraph paragraph, GrepMatch match, string fmtLine)
        {
            if (paragraph == null || match == null || string.IsNullOrEmpty(fmtLine))
            {
                return;
            }

            GroupMap map = new GroupMap(match, fmtLine);

            foreach (var range in map.Ranges.Where(r => r.Length > 0))
            {
                var run = new Run(range.RangeText);
                if (range.Group == null)
                {
                    run.SetResourceReference(Run.ForegroundProperty, "Match.Highlight.Foreground");
                    run.SetResourceReference(Run.BackgroundProperty, "Match.Highlight.Background");
                    run.ToolTip = TranslationSource.Format(Resources.Main_ResultList_MatchToolTip1, Parent.MatchIdx, Environment.NewLine, fmtLine);
                    paragraph.Inlines.Add(run);
                }
                else
                {
                    if (!Parent.GroupColors.TryGetValue(range.Group.Name, out string bgColor))
                    {
                        int groupIdx = Parent.GroupColors.Count % 10;
                        bgColor = $"Match.Group.{groupIdx}.Highlight.Background";
                        Parent.GroupColors.Add(range.Group.Name, bgColor);
                    }
                    run.SetResourceReference(Run.ForegroundProperty, "Match.Highlight.Foreground");
                    run.SetResourceReference(Run.BackgroundProperty, bgColor);
                    run.ToolTip = TranslationSource.Format(Resources.Main_ResultList_MatchToolTip2,
                                                           Parent.MatchIdx, Environment.NewLine, range.Group.Name, range.Group.Value);
                    paragraph.Inlines.Add(run);
                }
            }
        }
Exemple #9
0
        public SettingsViewModel(
            IChocolateyService chocolateyService,
            IDialogService dialogService,
            IProgressService progressService,
            IConfigService configService,
            IEventAggregator eventAggregator,
            IChocolateyGuiCacheService chocolateyGuiCacheService,
            IFileSystem fileSystem,
            TranslationSource translationSource)
            : base(translationSource)
        {
            _chocolateyService         = chocolateyService;
            _dialogService             = dialogService;
            _progressService           = progressService;
            _configService             = configService;
            _eventAggregator           = eventAggregator;
            _chocolateyGuiCacheService = chocolateyGuiCacheService;
            _fileSystem        = fileSystem;
            _translationSource = translationSource;
            DisplayName        = L(nameof(Resources.SettingsViewModel_DisplayName));
            Activated         += OnActivated;
            Deactivated       += OnDeactivated;

            ChocolateyGuiFeaturesView.Filter = new Predicate <object>(o => FilterChocolateyGuiFeatures(o as ChocolateyGuiFeature));
            ChocolateyGuiSettingsView.Filter = new Predicate <object>(o => FilterChocolateyGuiSettings(o as ChocolateyGuiSetting));
            ChocolateyFeaturesView.Filter    = new Predicate <object>(o => FilterChocolateyFeatures(o as ChocolateyFeature));
            ChocolateySettingsView.Filter    = new Predicate <object>(o => FilterChocolateySettings(o as ChocolateySetting));
        }
Exemple #10
0
        private void FormatFileReplaceStatus()
        {
            var item = SelectedSearchResult;

            if (item != null)
            {
                string matchStr     = string.Empty;
                string replaceStr   = string.Empty;
                int    matchCount   = item.Matches == null ? 0 : item.Matches.Count;
                int    replaceCount = 0;
                if (matchCount > 0)
                {
                    replaceCount = item.Matches.Count(r => r.ReplaceMatch);
                }

                matchStr   = matchCount.ToString("N0", CultureInfo.CurrentCulture);
                replaceStr = replaceCount.ToString("N0", CultureInfo.CurrentCulture);

                string formattedText = TranslationSource.Format(Resources.Replace_NumberOfMatchesMarkedForReplacement,
                                                                replaceStr, matchStr);

                if (Utils.IsReadOnly(item))
                {
                    formattedText += " " + Resources.Replace_ReadOnly;
                }

                FileReplaceStatus = formattedText;
            }
            else
            {
                FileReplaceStatus = string.Empty;
            }
        }
Exemple #11
0
        public string GetHelpString()
        {
            string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            string buildDate       = AboutViewModel.GetLinkerTime(Assembly.GetExecutingAssembly()).ToString(CultureInfo.CurrentCulture);

            return(TranslationSource.Format(Localization.Properties.Resources.Help_CmdLine,
                                            assemblyVersion, buildDate));
        }
Exemple #12
0
 public DictionaryTranslation(
     string enWord,
     string ruWord,
     string enTranscription,
     TranslationSource source)
 {
     EnWord          = enWord;
     EnTranscription = enTranscription ?? "";
     RuWord          = ruWord;
     Source          = source;
 }
Exemple #13
0
        internal void SetExtendedProperties()
        {
            var tempList = new List <string>();

            if (IncludeArchive)
            {
                tempList.Add(Resources.Bookmarks_Summary_SearchInArchives);
            }
            if (!IncludeSubfolders || (IncludeSubfolders && MaxSubfolderDepth == 0))
            {
                tempList.Add(Resources.Bookmarks_Summary_NoSubfolders);
            }
            if (IncludeSubfolders && MaxSubfolderDepth > 0)
            {
                tempList.Add(TranslationSource.Format(Resources.Bookmarks_Summary_MaxFolderDepth, MaxSubfolderDepth));
            }
            if (!IncludeHidden)
            {
                tempList.Add(Resources.Bookmarks_Summary_NoHidden);
            }
            if (!IncludeBinary)
            {
                tempList.Add(Resources.Bookmarks_Summary_NoBinary);
            }
            if (!FollowSymlinks)
            {
                tempList.Add(Resources.Bookmarks_Summary_NoSymlinks);
            }
            if (CaseSensitive)
            {
                tempList.Add(Resources.Bookmarks_Summary_CaseSensitive);
            }
            if (WholeWord)
            {
                tempList.Add(Resources.Bookmarks_Summary_WholeWord);
            }
            if (Multiline)
            {
                tempList.Add(Resources.Bookmarks_Summary_Multiline);
            }

            if (tempList.Count == 0)
            {
                ExtendedProperties = string.Empty;
            }
            else
            {
                ExtendedProperties = string.Join(", ", tempList);
            }
        }
Exemple #14
0
        public LocalSourceViewModel(
            IChocolateyService chocolateyService,
            IDialogService dialogService,
            IProgressService progressService,
            IPersistenceService persistenceService,
            IChocolateyGuiCacheService chocolateyGuiCacheService,
            IConfigService configService,
            IAllowedCommandsService allowedCommandsService,
            IEventAggregator eventAggregator,
            string displayName,
            IMapper mapper,
            TranslationSource translator)
            : base(translator)
        {
            _chocolateyService         = chocolateyService;
            _dialogService             = dialogService;
            _progressService           = progressService;
            _persistenceService        = persistenceService;
            _chocolateyGuiCacheService = chocolateyGuiCacheService;
            _configService             = configService;
            _allowedCommandsService    = allowedCommandsService;

            if (displayName[0] == '[' && displayName[displayName.Length - 1] == ']')
            {
                _resourceId = displayName.Trim('[', ']');
                DisplayName = translator[_resourceId];
                translator.PropertyChanged += (sender, e) =>
                {
                    DisplayName = translator[_resourceId];
                };
            }
            else
            {
                DisplayName = displayName;
            }

            _packages            = new List <IPackageViewModel>();
            Packages             = new ObservableCollection <IPackageViewModel>();
            PackageSource        = CollectionViewSource.GetDefaultView(Packages);
            PackageSource.Filter = FilterPackage;

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

            _eventAggregator = eventAggregator;
            _mapper          = mapper;
            _eventAggregator.Subscribe(this);
        }
        public RemoteSourceViewModel(
            IChocolateyService chocolateyPackageService,
            IDialogService dialogService,
            IProgressService progressService,
            IChocolateyGuiCacheService chocolateyGuiCacheService,
            IConfigService configService,
            IEventAggregator eventAggregator,
            ChocolateySource source,
            IMapper mapper,
            TranslationSource translator)
            : base(translator)
        {
            Source = source;
            _chocolateyPackageService  = chocolateyPackageService;
            _dialogService             = dialogService;
            _progressService           = progressService;
            _chocolateyGuiCacheService = chocolateyGuiCacheService;
            _configService             = configService;
            _eventAggregator           = eventAggregator;
            _mapper = mapper;

            Packages = new ObservableCollection <IPackageViewModel>();

            if (source.Id[0] == '[' && source.Id[source.Id.Length - 1] == ']')
            {
                _resourceId = source.Id.Trim('[', ']');
                DisplayName = translator[_resourceId];
                translator.PropertyChanged += (sender, e) =>
                {
                    DisplayName = translator[_resourceId];
                };
            }
            else
            {
                DisplayName = source.Id;
            }

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

            _eventAggregator.Subscribe(this);

            AddSortOptions();

            SortSelection = L(nameof(Resources.RemoteSourceViewModel_SortSelectionPopularity));
        }
Exemple #16
0
        internal bool SetLabel()
        {
            bool isFileReadOnly = Utils.IsReadOnly(GrepResult);

            string basePath      = string.IsNullOrWhiteSpace(searchFolderPath) ? string.Empty : searchFolderPath.TrimEnd('\\');
            string displayedName = Path.GetFileName(GrepResult.FileNameDisplayed);

            if (GrepSettings.Instance.Get <bool>(GrepSettings.Key.ShowFilePathInResults) &&
                GrepResult.FileNameDisplayed.Contains(basePath, StringComparison.CurrentCultureIgnoreCase))
            {
                if (!string.IsNullOrWhiteSpace(basePath))
                {
                    displayedName = GrepResult.FileNameDisplayed.Substring(basePath.Length + 1).TrimStart('\\');
                }
                else
                {
                    displayedName = GrepResult.FileNameDisplayed;
                }
            }
            if (!string.IsNullOrWhiteSpace(GrepResult.AdditionalInformation))
            {
                displayedName += " " + GrepResult.AdditionalInformation + " ";
            }
            int matchCount = GrepResult.Matches == null ? 0 : GrepResult.Matches.Count;

            if (matchCount > 0)
            {
                if (GrepSettings.Instance.Get <bool>(GrepSettings.Key.ShowVerboseMatchCount) && !GrepResult.IsHexFile)
                {
                    var lineCount = GrepResult.Matches.Where(r => r.LineNumber > 0)
                                    .Select(r => r.LineNumber).Distinct().Count();
                    displayedName = TranslationSource.Format(Resources.Main_ResultList_CountMatchesOnLines, displayedName, matchCount, lineCount);
                }
                else
                {
                    displayedName = string.Format(Resources.Main_ResultList_CountMatches, displayedName, matchCount);
                }
            }
            if (isFileReadOnly)
            {
                displayedName = displayedName + " " + Resources.Main_ResultList_ReadOnly;
            }

            Label = displayedName;

            return(isFileReadOnly);
        }
Exemple #17
0
 /// <summary>
 /// This is the set of Resource strings used in string.Format
 /// </summary>
 internal void InitializeStrings()
 {
     list.Clear();
     list.Add(new ResourceString("Bookmarks_Summary_MaxFolderDepth", TranslationSource.Format(Resources.Bookmarks_Summary_MaxFolderDepth, 3)));
     list.Add(new ResourceString("Main_ExcelSheetName", TranslationSource.Format(Resources.Main_ExcelSheetName, "Sheet1")));
     list.Add(new ResourceString("Main_FilterSummary_MaxFolderDepth", TranslationSource.Format(Resources.Main_FilterSummary_MaxFolderDepth, 2)));
     list.Add(new ResourceString("Main_PowerPointSlideNumber", TranslationSource.Format(Resources.Main_PowerPointSlideNumber, 3)));
     list.Add(new ResourceString("Main_ResultList_AtPosition", TranslationSource.Format(Resources.Main_ResultList_AtPosition, 234)));
     list.Add(new ResourceString("Main_ResultList_CountMatches", TranslationSource.Format(Resources.Main_ResultList_CountMatches, @"folder\testFile1.text", 14)));
     list.Add(new ResourceString("Main_ResultList_CountMatchesOnLines", TranslationSource.Format(Resources.Main_ResultList_CountMatchesOnLines, @"folder\testFile1.text", 14, 5)));
     list.Add(new ResourceString("Main_ResultList_MatchToolTip1", TranslationSource.Format(Resources.Main_ResultList_MatchToolTip1, 1, Environment.NewLine, "The quick brown fox")));
     list.Add(new ResourceString("Main_ResultList_MatchToolTip2", TranslationSource.Format(Resources.Main_ResultList_MatchToolTip2, 2, Environment.NewLine, 1, "fox")));
     list.Add(new ResourceString("Main_ResultList_PlusCountMoreMatches", TranslationSource.Format(Resources.Main_ResultList_PlusCountMoreMatches, 7)));
     list.Add(new ResourceString("Main_Status_ReplaceComplete0FilesReplaced", TranslationSource.Format(Resources.Main_Status_ReplaceComplete0FilesReplaced, 6)));
     list.Add(new ResourceString("Main_Status_SearchCompletedIn0_1MatchesFoundIn2FilesOf3Searched", TranslationSource.Format(Resources.Main_Status_SearchCompletedIn0_1MatchesFoundIn2FilesOf3Searched, "0.184s", 42, 3, 7)));
     list.Add(new ResourceString("Main_Status_Searched0FilesFound1MatchingFiles", TranslationSource.Format(Resources.Main_Status_Searched0FilesFound1MatchingFiles, 7, 3)));
     list.Add(new ResourceString("Main_Status_Searched0FilesFound1MatchingFilesProcessing2", TranslationSource.Format(Resources.Main_Status_Searched0FilesFound1MatchingFilesProcessing2, 4, 2, "large.xml")));
     list.Add(new ResourceString("Main_WindowTitle", TranslationSource.Format(Resources.Main_WindowTitle, "test", @"C:\testFiles\test")));
     list.Add(new ResourceString("MessageBox_CouldNotLoadResourcesFile0", TranslationSource.Format(Resources.MessageBox_CouldNotLoadResourcesFile0, "Resources.en.resx")));
     list.Add(new ResourceString("MessageBox_CouldNotLoadTheme", TranslationSource.Format(Resources.MessageBox_CouldNotLoadTheme, "Sunset")));
     list.Add(new ResourceString("MessageBox_CountFilesHaveBeenSuccessfullyCopied", TranslationSource.Format(Resources.MessageBox_CountFilesHaveBeenSuccessfullyCopied, 3)));
     list.Add(new ResourceString("MessageBox_CountFilesHaveBeenSuccessfullyDeleted", TranslationSource.Format(Resources.MessageBox_CountFilesHaveBeenSuccessfullyDeleted, 2)));
     list.Add(new ResourceString("MessageBox_CountFilesHaveBeenSuccessfullyMoved", TranslationSource.Format(Resources.MessageBox_CountFilesHaveBeenSuccessfullyMoved, 5)));
     list.Add(new ResourceString("MessageBox_NewVersionOfDnGREP0IsAvailableForDownload", TranslationSource.Format(Resources.MessageBox_NewVersionOfDnGREP0IsAvailableForDownload, "2.9.454")));
     list.Add(new ResourceString("MessageBox_ResourcesFile0IsNotAResxFile", TranslationSource.Format(Resources.MessageBox_ResourcesFile0IsNotAResxFile, "Resources.yy.resx")));
     list.Add(new ResourceString("MessageBox_SearchPathInTheFieldIsNotValid", TranslationSource.Format(Resources.MessageBox_SearchPathInTheFieldIsNotValid, Resources.Main_Folder)));
     list.Add(new ResourceString("MessageBox_TheFile0AlreadyExistsIn1OverwriteExisting", TranslationSource.Format(Resources.MessageBox_TheFile0AlreadyExistsIn1OverwriteExisting, "config.xml", @"C:\test\config")));
     list.Add(new ResourceString("MessageBox_TheFilePattern0IsNotAValidRegularExpression12", TranslationSource.Format(Resources.MessageBox_TheFilePattern0IsNotAValidRegularExpression12, "(.*", Environment.NewLine, "Not enough )'s")));
     list.Add(new ResourceString("MessageBox_ThisBookmarkIsAssociatedWith0OtherFolders", TranslationSource.Format(Resources.MessageBox_ThisBookmarkIsAssociatedWith0OtherFolders, 2)));
     list.Add(new ResourceString("MessageBox_WindowTitleIsName", TranslationSource.Format(Resources.MessageBox_WindowTitleIsName, "Word")));
     list.Add(new ResourceString("Options_CustomEditorHelp", TranslationSource.Format(Resources.Options_CustomEditorHelp, sFile, Line, Pattern, Match, Column)));
     list.Add(new ResourceString("Replace_FileNumberOfCountName", TranslationSource.Format(Resources.Replace_FileNumberOfCountName, 1, 3, "test.xml", "9", "6")));
     list.Add(new ResourceString("Replace_NumberOfMatchesMarkedForReplacement", TranslationSource.Format(Resources.Replace_NumberOfMatchesMarkedForReplacement, 1, 3)));
     list.Add(new ResourceString("Report_Found0MatchesOn1LinesIn2Files", TranslationSource.Format(Resources.Report_Found0MatchesOn1LinesIn2Files, 138, 83, 6)));
     list.Add(new ResourceString("Report_Has0MatchesOn1Lines", TranslationSource.Format(Resources.Report_Has0MatchesOn1Lines, 14, 6)));
     list.Add(new ResourceString("ReportSummary_MaxFolderDepth", TranslationSource.Format(Resources.ReportSummary_MaxFolderDepth, 2)));
     list.Add(new ResourceString("ReportSummary_SizeFrom0To1KB", TranslationSource.Format(Resources.ReportSummary_SizeFrom0To1KB, 25, 1000)));
     list.Add(new ResourceString("ReportSummary_Type0DateFrom1To2", TranslationSource.Format(Resources.ReportSummary_Type0DateFrom1To2, "Modified", "*", "*")));
     list.Add(new ResourceString("ReportSummary_Type0DateInPast1To2Hours", TranslationSource.Format(Resources.ReportSummary_Type0DateInPast1To2Hours, "Created", 0, 8)));
     list.Add(new ResourceString("ReportSummary_UsingTypeOfSeach", TranslationSource.Format(Resources.ReportSummary_UsingTypeOfSeach, "Regex")));
     list.Add(new ResourceString("Help_CmdLine", TranslationSource.Format(Resources.Help_CmdLine, "2.9.454.0", DateTime.Now.ToString())));
 }
Exemple #18
0
        private const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute


        /// <summary>
        /// Sets the clipboard text and suppresses the CLIPBRD_E_CANT_OPEN error
        /// </summary>
        /// <remarks>
        /// Applications receiving clipboard notifications can lock the clipboard,  causing
        /// Clipboard.SetText to fail.
        ///
        /// The WPF implementation (link below) already calls the clipboard with delays
        /// and retries. Testing has shown that calling SetText in a retry loop won't help, it only
        /// makes the failure slower.
        ///
        /// The SetText method does two clipboard operations: first to set the data object and
        /// second to flush the data so it is remains on the clipboard after the application exits.
        /// Testing has shown that setting the data succeeds, which raises a notification, the bad actor
        /// locks the clipboard, and the call to flush fails with CLIPBRD_E_CANT_OPEN.
        ///
        /// The flush is nice, but not really a necessary feature.
        ///
        /// In contrast, Clipboard.SetDataObject(text) does not do the flush, and won't have
        /// to wait through the retry loops.  So if SetText fails, fall back to SetDataObject.
        ///
        /// https://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Clipboard.cs,8b9b56e883ff64c7
        /// </remarks>
        /// <param name="text"></param>
        public static void SetClipboardText(string text)
        {
            const uint CLIPBRD_E_CANT_OPEN = 0x800401D0;

            try
            {
                if (useClipboardSetDataObject)
                {
                    System.Windows.Clipboard.SetDataObject(text);
                }
                else
                {
                    System.Windows.Clipboard.SetText(text);
                }
                return;
            }
            catch (COMException ex)
            {
                if ((uint)ex.ErrorCode == CLIPBRD_E_CANT_OPEN)
                {
                    useClipboardSetDataObject = true;

                    var process = ProcessHoldingClipboard();
                    if (process != null)
                    {
                        string msg = Resources.MessageBox_ErrorSettingClipboardTextTheClipboardIsLockedBy + Environment.NewLine;
                        msg += (process.MainModule != null && !string.IsNullOrEmpty(process.MainModule.FileName) ?
                                process.MainModule.FileName : process.ProcessName) + Environment.NewLine +
                               TranslationSource.Format(Resources.MessageBox_WindowTitleIsName, process.MainWindowTitle);
                        logger.Error(msg);
                        System.Windows.MessageBox.Show(msg, Resources.MessageBox_DnGrep,
                                                       System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error,
                                                       System.Windows.MessageBoxResult.OK, TranslationSource.Instance.FlowDirection);
                    }
                }
                else
                {
                    throw;
                }
            }
        }
        public void TranslateWithGlobalCulture(TranslationSource.Row row)
        {
            Translator.CurrentCulture = row.Culture;
            var actual = Translator<Properties.Resources>.Translate(row.Key);
            Assert.AreEqual(row.ExpectedTranslation, actual);

            foreach (var errorHandling in Enum.GetValues(typeof(ErrorHandling))
                                              .OfType<ErrorHandling>())
            {
                actual = Translator<Properties.Resources>.Translate(row.Key, errorHandling);
                Assert.AreEqual(row.ExpectedTranslation, actual);
            }

            foreach (var errorHandling in Enum.GetValues(typeof(ErrorHandling))
                              .OfType<ErrorHandling>())
            {
                Translator.ErrorHandling = errorHandling;
                actual = Translator<Properties.Resources>.Translate(row.Key);
                Assert.AreEqual(row.ExpectedTranslation, actual);
            }
        }
            public void TranslateWithExplicitCulture(TranslationSource.Row row)
            {
                Translator.CurrentCulture = null;
                var actual = Translator.Translate(Properties.Resources.ResourceManager, row.Key, row.Culture);
                Assert.AreEqual(row.ExpectedTranslation, actual);

                foreach (var errorHandling in Enum.GetValues(typeof(ErrorHandling))
                                                  .OfType<ErrorHandling>())
                {
                    actual = Translator.Translate(Properties.Resources.ResourceManager, row.Key, row.Culture, errorHandling);
                    Assert.AreEqual(row.ExpectedTranslation, actual);
                }

                foreach (var errorHandling in Enum.GetValues(typeof(ErrorHandling))
                                  .OfType<ErrorHandling>())
                {
                    Translator.ErrorHandling = errorHandling;
                    actual = Translator.Translate(Properties.Resources.ResourceManager, row.Key, row.Culture);
                    Assert.AreEqual(row.ExpectedTranslation, actual);
                }
            }
Exemple #21
0
        private static void LoadSettings()
        {
            if (File.Exists(SettingsFullPath))
            {
                try
                {
                    using (var fileStream = new FileStream(SettingsFullPath, FileMode.Open))
                    {
                        fileStream.Position = 0;
                        Settings            = (AppSettings) new BinaryFormatter().Deserialize(fileStream);
                    }
                    return;
                }
                catch (Exception e) { Logger.Error("Failed to load settings file", e); }
            }

            //write default values to file on first launch or if config file doesn't exist or deserialization failed
            Settings = new AppSettings {
                CurrentAppTheme = AppTheme.System, AppLanguage = TranslationSource.GetSystemLanguage()
            };
            SaveSettings().GetAwaiter().GetResult();
        }
Exemple #22
0
        public async Task SingleSourceSingleTargetListDocumentsTest()
        {
            Uri sourceUri = await CreateSourceContainerAsync(oneDocumentList);

            Uri targetUri = await CreateTargetContainerAsync();

            var client = GetClient();

            var filter = new DocumentFilter
            {
                Suffix = "1.txt"
            };
            var source = new TranslationSource(sourceUri)
            {
                Filter = filter
            };
            var targets = new List <TranslationTarget> {
                new TranslationTarget(targetUri, "fr")
            };
            var input     = new DocumentTranslationInput(source, targets);
            var operation = await client.StartTranslationAsync(input);

            await operation.WaitForCompletionAsync(PollingInterval);

            var documents = operation.GetAllDocumentStatusesAsync();

            List <DocumentStatusResult> documentsList = await documents.ToEnumerableAsync();

            Assert.AreEqual(1, documentsList.Count);

            foreach (var document in documentsList)
            {
                Assert.AreEqual(TranslationStatus.Succeeded, document.Status);
                Assert.IsTrue(document.HasCompleted);
                Assert.AreEqual(100f, document.TranslationProgressPercentage);
                Assert.AreEqual("fr", document.TranslateTo);
                Assert.NotNull(document.TranslatedDocumentUri);
            }
        }
        private void frmTransProcess_Loaded(object sender, RoutedEventArgs e)
        {
            if (TranslationSource.ProcessSourceList == null || TranslationSource.ProcessSourceList.Count == 0)
            {
                TranslationSource sources = new TranslationSource();
                lstProcess.ItemsSource = sources;
                TranslationSource.ProcessSourceList = sources;
            }
            else
            {
                lstProcess.ItemsSource = TranslationSource.ProcessSourceList;
            }

            cbBing.IsChecked = ConfigSetting.OnlyTranslateFromBing;
            if (!_isAccessDB)
            {
                cbBing.IsChecked = true;
                lstProcess.IsEnabled = false;
                btnMoveUp.IsEnabled = false;
                btnMoveDown.IsEnabled = false;
                cbBing.IsEnabled = false;
            }
        }
Exemple #24
0
        private InlineCollection FormatLine(GrepLine line)
        {
            Paragraph paragraph = new Paragraph();

            string fullLine = line.LineText;

            if (line.LineText.Length > MaxLineLength)
            {
                fullLine = line.LineText.Substring(0, MaxLineLength);
            }

            if (line.Matches.Count == 0)
            {
                Run mainRun = new Run(fullLine);
                paragraph.Inlines.Add(mainRun);
            }
            else
            {
                int         counter     = 0;
                GrepMatch[] lineMatches = new GrepMatch[line.Matches.Count];
                line.Matches.CopyTo(lineMatches);
                foreach (GrepMatch m in lineMatches)
                {
                    Parent.MatchIdx++;
                    try
                    {
                        string regLine = null;
                        string fmtLine = null;
                        if (m.StartLocation < fullLine.Length)
                        {
                            regLine = fullLine.Substring(counter, m.StartLocation - counter);
                        }

                        if (m.StartLocation + m.Length <= fullLine.Length)
                        {
                            fmtLine = fullLine.Substring(m.StartLocation, m.Length);
                        }
                        else if (fullLine.Length > m.StartLocation)
                        {
                            // match may include the non-printing newline chars at the end of the line: don't overflow the length
                            fmtLine = fullLine.Substring(m.StartLocation, fullLine.Length - m.StartLocation);
                        }
                        else
                        {
                            // binary file?
                            regLine = fullLine;
                        }

                        if (regLine != null)
                        {
                            Run regularRun = new Run(regLine);
                            paragraph.Inlines.Add(regularRun);
                        }
                        if (fmtLine != null)
                        {
                            if (HighlightCaptureGroups && m.Groups.Count > 0)
                            {
                                FormatCaptureGroups(paragraph, m, fmtLine);
                            }
                            else
                            {
                                var run = new Run(fmtLine);
                                run.SetResourceReference(Run.ForegroundProperty, "Match.Highlight.Foreground");
                                run.SetResourceReference(Run.BackgroundProperty, "Match.Highlight.Background");
                                paragraph.Inlines.Add(run);
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch
                    {
                        Run regularRun = new Run(fullLine);
                        paragraph.Inlines.Add(regularRun);
                    }
                    finally
                    {
                        counter = m.StartLocation + m.Length;
                    }
                }
                if (counter < fullLine.Length)
                {
                    try
                    {
                        string regLine    = fullLine.Substring(counter);
                        Run    regularRun = new Run(regLine);
                        paragraph.Inlines.Add(regularRun);
                    }
                    catch
                    {
                        Run regularRun = new Run(fullLine);
                        paragraph.Inlines.Add(regularRun);
                    }
                }
                if (line.LineText.Length > MaxLineLength)
                {
                    string msg = TranslationSource.Format(Resources.Main_ResultList_CountAdditionalCharacters, line.LineText.Length - MaxLineLength);

                    var msgRun = new Run(msg);
                    msgRun.SetResourceReference(Run.ForegroundProperty, "TreeView.Message.Highlight.Foreground");
                    msgRun.SetResourceReference(Run.BackgroundProperty, "TreeView.Message.Highlight.Background");
                    paragraph.Inlines.Add(msgRun);

                    var hiddenMatches = line.Matches.Where(m => m.StartLocation > MaxLineLength).Select(m => m);
                    int count         = hiddenMatches.Count();
                    if (count > 0)
                    {
                        paragraph.Inlines.Add(new Run(" " + Resources.Main_ResultList_AdditionalMatches));
                    }

                    // if close to getting them all, then take them all,
                    // otherwise, stop at 20 and just show the remaining count
                    int takeCount = count > 25 ? 20 : count;

                    foreach (GrepMatch m in hiddenMatches.Take(takeCount))
                    {
                        if (m.StartLocation + m.Length <= line.LineText.Length)
                        {
                            paragraph.Inlines.Add(new Run("  "));
                            string fmtLine = line.LineText.Substring(m.StartLocation, m.Length);
                            var    run     = new Run(fmtLine);
                            run.SetResourceReference(Run.ForegroundProperty, "Match.Highlight.Foreground");
                            run.SetResourceReference(Run.BackgroundProperty, "Match.Highlight.Background");
                            paragraph.Inlines.Add(run);

                            if (m.StartLocation + m.Length == line.LineText.Length)
                            {
                                paragraph.Inlines.Add(new Run(" " + Resources.Main_ResultList_AtEndOfLine));
                            }
                            else
                            {
                                paragraph.Inlines.Add(new Run(" " + TranslationSource.Format(Resources.Main_ResultList_AtPosition, m.StartLocation)));
                            }
                        }
                    }

                    if (count > takeCount)
                    {
                        paragraph.Inlines.Add(new Run(TranslationSource.Format(Resources.Main_ResultList_PlusCountMoreMatches, count - takeCount)));
                    }
                }
            }
            return(paragraph.Inlines);
        }
Exemple #25
0
        /// <summary>Saves translations to the cache.</summary>
        /// <param name="word">Original word.</param>
        /// <param name="translations">List of translations.</param>
        /// <param name="source">Source of the translation.</param>
        private void SaveTranslationsToCache(string word, IReadOnlyCollection <string> translations, TranslationSource source)
        {
            Task.Run(() =>
            {
                if (translations.Count == 0)
                {
                    return;
                }

                // delete if exist
                var existing = _watchWordUnitOfWork.TranslationsRepository.GetAll(t => t.Word == word);
                foreach (var translation in existing)
                {
                    _watchWordUnitOfWork.TranslationsRepository.Delete(translation);
                }

                // save translations
                var translationsCache = translations.Select(translation => new Translation
                {
                    Word      = word,
                    Translate = translation,
                    AddDate   = DateTime.Now,
                    Source    = source
                }).ToList();

                _watchWordUnitOfWork.TranslationsRepository.Insert(translationsCache);
                _watchWordUnitOfWork.TranslationsRepository.Save();
            });
        }
 /// <summary>Saves translations to the cache.</summary>
 /// <param name="word">Original word.</param>
 /// <param name="translations">List of translations.</param>
 /// <param name="source">Source of the translation.</param>
 private async Task SaveTranslationsToCache(string word, IReadOnlyCollection <string> translations,
                                            TranslationSource source)
 {
     await SaveTranslationsToCacheAsync(word, translations, source);
 }
Exemple #27
0
        internal static AudioSessionModel GetAudioSessionModel(this IAudioSessionControl sControl, out bool isSystemSession)
        {
            if (sControl == null)
            {
                isSystemSession = false;
                return(null);
            }
            var     sessionControl = (IAudioSessionControl2)sControl;
            Process process;

            try
            {
                Marshal.ThrowExceptionForHR(sessionControl.GetProcessId(out var processId));
                process = Process.GetProcessById((int)processId);
            }
            catch (Exception e)
            {
                Logger.Error($"Failed to get session process", e);
                isSystemSession = false;
                return(null);
            }

            try
            {
                ImageSource iconImageSource = null;
                string      sessionName     = string.Empty;

                try
                {
                    sessionName = process.ProcessName;
                }
                catch { }

                if (sessionControl.IsNotSystemSounds())
                {
                    App.Current.Dispatcher.Invoke(() => iconImageSource = ExtractSessionIcon(process, sControl));
                    isSystemSession = false;
                }
                else
                {
                    isSystemSession = true;
                    //check if the system language was changed to get a new localized name for the system sounds session
                    var systemLanguage = TranslationSource.GetSystemLanguage();
                    if (SettingsProvider.Settings.SystemSoundsName == null ||
                        SettingsProvider.Settings.SystemLanguage != systemLanguage)
                    {
                        //returns resources "DllPath,index"
                        sessionName = sControl.GetSystemSoundsName();
                        SettingsProvider.Settings.SystemLanguage   = systemLanguage;
                        SettingsProvider.Settings.SystemSoundsName = sessionName;
                        SettingsProvider.SaveSettings().GetAwaiter().GetResult();
                    }
                    else
                    {
                        sessionName = SettingsProvider.Settings.SystemSoundsName;
                    }

                    try
                    {
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            Icon icon =
                                Icon.ExtractAssociatedIcon(Environment.ExpandEnvironmentVariables("%SystemRoot%\\System32\\AudioSrv.dll"));
                            iconImageSource = IconHelper.GetImageSourceFromIcon(icon);
                        });
                    }
                    catch (Exception e)
                    {
                        Logger.Error($"Failed to extract system sounds icon from AudioSrv.dll.", e);
                    }
                }

                var sessionVolume = new AudioSessionVolume(sessionControl);
                var muteState     = sessionVolume.GetMute();
                var volume        = sessionVolume.GetVolume();
                sessionControl.GetSessionIdentifier(out var sessionId);

                AudioSessionStateNotifications sessionStateNotifications =
                    new AudioSessionStateNotifications(sessionControl);

                try
                {
                    sessionStateNotifications.RegisterNotifications();
                }
                catch (Exception e)
                {
                    Logger.Error($"Failed to register audio session notifications, process: [{sessionName}]", e);
                }

                AudioSessionModel session =
                    new AudioSessionModel(muteState, Convert.ToInt32(volume * 100), sessionName, sessionId, iconImageSource,
                                          sessionVolume,
                                          sessionStateNotifications);
                return(session);
            }
            catch (Exception e)
            {
                Logger.Error($"Failed to create audio session model, process: [{process.ProcessName}]", e);
            }
            isSystemSession = false;
            return(null);
        }
Exemple #28
0
 public Translation(string text, TranslationSource source)
 {
     Text   = text;
     Source = source.ToString();
 }
Exemple #29
0
        public async Task <IActionResult> Translate(TranslateRequestModel model)
        {
            var message = string.Empty;
            var documentTranslationClient = GetDocumentTranslationClient();

            var documentTranslationInputs = new List <DocumentTranslationInput>();
            var expiresOn = DateTimeOffset.UtcNow.AddDays(365);

            foreach (var language in model.TargetLanguages)
            {
                var translationTargets = new List <TranslationTarget>();

                var sourceUri         = storageService.GenerateSourceContainerSasUri(azureTranslatorOptions.SourceBlobContainerName, expiresOn);
                var translationSource = new TranslationSource(new Uri(sourceUri));
                translationSource.LanguageCode = model.CriteriaLanguage;

                var sourceName = documentNamingStrategy.GetTranslatedDocumentName(model.Name, language);

                var nameTokens = sourceName.Split(".");
                var namePart   = String.Join(".", nameTokens.Take(nameTokens.Length - 1));

                translationSource.Filter = new DocumentFilter
                {
                    Prefix = namePart,
                    Suffix = string.Empty,
                };

                var translationTarget = new TranslationTarget(new Uri(storageService.GenerateTargetContainerSasUri(azureTranslatorOptions.TargetBlobContainerName, expiresOn)), language);

                translationTargets.Add(translationTarget);

                kr.bbon.Azure.Translator.Services.Models.AzureStorage.Blob.BlobCreateResultModel blobfound = null;

                try
                {
                    blobfound = await storageService.FindByNameAsync(azureTranslatorOptions.TargetBlobContainerName, sourceName);
                }
                catch (Exception ex)
                {
                    blobfound = null;
                }

                if (blobfound != null)
                {
                    var error = new ErrorModel
                    {
                        Code    = "Target blob exists",
                        Message = $"If target blob exists, translation job will be failed. Please make sure to remove target blob ({sourceName}) in target container.",
                    };

                    throw new ApiHttpStatusException <ErrorModel>(HttpStatusCode.BadRequest, error.Message, error);
                }

                var documentTranslationInput = new DocumentTranslationInput(translationSource, translationTargets);
                documentTranslationInputs.Add(documentTranslationInput);
            }

            if (documentTranslationInputs.Count == 0)
            {
                message = "Request is invaild";
                var errorModel = new ErrorModel {
                    Code = "BadRequest", Message = message
                };
                throw new ApiHttpStatusException <ErrorModel>(HttpStatusCode.BadRequest, message, errorModel);
            }

            var operation = await documentTranslationClient.StartTranslationAsync(documentTranslationInputs);

            //var documentStatus = await operation.WaitForCompletionAsync();
            //await foreach (var document in documentStatus.Value)
            //{

            //}


            return(StatusCode(System.Net.HttpStatusCode.Accepted, new DocumentTranslationResponseModel
            {
                Id = operation.Id,
            }));
        }
Exemple #30
0
 public WordDictionary(string enWord, string translation, string transcription, TranslationSource sourse, List <Phrase> phrases)
Exemple #31
0
 protected ObservableBase(TranslationSource translationSource)
 {
     _translationSource = translationSource;
     _translationSource.PropertyChanged += (sender, args) => OnLanguageChanged();
 }
 protected ViewModelScreen(TranslationSource translationSource)
 {
     _translationSource = translationSource;
     _translationSource.PropertyChanged += (sender, args) => OnLanguageChanged();
 }
 /// <summary>
 /// 翻译器实例构造方法
 /// </summary>
 /// <param name="_TLSource">翻译源</param>
 /// <param name="_From">被翻译的文本语言</param>
 /// <param name="_To">目标语言</param>
 public TranslatorConfiguration(TranslationSource _TLSource, BaseLanguageType _From, BaseLanguageType _To)
 {
     TLSource = _TLSource;
     From     = _From;
     To       = _To;
 }