/* * protected void SettingChanged(SettingChangedEventArgs args) * { * if (args.Setting is DyslexicModeSetting dyslexicModeSetting) * { * this.DyslexicMode = dyslexicModeSetting.value; * this.RecolourGUIs(); * LayoutRebuilder.MarkLayoutForRebuild(this.MainUI.GetComponent<RectTransform>()); * } * } */ protected void LoadDefaults() { string file = Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.SETTINGS_FOLDER + "/GUIDefaults.json"; if (File.Exists(file)) { this.LoadFontSettings( file, this.StandardFontSizes, this.LoadedFonts); } else { GlobalConstants.ActionLog.Log("COULD NOT FIND GUI DEFAULTS.", LogLevel.Error); } file = Directory.GetCurrentDirectory() + GlobalConstants.SETTINGS_FOLDER + "/DyslexicMode.json"; if (File.Exists(file)) { this.LoadFontSettings( file, this.DyslexicModeFontSizes, this.DyslexicModeFonts); } /* * this.DyslexicMode = (bool) GlobalConstants.GameManager.SettingsManager * .GetSetting(SettingNames.DYSLEXIC_MODE).objectValue; */ }
public object Search(string keyWord, int pageIndex, int pageSize) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); string indexPath = Directory.GetCurrentDirectory() + "/Index"; FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory()); IndexReader reader = IndexReader.Open(directory, true); //创建IndexSearcher准备进行搜索。 IndexSearcher searcher = new IndexSearcher(reader); // 查询条件 keyWord = GetKeyWordsSplitBySpace(keyWord, new PanGuTokenizer()); //创建QueryParser查询解析器。用来对查询语句进行语法分析。 //QueryParser调用parser进行语法分析,形成查询语法树,放到Query中。 QueryParser msgQueryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Content", new PanGuAnalyzer(true)); Query msgQuery = msgQueryParser.Parse(keyWord); //TopScoreDocCollector:盛放查询结果的容器 //numHits 获取条数 TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true); //IndexSearcher调用search对查询语法树Query进行搜索,得到结果TopScoreDocCollector。 // 使用query这个查询条件进行搜索,搜索结果放入collector searcher.Search(msgQuery, null, collector); // 从查询结果中取出第n条到第m条的数据 ScoreDoc[] docs = collector.TopDocs(0, 1000).scoreDocs; stopwatch.Stop(); // 遍历查询结果 List <ReturnModel> resultList = new List <ReturnModel>(); var pm = new Page <ReturnModel> { PageIndex = pageIndex, PageSize = pageSize, TotalRows = docs.Length }; pm.TotalPages = pm.TotalRows / pageSize; if (pm.TotalRows % pageSize != 0) { pm.TotalPages++; } for (int i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize && i < docs.Length; i++) { var doc = searcher.Doc(docs[i].doc); var content = HighlightHelper.HighLight(keyWord, doc.Get("Content")); var result = new ReturnModel { Title = doc.Get("Title"), Content = content, Count = Regex.Matches(content, "<font").Count }; resultList.Add(result); } pm.LsList = resultList; var elapsedTime = stopwatch.ElapsedMilliseconds + "ms"; var list = new { list = pm, ms = elapsedTime }; return(list); }
private async Task <(Stream stream, string contentType, string fileName)> GetRemoteRun(string os, string pre, CancellationToken cancellationToken) { var host = Request.Scheme + "://" + Request.Host; var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "RemoteAgents"); var osName = os.ToLower(); switch (osName) { case "osx": case "linux": case "alpine": var file = await System.IO.File.ReadAllLinesAsync(Path.Combine(path, $"dexih.remote.run.{osName}.sh"), cancellationToken); for (var i = 0; i < file.Length; i++) { if (file[i].Contains("{{SERVER}}")) { file[i] = file[i].Replace("{{SERVER}}", host); } if (file[i].Contains("{{PRE}}")) { file[i] = file[i].Replace("{{PRE}}", pre); } } var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(string.Join('\n', file))); return(memoryStream, "text/plain", $"dexih.remote.run.{osName}.sh"); case "windows": var file2 = System.IO.File.OpenRead(Path.Combine(path, $"dexih.remote.run.exe")); return(file2, "application/octet-stream", $"dexih.remote.run.exe"); } throw new RemoteAgentControllerException($"The operating system {os} is not supported."); }
public static void SaveDefaultWindowPreferences() { // Save Project Current Layout SaveWindowLayout(Path.Combine(Directory.GetCurrentDirectory(), kCurrentLayoutPath)); // Save Global Last Layout SaveWindowLayout(Path.Combine(layoutsPreferencesPath, kLastLayoutName)); }
public IEnumerable <IGender> Load() { HashSet <IGender> genders = new HashSet <IGender>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "/Genders", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Could not parse JSON in " + file + " into a Dictionary.", LogLevel.Warning); continue; } ICollection <Dictionary> gendersCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Genders"); foreach (Dictionary gender in gendersCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Name"); string possessive = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Possessive"); string personalSubject = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PersonalSubject"); string personalObject = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PersonalObject"); string reflexive = this.ValueExtractor.GetValueFromDictionary <string>(gender, "Reflexive"); string possessivePlural = this.ValueExtractor.GetValueFromDictionary <string>(gender, "PossessivePlural"); string reflexivePlural = this.ValueExtractor.GetValueFromDictionary <string>(gender, "ReflexivePlural"); string isOrAre = this.ValueExtractor.GetValueFromDictionary <string>(gender, "IsOrAre"); genders.Add(new BaseGender( name, possessive, personalSubject, personalObject, reflexive, possessivePlural, reflexivePlural, isOrAre)); } } return(genders); }
protected void LoadDefinitions() { string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Sprite Definitions/GUI/", "*.json", SearchOption.AllDirectories); foreach (string file in files) { if (File.Exists(file) == false) { GlobalConstants.ActionLog.Log("Could not find GUI definitions file " + file, LogLevel.Warning); return; } JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning); return; } string tileSetName = this.ValueExtractor.GetValueFromDictionary <string>( this.ValueExtractor.GetValueFromDictionary <Dictionary>(dictionary, "TileSet"), "Name"); var spriteData = GlobalConstants.GameManager.ObjectIconHandler.GetTileSet(tileSetName); foreach (SpriteData data in spriteData) { if (this.Themes.ContainsKey(data.m_Name) == false) { Theme theme = new Theme(); theme.SetIcon(data.m_Name, "ManagedUIElement", data.m_Parts.First().m_FrameSprite.GetFrame("default", 0)); this.Themes.Add(data.m_Name, theme); } if (this.UISprites.ContainsKey(data.m_Name)) { continue; } this.UISprites.Add(data.m_Name, new SpriteState(data.m_Name, data)); } } }
private void Finish_OnClick(object sender, RoutedEventArgs e) { if (_rollback && !_fatal) { Process.Start(_info); Process.GetCurrentProcess().Kill(); return; } if (_fatal) { Process.GetCurrentProcess().Kill(); return; } if (!string.IsNullOrEmpty(_exe)) { _info = new ProcessStartInfo(_exe); _info.Arguments = _argv; } if (_info == null) { _report("There is no exe file specified for the new app."); } else { Process.Start(_info); } ProcessStartInfo info = new ProcessStartInfo(); info.WindowStyle = ProcessWindowStyle.Hidden; info.CreateNoWindow = true; if (_config.replaceUpdateProgressExe) { string del = _backupPath.Substring(0, _backupPath.Length - _backupPath.Split('\\').Last().Length); string script = CreateScript(_config.updateProgressSrc.Substring(0, _config.updateProgressSrc.Length - "Update progress.exe".Length - 1), _config.appPath, "Update progress.exe", del); File.WriteAllText($"{Path.GetTempPath()}script.bat", script); info.FileName = $"{Path.GetTempPath()}script.bat"; info.UseShellExecute = true; } if (_config.deleteUpdateProgressExe) { info.Arguments = string.Format($"{FileSystemActions.Commands.Pause2SecCommand} & {FileSystemActions.Commands.DeleteFile}", $"{Directory.GetCurrentDirectory()}\\Update progress.exe"); info.FileName = "cmd.exe"; } _disable(Finish); Process.Start(info); Process.GetCurrentProcess().Kill(); }
protected IEnumerable <BaseItemType> LoadComponents() { string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Items/Components", "*.json", SearchOption.AllDirectories); return(this.GetTypesFromJson(files)); }
public async Task <IActionResult> DeleteDocument(int id) { Document docDelete = await dr.GetByIdAsync(id); if (docDelete != null) { string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "documents", docDelete.Name + "." + docDelete.FileType); System.IO.File.Delete(filePath); await dr.DeleteByIdAsync(docDelete); } return(RedirectToAction("Index", "Home")); }
/// <summary> /// Find a file on Current Directory and in all Subdirectories /// </summary> /// <param name="fileName"></param> /// <param name="extension"></param> /// <returns></returns> private string FindFileOnCurrentDirectoryPath(string fileName, string extension = "*.*") { string ret = ""; string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), extension, SearchOption.AllDirectories); foreach (string s in files) { if (s.Contains(fileName)) { return(s); } } return(ret); }
public string CreateIndex() { //索引保存位置 var indexPath = Directory.GetCurrentDirectory() + "/Index"; if (!Directory.Exists(indexPath)) { Directory.CreateDirectory(indexPath); } FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory()); if (IndexWriter.IsLocked(directory)) { // 如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁 // Lucene.Net在写索引库之前会自动加锁,在close的时候会自动解锁 IndexWriter.Unlock(directory); } //Lucene的index模块主要负责索引的创建 // 创建向索引库写操作对象 IndexWriter(索引目录,指定使用盘古分词进行切词,最大写入长度限制) // 补充:使用IndexWriter打开directory时会自动对索引库文件上锁 //IndexWriter构造函数中第一个参数指定索引文件存储位置; //第二个参数指定分词Analyzer,Analyzer有多个子类, //然而其分词效果并不好,这里使用的是第三方开源分词工具盘古分词; //第三个参数表示是否重新创建索引,true表示重新创建(删除之前的索引文件), //最后一个参数指定Field的最大数目。 IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED); var txtPath = Directory.GetCurrentDirectory() + "/Upload/Articles"; for (int i = 1; i <= 1000; i++) { // 一条Document相当于一条记录 Document document = new Document(); var title = "天骄战纪_" + i + ".txt"; var content = System.IO.File.ReadAllText(txtPath + "/" + title, Encoding.Default); // 每个Document可以有自己的属性(字段),所有字段名都是自定义的,值都是string类型 // Field.Store.YES不仅要对文章进行分词记录,也要保存原文,就不用去数据库里查一次了 document.Add(new Field("Title", "天骄战纪_" + i, Field.Store.YES, Field.Index.NOT_ANALYZED)); // 需要进行全文检索的字段加 Field.Index. ANALYZED // Field.Index.ANALYZED:指定文章内容按照分词后结果保存,否则无法实现后续的模糊查询 // WITH_POSITIONS_OFFSETS:指示不仅保存分割后的词,还保存词之间的距离 document.Add(new Field("Content", content, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(document); } writer.Close(); // Close后自动对索引库文件解锁 directory.Close(); // 不要忘了Close,否则索引结果搜不到 return("索引创建完毕"); }
public static string CompareDocument(this Document doc1, Document doc2) { if (doc1.FileType != "docx" || doc2.FileType != "docx") { return("Cant Compare"); } var document1 = new Aspose.Words.Document(Path.Combine(GetPath(), doc1.Name + "." + doc1.FileType)); var document2 = new Aspose.Words.Document(Path.Combine(GetPath(), doc2.Name + "." + doc2.FileType)); string compareFileName = "Compare " + doc1.Name + " - " + doc2.Name + ".docx"; var documentCompare = new Aspose.Words.Document(Path.Combine(GetPath(), doc1.Name + "." + doc1.FileType)); DocumentBuilder builder = new DocumentBuilder(documentCompare); //TODO: extends compare (use Revision Document) document1.Compare(document2, "nhan1110i", DateTime.Now); document1.Save(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Temp", compareFileName)); return(compareFileName); }
public async Task <FileResult> CompareDocument(int doc1, int doc2) { Document firstDocument = await dr.GetByIdAsync(doc1); Document secondDocument = await dr.GetByIdAsync(doc2); //var compareWord = new Aspose.Words.Document(firstDocument.CompareDocument(secondDocument)); var result = new Document { Name = firstDocument.CompareDocument(secondDocument), FileType = FileType.DOCX, Id = 0 }; string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Temp", result.Name); byte[] file = System.IO.File.ReadAllBytes(filePath); return(File(file, "application/force-download", result.Name)); }
public IEnumerable <KeyValuePair <string, string> > InFiles(string directoryPath, string pattern, bool recursive = true, bool caseInsensitive = false) { if (string.IsNullOrEmpty(pattern)) { return(_empty); } if (directoryPath == "") { directoryPath = IoDir.GetCurrentDirectory(); } else if (directoryPath != "") { var x = directoryPath; directoryPath = x; } var results = SearchDirectory(directoryPath, pattern, recursive, caseInsensitive); return(results); }
public static void SaveDefaultWindowPreferences() { // Do not save layout to default if running tests if (!InternalEditorUtility.isHumanControllingUs) { return; } // Save Project Current Layout SaveWindowLayout(Path.Combine(Directory.GetCurrentDirectory(), kCurrentLayoutPath)); // Make sure we have a layout directory to save the last layout. if (!Directory.Exists(layoutsPreferencesPath)) { Directory.CreateDirectory(layoutsPreferencesPath); } // Save Global Last Layout SaveWindowLayout(Path.Combine(layoutsPreferencesPath, kLastLayoutName)); }
public Index AddIndex(string url, string name) { string path = Path.Combine(Directory.GetCurrentDirectory(), "APP_DATA", "Indices", name); string temp = Path.Combine(Directory.GetCurrentDirectory(), "APP_DATA", "temp", name); Directory.CreateDirectory(path); Directory.CreateDirectory(temp); IReplicator replicator = new HttpReplicator($"{url}/api/replicate/{name}"); FSDirectory directory = FSDirectory.Open(path); Index index = new Index(directory, name); indices.Add(name, index); ReplicationClient client = new ReplicationClient(replicator, new IndexReplicationHandler(directory, index.UpdateIndex), new PerSessionDirectoryFactory(temp)); client.UpdateNow(); client.StartUpdateThread(5000, "Replicator Thread"); replicators.Add(name, client); return(index); }
public IEnumerable <IBioSex> Load() { List <IBioSex> sexes = new List <IBioSex>(); this.Processors = GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <IBioSexProcessor>() .ToDictionary(processor => processor.Name, processor => processor); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "/Sexes", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Could not parse JSON in " + file + " into a Dictionary.", LogLevel.Warning); continue; } ICollection <Dictionary> sexesCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Sexes"); foreach (Dictionary innerDict in sexesCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Name"); bool canBirth = this.ValueExtractor.GetValueFromDictionary <bool>(innerDict, "CanBirth"); bool canFertilise = this.ValueExtractor.GetValueFromDictionary <bool>(innerDict, "CanFertilise"); string processorString = innerDict.Contains("Processor") ? this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Processor") : "Neutral"; ICollection <string> tags = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(innerDict, "Tags"); IBioSexProcessor processor = this.Processors.Values.FirstOrDefault(preferenceProcessor => preferenceProcessor.Name.Equals(processorString, StringComparison.OrdinalIgnoreCase)) ?? new NeutralProcessor(); sexes.Add( new BaseBioSex( name, canBirth, canFertilise, processor, tags)); } } sexes.AddRange(GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <IBioSex>()); return(sexes); }
public IEnumerable <IEntityTemplate> Load() { List <IEntityTemplate> entities = new List <IEntityTemplate>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Entities", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { GlobalConstants.ActionLog.Log("Could not load entity templates from " + file, LogLevel.Warning); GlobalConstants.ActionLog.Log(result.ErrorString, LogLevel.Warning); GlobalConstants.ActionLog.Log("On line: " + result.ErrorLine, LogLevel.Warning); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning); continue; } Array templateArray = this.ValueExtractor.GetValueFromDictionary <Array>(dictionary, "Entities"); foreach (Dictionary templateDict in templateArray) { string creatureType = this.ValueExtractor.GetValueFromDictionary <string>(templateDict, "CreatureType"); string type = this.ValueExtractor.GetValueFromDictionary <string>(templateDict, "Type"); string visionType = this.ValueExtractor.GetValueFromDictionary <string>(templateDict, "VisionType") ?? "diurnal vision"; IVision vision = this.VisionProviderHandler.Get(visionType); string description = this.ValueExtractor.GetValueFromDictionary <string>(templateDict, "Description"); IDictionary <string, IEntityStatistic> statistics = new System.Collections.Generic.Dictionary <string, IEntityStatistic>(); ICollection <Dictionary> statisticsCollection = this.ValueExtractor.GetCollectionFromArray <Dictionary>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Statistics")); foreach (Dictionary innerDict in statisticsCollection) { string statName = this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Name"); int statValue = this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "Value"); int threshold = innerDict.Contains("Threshold") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "Threshold") : GlobalConstants.DEFAULT_SUCCESS_THRESHOLD; IEntityStatistic statistic = GlobalConstants.GameManager.StatisticHandler.Get(statName); statistic.SetValue(statValue); statistic.SetThreshold(threshold); statistics.Add( statName, statistic); } IDictionary <string, IEntitySkill> skills = new System.Collections.Generic.Dictionary <string, IEntitySkill>(); if (templateDict.Contains("Skills")) { ICollection <Dictionary> skillCollection = this.ValueExtractor.GetCollectionFromArray <Dictionary>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Skills")); foreach (Dictionary innerDict in skillCollection) { string skillName = this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Name"); int skillValue = this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "Value"); int threshold = innerDict.Contains("Threshold") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "Threshold") : GlobalConstants.DEFAULT_SUCCESS_THRESHOLD; IEntitySkill skill = GlobalConstants.GameManager.SkillHandler.Get(skillName); skill.SetValue(skillValue); skill.SetThreshold(threshold); skills.Add( skillName, skill); } } ICollection <string> tags = this.ValueExtractor.GetCollectionFromArray <string>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Tags")); ICollection <string> slots = this.ValueExtractor.GetCollectionFromArray <string>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Slots")); ICollection <string> needs = this.ValueExtractor.GetCollectionFromArray <string>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Needs")); ICollection <IAbility> abilities = new List <IAbility>(); if (templateDict.Contains("Abilities")) { ICollection <string> abilityNames = this.ValueExtractor.GetCollectionFromArray <string>( this.ValueExtractor.GetValueFromDictionary <Array>(templateDict, "Abilities")); foreach (string name in abilityNames) { abilities.Add(this.AbilityHandler.Get(name)); } } int size = this.ValueExtractor.GetValueFromDictionary <int>(templateDict, "Size"); entities.Add( new EntityTemplate( statistics, skills, needs.ToArray(), abilities.ToArray(), slots.ToArray(), size, vision, creatureType, type, description, tags.ToArray())); } } return(entities); }
private static string GetJsonOutputPath() { var jop = _appSettings["jsonOutFile"]; return(string.IsNullOrWhiteSpace(jop) ? @"c:\temp\npcs.json" : Path.Combine(Directory.GetCurrentDirectory(), jop)); }
public IEnumerable <WorldInfo> Load() { string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "World Spaces", "*.json", SearchOption.AllDirectories); List <WorldInfo> worldInfos = new List <WorldInfo>(); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning); continue; } ICollection <Dictionary> infoCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "WorldInfo"); foreach (Dictionary worldInfo in infoCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(worldInfo, "Name"); if (name.IsNullOrEmpty()) { continue; } IEnumerable <string> inhabitants = worldInfo.Contains("Inhabitants") ? this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(worldInfo, "Inhabitants") : new string[0]; IEnumerable <string> cultures = worldInfo.Contains("Cultures") ? this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(worldInfo, "Cultures") : new string[0]; IEnumerable <string> tags = worldInfo.Contains("Tags") ? this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(worldInfo, "Tags") : new string[0]; string tileSetName = this.ValueExtractor.GetValueFromDictionary <string>( this.ValueExtractor.GetValueFromDictionary <Dictionary>(worldInfo, "TileSet"), "Name"); this.ObjectIcons.AddSpriteDataFromJson(worldInfo); worldInfos.Add(new WorldInfo { inhabitants = inhabitants, name = name, tags = tags, cultures = cultures }); this.WorldTiles.Add( name, new WorldTile( name, tileSetName, tags)); } } return(worldInfos); }
public IEnumerable <IRelationship> Load() { List <IRelationship> relationships = new List <IRelationship>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "/Relationships", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Failed to parse JSON from " + file + " into a Dictionary.", LogLevel.Warning); continue; } ICollection <Dictionary> relationshipCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Relationships"); foreach (Dictionary relationship in relationshipCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(relationship, "Name"); string displayName = this.ValueExtractor.GetValueFromDictionary <string>(relationship, "DisplayName"); IEnumerable <string> uniqueTags = relationship.Contains("UniqueTags") ? this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(relationship, "UniqueTags") : new string[0]; int maxParticipants = relationship.Contains("MaxParticipants") ? this.ValueExtractor.GetValueFromDictionary <int>(relationship, "MaxParticipants") : -1; IEnumerable <string> tags = relationship.Contains("Tags") ? this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(relationship, "Tags") : new string[0]; relationships.Add( new BaseRelationship( name, displayName, maxParticipants, uniqueTags, null, null, tags)); } } relationships.AddRange(GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <IRelationship>()); return(relationships); }
public IEnumerable <IRomance> Load() { List <IRomance> romances = new List <IRomance>(); this.Processors = GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <IRomanceProcessor>() .ToDictionary(processor => processor.Name, processor => processor); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "/Romance", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Failed to parse JSON in " + file + " into a Dictionary.", LogLevel.Warning); continue; } ICollection <Dictionary> romanceCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Romance"); foreach (Dictionary romance in romanceCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(romance, "Name"); bool decaysNeed = romance.Contains("DecaysNeed") && this.ValueExtractor.GetValueFromDictionary <bool>(romance, "DecaysNeed"); int romanceThreshold = romance.Contains("RomanceThreshold") ? this.ValueExtractor.GetValueFromDictionary <int>(romance, "RomanceThreshold") : 0; int bondingThreshold = romance.Contains("BondingThreshold") ? this.ValueExtractor.GetValueFromDictionary <int>(romance, "BondingThreshold") : 0; string processorString = romance.Contains("Processor") ? this.ValueExtractor.GetValueFromDictionary <string>(romance, "Processor") : "aromantic"; ICollection <string> tags = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(romance, "Tags"); IRomanceProcessor processor = this.Processors.Values.FirstOrDefault(preferenceProcessor => preferenceProcessor.Name.Equals(processorString, StringComparison.OrdinalIgnoreCase)) ?? new AromanticProcessor(); romances.Add( new BaseRomance( name, decaysNeed, romanceThreshold, bondingThreshold, processor, tags)); } } romances.AddRange(GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <IRomance>()); return(romances); }
public IEnumerable <IVision> Load() { List <IVision> visionTypes = new List <IVision>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Vision Types", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary visionDict)) { GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning); continue; } ICollection <Dictionary> visions = this.ValueExtractor.GetCollectionFromArray <Dictionary>( this.ValueExtractor.GetValueFromDictionary <Array>( visionDict, "VisionTypes")); foreach (Dictionary innerDict in visions) { string name = this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Name"); Color lightColour = new Color(this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "LightColour")); Color darkColour = new Color(this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "DarkColour")); int minimumLight = innerDict.Contains("MinimumLight") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "MinimumLight") : 0; int minimumComfort = innerDict.Contains("MinimumComfort") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "MinimumComfort") : minimumLight; int maximumLight = innerDict.Contains("MaximumLight") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "MaximumLight") : GlobalConstants.MAX_LIGHT; int maximumComfort = innerDict.Contains("MaximumComfort") ? this.ValueExtractor.GetValueFromDictionary <int>(innerDict, "MaximumComfort") : maximumLight; string visionProvider = innerDict.Contains("Algorithm") ? this.ValueExtractor.GetValueFromDictionary <string>(innerDict, "Algorithm") : nameof(FOVShadowCasting); IFOVHandler handler = (IFOVHandler)GlobalConstants.ScriptingEngine.FetchAndInitialise(visionProvider); visionTypes.Add( new BaseVisionProvider( darkColour, lightColour, handler, minimumLight, minimumComfort, maximumLight, maximumComfort, name)); } } return(visionTypes); }
public IEnumerable <IJob> Load() { List <IJob> jobTypes = new List <IJob>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Jobs", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dictionary)) { GlobalConstants.ActionLog.Log("Failed to parse JSON from " + file + " into a Dictionary.", LogLevel.Warning); continue; } ICollection <Dictionary> jobCollection = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(dictionary, "Jobs"); foreach (Dictionary job in jobCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(job, "Name"); string description = this.ValueExtractor.GetValueFromDictionary <string>(job, "Description") ?? "NO DESCRIPTION PROVIDED."; IDictionary <string, int> statisticDiscounts = new System.Collections.Generic.Dictionary <string, int>(); if (job.Contains("Statistics")) { ICollection <Dictionary> statistics = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(job, "Statistics"); foreach (Dictionary statistic in statistics) { statisticDiscounts.Add( this.ValueExtractor.GetValueFromDictionary <string>(statistic, "Name"), this.ValueExtractor.GetValueFromDictionary <int>(statistic, "Discount")); } } IDictionary <string, int> skillDiscounts = new System.Collections.Generic.Dictionary <string, int>(); if (job.Contains("Skills")) { ICollection <Dictionary> skills = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(job, "Skills"); foreach (Dictionary skill in skills) { skillDiscounts.Add( this.ValueExtractor.GetValueFromDictionary <string>(skill, "Name"), this.ValueExtractor.GetValueFromDictionary <int>(skill, "Discount")); } } IDictionary <IAbility, int> abilityCosts = new System.Collections.Generic.Dictionary <IAbility, int>(); if (job.Contains("Abilities")) { ICollection <Dictionary> abilities = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <Dictionary>(job, "Abilities"); foreach (Dictionary ability in abilities) { abilityCosts.Add( this.AbilityHandler.Get( this.ValueExtractor.GetValueFromDictionary <string>(ability, "Name")), this.ValueExtractor.GetValueFromDictionary <int>(ability, "Cost")); } } Color abilityIconColour = Colors.White; Color abilityBackgroundColour = Colors.Black; if (job.Contains("Colours")) { Dictionary colours = this.ValueExtractor.GetValueFromDictionary <Dictionary>(job, "Colours"); abilityIconColour = new Color(this.ValueExtractor.GetValueFromDictionary <string>(colours, "Icon")); abilityBackgroundColour = new Color(this.ValueExtractor.GetValueFromDictionary <string>(colours, "Background")); } jobTypes.Add( new JobType( name, description, statisticDiscounts, skillDiscounts, abilityCosts, abilityIconColour, abilityBackgroundColour)); } } return(jobTypes); }
public IEnumerable <ICulture> Load() { string folderPath = Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "Cultures"; string[] files = Directory.GetFiles(folderPath, "*.json", SearchOption.AllDirectories); List <ICulture> cultures = new List <ICulture>(); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary cultureDict)) { GlobalConstants.ActionLog.Log("Could not parse JSON to Dictionary from " + file, LogLevel.Warning); continue; } Array cultureArray = this.ValueExtractor.GetValueFromDictionary <Array>(cultureDict, "Cultures"); foreach (Dictionary culture in cultureArray) { string cultureName = this.ValueExtractor.GetValueFromDictionary <string>(culture, "CultureName"); string description = this.ValueExtractor.GetValueFromDictionary <string>(culture, "Description"); int nonconformingGenderChance = this.ValueExtractor.GetValueFromDictionary <int>(culture, "NonConformingGenderChance"); ICollection <string> rulers = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(culture, "Rulers"); ICollection <string> crimes = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(culture, "Crimes"); ICollection <string> inhabitants = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(culture, "Inhabitants"); ICollection <string> relationships = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(culture, "Relationships"); List <NameData> nameDatas = new List <NameData>(); Array entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Names"); ICollection <Dictionary> nameData = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); foreach (var data in nameData) { string name = this.ValueExtractor.GetValueFromDictionary <string>(data, "Name"); ICollection <int> chain = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <int>(data, "Chain"); ICollection <int> groups = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <int>(data, "Group"); ICollection <string> genders = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(data, "Gender"); nameDatas.Add(new NameData( name, chain.ToArray(), genders.ToArray(), groups.ToArray())); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Sexualities"); ICollection <Dictionary> inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, int> sexualities = new System.Collections.Generic.Dictionary <string, int>(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); sexualities.Add(name, weight); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Sexes"); inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, int> sexes = new System.Collections.Generic.Dictionary <string, int>(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); sexes.Add(name, weight); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Romances"); inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, int> romances = new System.Collections.Generic.Dictionary <string, int>(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); romances.Add(name, weight); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Genders"); inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, int> genderChances = new System.Collections.Generic.Dictionary <string, int>(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); genderChances.Add(name, weight); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Jobs"); inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, int> jobs = new System.Collections.Generic.Dictionary <string, int>(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); jobs.Add(name, weight); } entry = this.ValueExtractor.GetValueFromDictionary <Array>(culture, "Statistics"); inner = this.ValueExtractor.GetCollectionFromArray <Dictionary>(entry); IDictionary <string, Tuple <int, int> > statistics = new System.Collections.Generic.Dictionary <string, Tuple <int, int> >(); foreach (Dictionary dict in inner) { string name = this.ValueExtractor.GetValueFromDictionary <string>(dict, "Name"); int weight = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Chance"); int magnitude = this.ValueExtractor.GetValueFromDictionary <int>(dict, "Magnitude"); statistics.Add( name, new Tuple <int, int>( weight, magnitude)); } this.IconHandler.AddSpriteDataFromJson(culture); string tileSetName = this.ValueExtractor.GetValueFromDictionary <string>( this.ValueExtractor.GetValueFromDictionary <Dictionary>( culture, "TileSet"), "Name"); Dictionary uiColours = this.ValueExtractor.GetValueFromDictionary <Dictionary>(culture, "UIColours"); IDictionary <string, IDictionary <string, Color> > backgroundColours = this.ExtractColourData( uiColours, "BackgroundColours"); IDictionary <string, IDictionary <string, Color> > cursorColours = this.ExtractColourData( uiColours, "CursorColours"); IDictionary <string, Color> fontColours = this.ExtractFontData( uiColours, "FontColours"); cultures.Add( new CultureType( cultureName, tileSetName, description, rulers, crimes, nameDatas, jobs, inhabitants, sexualities, sexes, statistics, relationships, romances, genderChances, nonconformingGenderChance, backgroundColours, cursorColours, fontColours)); } } return(cultures); }
public IEnumerable <ISexuality> Load() { this.PreferenceProcessors = GlobalConstants.ScriptingEngine .FetchAndInitialiseChildren <ISexualityPreferenceProcessor>() .ToDictionary(processor => processor.Name, processor => processor); List <ISexuality> sexualities = new List <ISexuality>(); string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() + GlobalConstants.ASSETS_FOLDER + GlobalConstants.DATA_FOLDER + "/Sexualities", "*.json", SearchOption.AllDirectories); foreach (string file in files) { JSONParseResult result = JSON.Parse(File.ReadAllText(file)); if (result.Error != Error.Ok) { this.ValueExtractor.PrintFileParsingError(result, file); continue; } if (!(result.Result is Dictionary dict)) { GlobalConstants.ActionLog.Log("Could not parse JSON into Dictionary, in file " + file, LogLevel.Warning); continue; } ICollection <Dictionary> sexualityCollection = this.ValueExtractor.GetCollectionFromArray <Dictionary>( this.ValueExtractor.GetValueFromDictionary <Array>(dict, "Sexualities")); foreach (Dictionary sexuality in sexualityCollection) { string name = this.ValueExtractor.GetValueFromDictionary <string>(sexuality, "Name"); bool decaysNeed = !sexuality.Contains("DecaysNeed") || this.ValueExtractor.GetValueFromDictionary <bool>(sexuality, "DecaysNeed"); int matingThreshold = sexuality.Contains("MatingThreshold") ? this.ValueExtractor.GetValueFromDictionary <int>(sexuality, "MatingThreshold") : 0; string processorName = sexuality.Contains("Processor") ? this.ValueExtractor.GetValueFromDictionary <string>(sexuality, "Processor") : "asexual"; ICollection <string> tags = this.ValueExtractor.GetArrayValuesCollectionFromDictionary <string>(sexuality, "Tags"); var preferenceProcessor = this.GetProcessor(processorName); sexualities.Add( new BaseSexuality( name, decaysNeed, matingThreshold, preferenceProcessor, tags)); } } IEnumerable <ISexuality> extraSexualities = GlobalConstants.ScriptingEngine.FetchAndInitialiseChildren <ISexuality>(); sexualities.AddRange(extraSexualities); return(sexualities); }
public Result <None> Run() => new ResharperCltUpdater() .UpdateIfNeed() .Then(_ => FileUtils.GetPathToSlnFile(PathToSlnFolder ?? Directory.GetCurrentDirectory())) .Then(StartCleanup);
private static string GetValuesPath() { var vp = _appSettings["values"]; return(string.IsNullOrWhiteSpace(vp) ? @"c:\temp\values.json" : Path.Combine(Directory.GetCurrentDirectory(), vp)); }
public static string GetCurrentDirectory() => MSIOD.GetCurrentDirectory();
public static DirectoryPath GetCurrentDirectory() => new DirectoryPath(D.GetCurrentDirectory());