Esempio n. 1
0
        /// <summary>
        /// Scan for all dicitionaries (default resx files, without culture identification)
        /// </summary>
        private void ScanForDefaultDictionaries()
        {
            Dictionaries.Clear();

            var culturInfoList = CultureInfo.GetCultures(CultureTypes.AllCultures).Where(c => c.Name.Length > 0);

            _resourceDirectory = SelectedProjectDirectory.GetDirectories("Resources").Single();
            var resxFiles = _resourceDirectory.GetFiles("*.resx");

            foreach (FileInfo resxFile in resxFiles)
            {
                if (culturInfoList.Any(ci => resxFile.Name.EndsWith(ci.Name + ".resx")))
                {
                    continue;
                }

                Dictionaries.Add(resxFile.Name.Replace(".resx", String.Empty));
            }

            if (Dictionaries.Any())
            {
                string lastUsedDictionary = AppRegistry.GetValue(RegistryKeys.SelectedDictionary);
                if (String.IsNullOrEmpty(lastUsedDictionary))
                {
                    SelectedDictionary = Dictionaries.First();
                }
                else
                {
                    SelectedDictionary = Dictionaries.First(dict => dict == lastUsedDictionary);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Scan for alle dicitionaries (default resx files, without culture identification)
        /// </summary>
        private void ScanForDictionaries()
        {
            Dictionaries.Clear();

            var culturInfoList = CultureInfo.GetCultures(CultureTypes.AllCultures).Where(c => c.Name.Length > 0);

            _resourceDirectory = ProjectDirectory.GetDirectories("Resources").Single();
            var resxFiles = _resourceDirectory.GetFiles("*.resx");

            foreach (FileInfo resxFile in resxFiles)
            {
                if (culturInfoList.Any(ci => resxFile.Name.EndsWith(ci.Name + ".resx")))
                {
                    continue;
                }

                Dictionaries.Add(resxFile.Name.Replace(".resx", String.Empty));
            }

            if (Dictionaries.Any())
            {
                if (!_settingsCache.Keys.Contains("dictionary"))
                {
                    SelectedDictionary = Dictionaries.First();
                }
                else
                {
                    SelectedDictionary = Dictionaries.First(d => d == _settingsCache["dictionary"]);
                }
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Adds a new dictionary in the system
 /// </summary>
 /// <param name="dictionary"></param>
 public void AddDictionary(Dictionary dictionary)
 {
     if (dictionary != null)
     {
         dictionary.Enclosing = this;
         Dictionaries.Add(dictionary);
     }
 }
Esempio n. 4
0
        public static ApiResult SetupDictionaries()
        {
            if (Dictionaries != null && Dictionaries.Count == DictionaryFiles.Count * 2)
            {
                Debug("Dictionaries already setup. Not running dictionary setup again.");
                return(ApiResult.Success);
            }
            else if (Dictionaries == null)
            {
                Dictionaries = new Dictionary <string, HashSet <string> >(DictionaryFiles.Count * 2);
            }

            int setup = 0;

            using (var op = Begin("Setting up dictionaries"))
            {
                foreach (var df in DictionaryFiles)
                {
                    var dfpath = GetDataDirectoryPathTo("dictionaries", df.Value);
                    if (Dictionaries.ContainsKey(df.Key))
                    {
                        Debug("Not updating existing dictionary {0}.", df.Key);
                        continue;
                    }
                    else if (!File.Exists(dfpath))
                    {
                        Error("The dictionary file {0} for dictionary {1} could not be found.", dfpath, df.Key);
                        continue;
                    }
                    else
                    {
                        try
                        {
                            using (FileStream fs = File.OpenRead(dfpath))
                                using (Stream s = df.Value.EndsWith(".gz") || df.Value.EndsWith(".GZ") ?
                                                  new GZipStream(fs, CompressionMode.Decompress) : (Stream)fs)
                                {
                                    var data = ReadAllLines(() => s, Encoding.UTF8).ToArray();
                                    Dictionaries.Add(df.Key, new HashSet <string>(data));
                                    Debug("Read {0} entries from file.", data.Length, dfpath);
                                    Info("Dictionary {0} has {1} entries from file: {2}.", df.Key, Dictionaries[df.Key].Count, dfpath);
                                    Dictionaries.Add(df.Key + "_3grams", new HashSet <string>(data.Where(w => w.Length <= 3)));
                                    Info("Dictionary {0} has {1} entries from file: {2}.", df.Key + "_3grams",
                                         Dictionaries[df.Key + "_3grams"].Count, dfpath);
                                    setup++;
                                }
                        }
                        catch (Exception e)
                        {
                            Error(e, "An error occurred reading dictionary file {0}.", dfpath);
                            continue;
                        }
                    }
                }
                op.Complete();
            }
            return(setup > 0 ? ApiResult.Success : ApiResult.Failure);
        }
Esempio n. 5
0
        public async Task Load()
        {
            Dictionaries.Clear();

            foreach (Dictionary dictionary in await DatabaseManager.Instance.GetDictionaries())
            {
                Dictionaries.Add(new DictionaryViewModel(dictionary));
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Adds a model element in this model element
 /// </summary>
 /// <param name="copy"></param>
 public void AddModelElement(Utils.IModelElement element)
 {
     {
         Dictionary item = element as Dictionary;
         if (item != null)
         {
             Dictionaries.Add(item);
         }
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Add dictionary to collection of dictionaries.
 /// </summary>
 /// <param name="dictionary"></param>
 public void AddDictionary(IDictionary dictionary)
 {
     if (!Dictionaries.Contains(dictionary))
     {
         Dictionaries.Add(dictionary);
         if (OnDictionariesChanged != null)
         {
             OnDictionariesChanged();
         }
     }
 }
Esempio n. 8
0
 private void SaveDictionary()
 {
     if (CurrentOptions.CurrentUser != null)
     {
         DictionaryViewModel newDictionary = new DictionaryViewModel();
         newDictionary.Name         = _newDictionary.Name;
         newDictionary.DictionaryID = _newDictionary.DictionaryID;
         Dictionaries.Add(newDictionary);
         _dao.addDictionary(newDictionary.getDictionary());
         NewDictionary = new DictionaryViewModel();
     }
 }
        static void AddDictionaries(int index)
        {
            Parallel.For(0, 1000000, (i) =>
            {
                var key   = $"key-{index}-{i}";
                var value = $"value-{index}-{i}";

                // 不加锁会报错
                lock (Dictionaries)
                {
                    Dictionaries.Add(key, value);
                }
            });
        }
        public TaskPropertyDictionary OpenDictionary(String TaskName)
        {
            var output = Dictionaries.FirstOrDefault(x => x.TaskName == TaskName);

            if (output == null)
            {
                output = new TaskPropertyDictionary()
                {
                    TaskName = TaskName
                };
                Dictionaries.Add(output);
            }

            return(output);
        }
        public override async Task Initialize()
        {
            var cultrues = Culture.Culture.getCultures();

            foreach (var cultrueTask in cultrues.Select(c => new { localizationTask = DbLocalizationDictionary.Create(SourceName, c, iocManager), c }))
            {
                var localization = await cultrueTask.localizationTask;
                if (!Dictionaries.ContainsKey(cultrueTask.c))
                {
                    Dictionaries.Add(cultrueTask.c, localization);
                }
                Dictionaries[cultrueTask.c] = localization;
                DefaultDictionary           = localization;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Загрузить словари для культуры SCADA
        /// </summary>
        /// <remarks>Если ключ загружаемого словаря совпадает с ключом уже загруженного, то словари сливаются.
        /// Если совпадают ключи фраз, то новое значение фразы записывается поверх старого</remarks>
        public static bool LoadDictionaries(string fileName, out string errMsg)
        {
            if (File.Exists(fileName))
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(fileName);

                    XmlNodeList dictNodeList = xmlDoc.DocumentElement.SelectNodes("Dictionary");
                    foreach (XmlElement dictElem in dictNodeList)
                    {
                        Dict   dict;
                        string dictKey = dictElem.GetAttribute("key");

                        if (!Dictionaries.TryGetValue(dictKey, out dict))
                        {
                            dict = new Dict(dictKey);
                            Dictionaries.Add(dictKey, dict);
                        }

                        XmlNodeList phraseNodeList = dictElem.SelectNodes("Phrase");
                        foreach (XmlElement phraseElem in phraseNodeList)
                        {
                            string phraseKey = phraseElem.GetAttribute("key");
                            dict.Phrases[phraseKey] = phraseElem.InnerText;
                        }
                    }

                    errMsg = "";
                    return(true);
                }
                catch (Exception ex)
                {
                    errMsg = string.Format(UseRussian ?
                                           "Ошибка при загрузке словарей из файла {0}: {1}" :
                                           "Error loading dictionaries from file {0}: {1}", fileName, ex.Message);
                    return(false);
                }
            }
            else
            {
                errMsg = (UseRussian ?
                          "Не найден файл словарей: " :
                          "Dictionary file not found: ") + fileName;
                return(false);
            }
        }
        public DefaultNHibernatePatternsHolder(IDomainInspector domainInspector, IExplicitDeclarationsHolder explicitDeclarations)
        {
            Poids.Add(new PoIdPattern());
            Sets.Add(new SetCollectionPattern());
            Bags.Add(new BagCollectionPattern());
            Lists.Add(new ListCollectionPattern(domainInspector));
            Arrays.Add(new ArrayCollectionPattern());
            Components.Add(new ComponentPattern(domainInspector));
            Dictionaries.Add(new DictionaryCollectionPattern());

            PoidStrategies.Add(new HighLowPoidPattern());
            PoidStrategies.Add(new GuidOptimizedPoidPattern());

            PersistentPropertiesExclusions.Add(new ReadOnlyPropertyPattern());
            ManyToOneRelations.Add(new OneToOneUnidirectionalToManyToOnePattern(domainInspector, explicitDeclarations));
            ManyToOneRelations.Add(new PolymorphicManyToOnePattern(domainInspector));
            OneToManyRelations.Add(new PolymorphicOneToManyPattern(domainInspector));
            HeterogeneousAssociations.Add(new HeterogeneousAssociationOnPolymorphicPattern(domainInspector));
        }
Esempio n. 14
0
 public void LoadSettings(string path)
 {
     using var reader = new StreamReader(path, Encoding.Default);
     while (reader.Peek() != -1)
     {
         var line = reader.ReadLine().Trim();
         if (line.Length == 0)
         {
             continue;
         }
         var token = line.Split(',');
         if (token[0] == "dictionary")
         {
             while (reader.Peek() != -1)
             {
                 line = reader.ReadLine().Trim();
                 if (line == "{")
                 {
                 }
                 else if (line == "}")
                 {
                     break;
                 }
                 else
                 {
                     Dictionaries.Add(line);
                 }
             }
         }
         else if (token[0] == "charset")
         {
             Encoding = Encoding.GetEncoding(token[1]);
         }
         else if (token[0] == "debug")
         {
             EnableDebugLog = token[1] == "1";
         }
         else if (token[0] == "error")
         {
             EnableErrorLog = token[1] == "1";
         }
     }
 }
Esempio n. 15
0
        public DefaultNHibernatePatternsHolder(IDomainInspector domainInspector, IExplicitDeclarationsHolder explicitDeclarations)
        {
            if (domainInspector == null)
            {
                throw new ArgumentNullException("domainInspector");
            }
            Poids.Add(new PoIdPattern());
            Sets.Add(new SetCollectionPattern());
            Bags.Add(new BagCollectionPattern());
            Lists.Add(new ListCollectionPattern(domainInspector));
            Arrays.Add(new ArrayCollectionPattern());
            Components.Add(new ComponentPattern(domainInspector));
            Dictionaries.Add(new DictionaryCollectionPattern());

            PoidStrategies.Add(new HighLowPoidPattern());
            PoidStrategies.Add(new GuidOptimizedPoidPattern());

            PersistentPropertiesExclusions.Add(new ReadOnlyPropertyPattern());
            ManyToOneRelations.Add(new OneToOneUnidirectionalToManyToOnePattern(explicitDeclarations));
        }
        /// <summary>
        /// Imports a dictionary, the imported dictionary is added to the dictionaries collection.
        /// </summary>
        private async Task AddDictionaryAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Opening OpenFileDialog.");

            await Task.Run(() =>
            {
                OpenFileDialog dlg   = new OpenFileDialog();
                dlg.DefaultExt       = ".txt";                                        // Default file extension
                dlg.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; // Filter files by extension
                dlg.InitialDirectory = _configurationProvider.DictionariesDir;
                dlg.Title            = "Import dictionaries";
                dlg.Multiselect      = true;

                bool dialogResult = dlg.ShowDialog() ?? false;
                if (dialogResult)
                {
                    foreach (string FileName in dlg.FileNames)
                    {
                        App.Current.Dispatcher.BeginInvoke(new System.Action(() =>
                        {
                            Dictionaries.Add(new Dictionary(FileName, Encoding.UTF8));
                        }));
                    }

                    /* Set dialog initial directory to last visited directory. */
                    string file = dlg.FileNames.FirstOrDefault();
                    if (file != default(string))
                    {
                        _configurationProvider.DictionariesDir = Path.GetDirectoryName(file);
                    }
                }
            });

            /* Select first dictionary in list. */
            SelectedDictionary = Dictionaries.FirstOrDefault();
            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
Esempio n. 17
0
        /// <summary>
        /// Download SCADA culture dictionaries
        /// </summary>
        /// <remarks>If the key of the loaded dictionary coincides with the key already loaded, the dictionaries merge.
        /// If the phrase keys match, the new phrase value is written over the old one.</remarks>
        public static bool LoadDictionaries(string fileName, out string errMsg)
        {
            if (File.Exists(fileName))
            {
                try {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(fileName);

                    var dictNodeList = xmlDoc.DocumentElement.SelectNodes("Dictionary");
                    foreach (XmlElement dictElem in dictNodeList)
                    {
                        string dictKey = dictElem.GetAttribute("key");

                        if (!Dictionaries.TryGetValue(dictKey, out var dict))
                        {
                            dict = new Dict(dictKey);
                            Dictionaries.Add(dictKey, dict);
                        }

                        var phraseNodeList = dictElem.SelectNodes("Phrase");
                        foreach (XmlElement phraseElem in phraseNodeList)
                        {
                            string phraseKey = phraseElem.GetAttribute("key");
                            dict.Phrases[phraseKey] = phraseElem.InnerText;
                        }
                    }

                    errMsg = "";
                    return(true);
                } catch (Exception ex) {
                    errMsg = $"Error loading dictionaries from file {fileName}: {ex.Message}";
                    return(false);
                }
            }

            errMsg = ("Dictionary file not found: ") + fileName;
            return(false);
        }
Esempio n. 18
0
        void Load(Func <string, IFileContainer> fileLoader, Func <char, Dictionary <string, byte[]> > diskLoader,
                  Func <string, bool> fileExistChecker, bool savesOnly = false)
        {
            var  ambermoonFiles    = savesOnly ? Legacy.Files.AmigaSaveFiles : Legacy.Files.AmigaFiles;
            var  fileReader        = new FileReader();
            bool foundNoDictionary = true;

            void HandleFileLoaded(string file)
            {
                if (log != null)
                {
                    log.AppendLine("succeeded");
                }

                if (IsDictionary(file))
                {
                    Dictionaries.Add(file.Split('.').Last(), Files[file].Files[1]);
                    foundNoDictionary = false;
                }
            }

            void HandleFileNotFound(string file, char disk)
            {
                if (log != null)
                {
                    log.AppendLine("failed");
                    log.AppendLine($" -> Unable to find file '{file}'.");
                }

                // We only need 1 dictionary, no savegames and only AM2_CPU but not AM2_BLIT.
                if (IsDictionary(file) || disk == 'J' || file == "AM2_BLIT")
                {
                    return;
                }

                if (stopAtFirstError)
                {
                    throw new FileNotFoundException($"Unable to find file '{file}'.");
                }
            }

            foreach (var ambermoonFile in ambermoonFiles)
            {
                var name = ambermoonFile.Key;

                if (log != null)
                {
                    log.Append($"Trying to load file '{name}' ... ");
                }

                // prefer direct files but also allow loading ADF disks
                if (loadPreference == LoadPreference.PreferExtracted && fileExistChecker(name))
                {
                    Files.Add(name, fileLoader(name));
                    HandleFileLoaded(name);
                }
                else if (loadPreference == LoadPreference.ForceExtracted)
                {
                    if (fileExistChecker(name))
                    {
                        Files.Add(name, fileLoader(name));
                        HandleFileLoaded(name);
                    }
                    else
                    {
                        HandleFileNotFound(name, ambermoonFile.Value);
                    }
                }
                else
                {
                    // load from disk
                    var disk = ambermoonFile.Value;

                    if (!loadedDisks.ContainsKey(disk))
                    {
                        var loadedDisk = diskLoader?.Invoke(disk);

                        if (loadedDisk == null)
                        {
                            // file not found
                            if (loadPreference == LoadPreference.ForceAdf)
                            {
                                if (log != null)
                                {
                                    log.AppendLine("failed");
                                    log.AppendLine($" -> Unabled to find ADF disk file with letter '{disk}'. Try to rename your ADF file to 'ambermoon_{disk}.adf'.");
                                }

                                if (stopAtFirstError)
                                {
                                    throw new FileNotFoundException($"Unabled to find ADF disk file with letter '{disk}'. Try to rename your ADF file to 'ambermoon_{disk}.adf'.");
                                }
                            }

                            if (loadPreference == LoadPreference.PreferAdf)
                            {
                                if (!fileExistChecker(name))
                                {
                                    HandleFileNotFound(name, disk);
                                }
                                else
                                {
                                    Files.Add(name, fileLoader(name));
                                    HandleFileLoaded(name);
                                }
                            }

                            continue;
                        }

                        loadedDisks.Add(disk, loadedDisk);
                    }

                    if (!loadedDisks[disk].ContainsKey(name))
                    {
                        HandleFileNotFound(name, disk);
                    }
                    else
                    {
                        GameDataSource = GameDataSource.ADF;
                        Files.Add(name, fileReader.ReadFile(name, loadedDisks[disk][name]));
                        HandleFileLoaded(name);
                    }
                }
            }

            if (savesOnly)
            {
                Loaded = true;
                return;
            }

            if (foundNoDictionary && stopAtFirstError)
            {
                throw new FileNotFoundException("Unable to find any dictionary file.");
            }

            LoadTravelGraphics();

            try
            {
                var possibleAssemblies = new string[2] {
                    "AM2_CPU", "AM2_BLIT"
                };

                foreach (var assembly in possibleAssemblies)
                {
                    if (Files.ContainsKey(assembly))
                    {
                        var file = Files[assembly].Files[1];

                        if (file.Size >= 128)
                        {
                            file.Position = file.Size - 128;
                            Version       = GetVersionFromAssembly(file.ReadToEnd(), out var language);
                            Language      = language;
                            file.Position = 0;
                            break;
                        }
                    }
                }
            }
            catch
            {
                // ignore
            }

            Loaded = true;
        }
Esempio n. 19
0
        private async void RunImportDictionaryCommand()
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.FileTypeFilter.Add(".txt");
            fileOpenPicker.FileTypeFilter.Add(".zip");

            IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow.Instance);

            WinRT.Interop.InitializeWithWindow.Initialize(fileOpenPicker, hwnd);

            IReadOnlyList <StorageFile> wordlistFiles = await fileOpenPicker.PickMultipleFilesAsync();

            if (wordlistFiles == null)
            {
                return;
            }

            foreach (StorageFile wordlistFile in wordlistFiles)
            {
                WordlistReader wordlistReader = new WordlistReader(wordlistFile);

                try
                {
                    await wordlistReader.ReadHeader();
                }
                catch
                {
                    wordlistReader.Dispose();

                    ContentDialog contentDialog = new ContentDialog()
                    {
                        Title           = resourceLoader.GetString("Import_Header_Error_Title"),
                        Content         = string.Format(resourceLoader.GetString("Import_Header_Error_Body"), wordlistFile.Name),
                        CloseButtonText = "OK",
                        XamlRoot        = MainWindow.Instance.Content.XamlRoot
                    };

                    await contentDialog.ShowAsync();

                    continue;
                }

                bool allConflictsResolved = await CheckForConflictingDictionary(wordlistReader);

                if (allConflictsResolved)
                {
                    DictionaryViewModel dictionaryViewModel = new DictionaryViewModel(wordlistReader);

                    Dictionaries.Add(dictionaryViewModel);
                }
                else
                {
                    wordlistReader.Dispose();
                }
            }

            if (!IsImportInProgress)
            {
                cancellationTokenSource = new CancellationTokenSource();
                importQueueProcessTask  = ProcessImportQueue();
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Sets new project as current.
        /// </summary>
        /// <param name="project"></param>
        public void SelectProject(string project)
        {
            // language might be null during the proccess
            // of changing language.
            if (currentLanguage == null)
            {
                return;
            }

            Log.Logger.Debug("New project is chosen.");
            currentProject = project;
            // Get custom project dictionaries
            IEnumerable <string> projectSpecificDics;

            if (IOTools.ListFiles(Config.ProjectDicPath, out projectSpecificDics))
            {
                // Add found dictionaries to dict collection.
                foreach (string fName in projectSpecificDics)
                {
                    Dictionaries.Add(new Dict
                    {
                        FileName = fName,
                        DictType = DictType.Project,
                        FilePath = IOTools.CombinePath(Config.ProjectDicPath, fName)
                    });
                }
            }

            // Get general project dictionaries.
            IEnumerable <string> generalDics;

            if (IOTools.ListFiles(Config.GenDicPath, out generalDics))
            {
                // Combine both specific and general dictionaries
                foreach (string fName in generalDics)
                {
                    Dictionaries.Add(new Dict
                    {
                        FileName = fName,
                        DictType = DictType.General,
                        FilePath = IOTools.CombinePath(Config.GenDicPath, fName)
                    });
                }
            }

            // Get file names from project dir
            IEnumerable <string> fileNames;

            if (!IOTools.ListFiles(Config.ProjectFilesPath, out fileNames))
            {
                // Can't reach the folder, no sense to proceed further.
                return;
            }

            // Create FileStats object for every file name
            IEnumerable <FileStats> inDir = fileNames.Select(fName => new FileStats(
                                                                 fName,
                                                                 IOTools.CombinePath(Config.ProjectFilesPath, fName),
                                                                 currentLanguage,
                                                                 project
                                                                 ));

            // Get list of objects from DB
            List <FileStats> inDB = Storage.GetFilesStats(currentLanguage, project);

            // NB: inDB.Intersect will return elements from inDB.
            // Need this order since they have more information.
            foreach (FileStats item in inDB.Intersect(inDir))
            {
                // Files from DB have output page already
                item.OutPath = printer.GetOutPath(item.FileName);
                Files.Add(item);
            }

            // Add files that we have in dir but no stats in DB
            foreach (FileStats item in inDir.Except(inDB))
            {
                Files.Add(item);
            }

            // Remove leftover stats from DB.
            foreach (FileStats item in inDB.Except(inDir))
            {
                Log.Logger.Debug(string.Format("Going to remove {0} from DB", item.FileName));
                Storage.RemoveFileStats(item);
            }
            // Start watching files in the project.
            watcher.ToggleOnProject(Config.ProjectDicPath, Config.GenDicPath, Config.ProjectFilesPath);
        }