private static bool loadModSessions(Session session) { if (CollabModule.Instance.SaveData.ModSessionsPerLevel.TryGetValue(session.Area.GetSID(), out Dictionary <string, string> sessions)) { // restore all mod sessions we can restore. foreach (EverestModule mod in Everest.Modules) { if (mod._Session != null && sessions.TryGetValue(mod.Metadata.Name, out string savedSession)) { try { // note: we are deserializing the session rather than just storing the object, because loading the session usually does that, // and a mod could react to a setter on its session being called. YamlHelper.DeserializerUsing(mod._Session).Deserialize(savedSession, mod.SessionType); } catch (Exception e) { // this is the same fallback message as the base EverestModule class if something goes wrong. Logger.Log(LogLevel.Warn, "CollabUtils2/ReturnToLobbyHelper", "Failed to load the session of " + mod.Metadata.Name + "!"); Logger.LogDetailed(e); } } } return(true); } return(false); }
public void Utf8CodepointsToEmoji() { var point = @"0001F338"; var hopefullyEmoji = YamlHelper.UnescapeUnicodeCodePoint(point); Assert.AreEqual("🌸", hopefullyEmoji, hopefullyEmoji); }
private void DoApplyEdit() { string s; switch (BlockFormat) { case "(unchanged)": s = YamlHelper.FormatBlock(CodeEditorController.Text, _selectedBlock.Suffix, _selectedBlock.Indent, ScalarType.None); break; case "Block": s = YamlHelper.FormatBlock(CodeEditorController.Text, _selectedBlock.Suffix, _selectedBlock.Indent, ScalarType.BlockFoldedStrip); break; case "Split": s = YamlHelper.FormatBlock(CodeEditorController.Text, _selectedBlock.Suffix, _selectedBlock.Indent, ScalarType.Plain); break; default: return; } YamlEditorController.SelectedText = s; CodeEditorController.Text = ""; CloseCodeEditor(); ApplicationDispatcher.Instance.BeginInvoke(DispatcherPriority.Render, YamlEditorController.BringSelectionIntoView); }
public async Task SaveAsync() { if (YamlHelper.TrySerialize(this, out string yaml)) { await File.WriteAllTextAsync(ConfigPath, yaml); } }
public void Test_Common() { var dtx = new DateTime(2009, 01, 08); var person = new Person() { Name = "test test test", BirthDay = dtx }; string yaml = YamlHelper.Serialize(person); using (var writer = new StreamWriter("test.yaml")) { writer.WriteLine(yaml); } using (var reader = new StreamReader("test.yaml")) { string content = reader.ReadToEnd(); var obj = YamlHelper.Deserialize(content) as Dictionary <object, object>; Assert.IsNotNull(obj); Assert.AreEqual("test test test", obj["Name"]); Assert.AreEqual(dtx, obj["BirthDay"]); var obj2 = YamlHelper.Deserialize(content, typeof(Person)); Assert.IsNotNull(obj2); var p2 = obj2[0] as Person; Assert.IsNotNull(p2); Assert.AreEqual("test test test", p2.Name); Assert.AreEqual(dtx, p2.BirthDay); } }
private static LanguageData Initialize() { LanguageData data = new LanguageData { LanguageFiles = new Dictionary <string, Dictionary <string, string> >(), DefaultFile = new Dictionary <string, string>() }; if (!Directory.Exists("Data/langs")) { return(data); } string[] langFiles = Directory.GetFiles("Data/langs"); foreach (string langFile in langFiles) { FileInfo fileInfo = new FileInfo(langFile); string name = fileInfo.Name.Remove(2); string yaml = File.ReadAllText(fileInfo.FullName); if (YamlHelper.TryDeserialize(yaml, out Dictionary <string, string> values)) { data.LanguageFiles.Add(name, values); if (name.Equals("EN")) { data.DefaultFile = values; } } else { data.LanguageFiles.Add(name, new Dictionary <string, string>()); } } return(data); }
// TODO: Repository to be added at the later stage #region Public Methods public List <Customer> GetCustomers() { var customers = new List <Customer>(); if (string.IsNullOrEmpty(_yamlFileOptions.FilePath)) { return(null); } var items = YamlFileUtility.ReadYamlFile(_yamlFileOptions.FilePath, "customers"); foreach (var yamlNode in items) { var item = (YamlMappingNode)yamlNode; var customer = new Customer { Id = YamlHelper.ConvertYamlScalarNodeToString(item, "id"), Name = YamlHelper.ConvertYamlScalarNodeToString(item, "name"), NumEmployees = Convert.ToInt16(YamlHelper.ConvertYamlScalarNodeToString(item, "num_employees")), Tags = YamlHelper.ConvertYamlScalarNodeToStingList(item, "tags") }; customers.Add(customer); } return(customers); }
public void SaveFile(string path) { var entity = ServiceConfigEntity.Import(this); using var fileStream = new FileStream(path, FileMode.Create); YamlHelper.WriteStream(fileStream, entity); }
public static ConfigurationDirectoryInfo CreateFromFile() { App.Trace($"Begin main config read started. Path: {FilePath}"); var item = YamlHelper.DeserializeFromFile <ConfigurationDirectoryInfo>(FilePath); App.Trace($"End main config read started. Path: {FilePath}"); return(item); }
public static string UnescapeUnicodeCodePoints(this string input) { return(CodePointRegex.Replace(input, me => { var str = me.Groups["code"].Value; var newString = YamlHelper.UnescapeUnicodeCodePoint(str); return newString; })); }
public List <T> GetObjects <T>() where T : Yaml_BaseObject { var pYamlType = YamlHelper.GetYamlType <T>(); List <Yaml_BaseObject> tObjects = null; if (!mCurrentDic.TryGetValue(pYamlType, out tObjects)) { return(null); } return(tObjects.ConvertAll(x => (T)x)); }
private void ParseConfig() { dynamic config = YamlHelper.ConfigFromFile("Translator/YandexTranslatorConfig.yaml"); _dictionaryUri = config["dictionary_uri"].ToString(); _dictionaryKey = config["dictionary_key"].ToString(); _detectLanguageUri = config["detect_language_uri"].ToString(); _tranlateKey = config["translate_key"].ToString(); _firstLanguage = config["first_language"].ToString(); _secondLanguage = config["second_language"].ToString(); }
public string Serialize <T>(T obj) { var escapedOutput = _serializer.Serialize(obj); var output = CodePointRegex.Replace(escapedOutput, me => { var str = me.Groups["code"].Value; var newString = YamlHelper.UnescapeUnicodeCodePoint(str); return(newString); }); return(output); }
private static T DeserializeYaml <T>(string path) { if (File.Exists(path)) { string yaml = File.ReadAllText(path); if (YamlHelper.TryDeserialize(yaml, out T value)) { return(value); } } throw new SerializationException($"Could not deserialize yaml file: \'{path}\'"); }
IEnumerator GetLocalManifest() { if (File.Exists(LocalManifestPath)) { mLocalManifest = YamlHelper.Deserialize <BundleManifest>(File.ReadAllText(LocalManifestPath)); } else { mLocalManifest = new BundleManifest(); } yield return(null); }
/// <summary> /// 保存为Conf文件 /// </summary> /// <param name="confFilename"></param> public static void SaveAsYmal(string confFilename) { var valueList = new List<ConfigurationFileOption.ConfigValue>(); var strValueList = new List<string>(); foreach (var item in SelectedConfigurationValueDictionary.Values) { valueList.Add(item); strValueList.Add(item.Path + ": " + item.ValueLiteral.Replace(".", YamlHelper.PointChar)); } //YMAL的做成 if (string.IsNullOrEmpty(confFilename)) confFilename = @"MongoService.conf"; YamlHelper.CreateFile(confFilename, strValueList); }
/// <summary> /// Custom startup so we load our IoC immediately before anything else /// </summary> /// <param name="e"></param> protected override async void OnStartup(StartupEventArgs e) { // Let the base application do what it needs. base.OnStartup(e); // Fix FPS. Timeline.DesiredFrameRateProperty.OverrideMetadata( typeof(Timeline), new FrameworkPropertyMetadata { DefaultValue = 60 } ); // Setup the main application ApplicationSetupAsync(); // Set up YAML config file(s). IoC.Application.CandyCategories = await YamlHelper.LoadConfigFile($"{AppDomain.CurrentDomain.BaseDirectory}"); // Pre-cache images. foreach (var category in IoC.Application.CandyCategories) { _cachedImages.Add(new BitmapImage(new Uri(category.ImageUrl), new HttpRequestCachePolicy(new DateTime(10000000)))); foreach (var type in category.CandyTypes) { _cachedImages.Add(new BitmapImage(new Uri(type.ImageUrl), new HttpRequestCachePolicy(new DateTime(10000000)))); } } // Setup the application view model. IoC.Application.GoToPage(DataModels.ApplicationPage.Categories, new CategoriesViewModel { PageLoadAnimation = PageAnimation.None, PageUnloadAnimation = PageAnimation.SlideOutToRight }); // Set up idle timer. IdleTimer.Interval = new TimeSpan(0, 0, 1); IdleTimer.Tick += (sender, arg) => { // If UI has been idle for 30 seconds. if (GetIdleTime() > 30 * 1000) { // Go back to main screen. IoC.Application.GoToPage(DataModels.ApplicationPage.Categories); IoC.Application.DarkeningGridOpacity = 0; IoC.Application.PayButtonVisibility = Visibility.Hidden; } }; IdleTimer.Start(); }
public static T ReadConfig <T>(params string[] folders) { var items = new List <string>(folders); if (ConfigurationDirectoryPath != null) { items.Insert(0, ConfigurationDirectoryPath); } items.Add(typeof(T).Name + ".yaml"); var filePath = string.Join(Path.DirectorySeparatorChar.ToString(), items); return(YamlHelper.DeserializeFromFile <T>(filePath)); }
private void DoEditScript() { YamlEditorController.ExpandCodeBlock(); _selectedBlock = YamlHelper.ExtractBlock(YamlEditorController.SelectedText); if (_selectedBlock == null) { return; } BlockFormat = "(unchanged)"; YamlEditorController.SetEnabled("YAML Editor is open", false); YamlEditorHeight = new GridLength(50); CodeEditorHeight = new GridLength(100, GridUnitType.Star); CodeEditorController.Text = _selectedBlock.Content; CodeEditorController.SetEnabled("Code Editor is open", true); Dispatcher.BeginInvoke(DispatcherPriority.Background, () => YamlEditorController.Data.ScrollToLine(YamlEditorController.Data.TextArea.Caret.Line)); }
public static ServiceConfig?LoadFile(string path) { try { if (!File.Exists(path)) { return(null); } using var fileStream = new FileStream(path, FileMode.Open); var entity = YamlHelper.ReadStream <ServiceConfigEntity>(fileStream); return(entity.Export()); } catch (Exception e) { _logger.Error(e); return(null); } }
public static void Main(string[] args) { #if !DEBUG start: try #endif { var config_file = (YamlMappingNode)YamlHelper.ParseFile(@"..\..\config.yaml"); var config = new AppConfig(Path.GetFullPath(@"..\.."), config_file); var downloader = new JavaVersionDownloader(); #if !DEBUG try #endif { downloader.DownloadMissing(config.Java.InputFolders, config); } #if !DEBUG catch (Exception ex) { Console.WriteLine("Java version downloader failed!"); Console.WriteLine(ex.ToString()); } #endif var java = new JavaUpdater(config); java.Perform(); var bedrock = new BedrockUpdater(config); bedrock.Perform(); Console.WriteLine("All done!"); } #if !DEBUG catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine(); Console.WriteLine("Press enter to try again"); Console.ReadLine(); goto start; } #endif }
public static T ReadConfig <T>(params string[] folders) { var items = new List <string>(folders); if (ConfigurationDirectoryPath != null) { items.Insert(0, ConfigurationDirectoryPath); } items.Add(typeof(T).Name + ".yaml"); var filePath = string.Join(Path.DirectorySeparatorChar.ToString(), items); if (!File.Exists(filePath)) { App.Trace($"File not found. FilePath: {filePath}"); throw new FileNotFoundException(filePath); } return(YamlHelper.DeserializeFromFile <T>(filePath)); }
// TODO: Repository to be added at the later stage #region Public Methods public bool Login(Login criteria) { if (string.IsNullOrEmpty(_yamlFileOptions.FilePath)) { return(false); } var items = YamlFileUtility.ReadYamlFile(_yamlFileOptions.FilePath, "auth"); foreach (var yamlNode in items) { var item = (YamlMappingNode)yamlNode; if (YamlHelper.ConvertYamlScalarNodeToString(item, "password") == criteria.Password && YamlHelper.ConvertYamlScalarNodeToString(item, "username") == criteria.Username) { return(true); } } return(false); }
static public void TestMethod1() { var tGoName = cPrefabName.Replace(".prefab", string.Empty); var tPrefab = GameObject.Find(tGoName); if (tPrefab == null) { throw new System.NullReferenceException("找不到" + tGoName); } var tTrans = YamlHelper.GetSpriteByIndex(tPrefab, Path.Combine(Application.dataPath, "Test/" + cPrefabName), "62adb30369acbf943a67cee0f69267a3", "Emoticon - Rambo", 5); if (tTrans != null) { Selection.activeTransform = tTrans.transform; } else { Debug.LogError("逻辑错误"); } }
public RetroMCP(string folder, string matched_version) { Folder = folder; var mcp = ParseTsrgs(matched_version); MatchedMCP = new(mcp.Client.Reversed(), mcp.Server.Reversed()); MatchedMojang = new(); using var client_file = File.OpenText(Path.Combine(Folder, "matched_client.txt")); using var server_file = File.OpenText(Path.Combine(Folder, "matched_server.txt")); MappingsIO.ParseProguard(MatchedMojang.Client, client_file); MappingsIO.ParseProguard(MatchedMojang.Server, server_file); FoundRenames = new((YamlMappingNode)YamlHelper.ParseFile(Path.Combine(folder, "mappings_found.yaml"))); CustomRenames = new((YamlMappingNode)YamlHelper.ParseFile(Path.Combine(folder, "mappings_custom.yaml"))); var found_equivs = Equivalencies.Parse((YamlMappingNode)YamlHelper.ParseFile(Path.Combine(folder, "equivalencies_custom.yaml"))); var custom_equivs = Equivalencies.Parse((YamlMappingNode)YamlHelper.ParseFile(Path.Combine(folder, "equivalencies_custom.yaml"))); var client_equivs = new Equivalencies(found_equivs.Client, custom_equivs.Client); var server_equivs = new Equivalencies(found_equivs.Server, custom_equivs.Server); MergedEquivalencies = new(client_equivs, server_equivs); }
public void Compile([Option("config", new[] { 'c' })][FilePathExists] string configPath) { var configs = YamlHelper.ReadFile <AppConfig[]>(configPath); foreach (var config in configs) { var includeFiles = GlobFiles(config.Includes); foreach (var target in config.CompileTargets ?? throw new NullReferenceException(nameof(config.CompileTargets))) { try { var input = target.Input ?? throw new NullReferenceException(nameof(target.Input)); var output = target.Output ?? throw new NullReferenceException(nameof(target.Output)); // 読み込み var(rootDefinition, includedDefinitions) = DefinitionLoader.Load(input, includeFiles); // 出力先フォルダが存在しない場合は作成する CreateParentDirectory(output); // 書き込み using var writer = new StreamWriter(output, false, new UTF8Encoding(false)); var codeGenerator = new CodeGenerator(rootDefinition, includedDefinitions); writer.Write(codeGenerator.Generate()); } catch (Exception e) { _logger.Error(e); var sb = new StringBuilder(); sb.AppendLine($"input: {target.Input}"); sb.AppendLine($"output: {target.Output}"); _logger.Error(sb.ToString()); throw; } } } }
public void LoadComponentAliases() { var componentFilename = $"{AddressFormattingDataDirectory}components.yaml"; var components = YamlHelper.DeserializeListFromFilePath <ComponentStructure>(componentFilename); var componentMapping = new List <KeyValuePair <string, Components> >(); foreach (var component in components) { var componentEnum = MapComponent(component.Name); componentMapping.Add(new KeyValuePair <string, Components>(component.Name, componentEnum)); if (component.Aliases?.Count > 0) { foreach (var alias in component.Aliases) { componentMapping.Add(new KeyValuePair <string, Components>(alias, componentEnum)); } } } _componentMapping = componentMapping; }
/// <summary> /// Creates from file. /// </summary> public static Config CreateFromFile(string filePath) { return(YamlHelper.DeserializeFromFile <Config>(filePath)); }
/// <summary> /// Synchronizes CODEOWNERS contacts to appropriate DevOps groups /// </summary> /// <param name="organization">Azure DevOps organization name</param> /// <param name="project">Azure DevOps project name</param> /// <param name="devOpsTokenVar">Personal Access Token environment variable name</param> /// <param name="aadAppIdVar">AAD App ID environment variable name (Kusto access)</param> /// <param name="aadAppSecretVar">AAD App Secret environment variable name (Kusto access)</param> /// <param name="aadTenantVar">AAD Tenant environment variable name (Kusto access)</param> /// <param name="kustoUrlVar">Kusto URL environment variable name</param> /// <param name="kustoDatabaseVar">Kusto DB environment variable name</param> /// <param name="kustoTableVar">Kusto Table environment variable name</param> /// <param name="pathPrefix">Azure DevOps path prefix (e.g. "\net")</param> /// <param name="dryRun">Do not persist changes</param> /// <returns></returns> public static async Task Main( string organization, string project, string devOpsTokenVar, string aadAppIdVar, string aadAppSecretVar, string aadTenantVar, string kustoUrlVar, string kustoDatabaseVar, string kustoTableVar, string pathPrefix = "", bool dryRun = false ) { #pragma warning disable CS0618 // Type or member is obsolete using (var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(config => { config.IncludeScopes = true; }); })) #pragma warning restore CS0618 // Type or member is obsolete { var devOpsService = AzureDevOpsService.CreateAzureDevOpsService( Environment.GetEnvironmentVariable(devOpsTokenVar), $"https://dev.azure.com/{organization}/", loggerFactory.CreateLogger <AzureDevOpsService>() ); var gitHubServiceLogger = loggerFactory.CreateLogger <GitHubService>(); var gitHubService = new GitHubService(gitHubServiceLogger); var githubNameResolver = new GitHubNameResolver( Environment.GetEnvironmentVariable(aadAppIdVar), Environment.GetEnvironmentVariable(aadAppSecretVar), Environment.GetEnvironmentVariable(aadTenantVar), Environment.GetEnvironmentVariable(kustoUrlVar), Environment.GetEnvironmentVariable(kustoDatabaseVar), Environment.GetEnvironmentVariable(kustoTableVar), loggerFactory.CreateLogger <GitHubNameResolver>() ); var logger = loggerFactory.CreateLogger <Program>(); var pipelineGroupTasks = (await devOpsService.GetAllTeamsAsync(project)) .Where(team => YamlHelper.Deserialize <TeamMetadata>(team.Description, swallowExceptions: true)?.Purpose == TeamPurpose.SynchronizedNotificationTeam ).Select(async team => { var pipelineId = YamlHelper.Deserialize <TeamMetadata>(team.Description).PipelineId; return(new { Pipeline = await devOpsService.GetPipelineAsync(project, pipelineId), Team = team }); }); var pipelineGroups = await Task.WhenAll(pipelineGroupTasks); var filteredGroups = pipelineGroups.Where(group => group.Pipeline != default && group.Pipeline.Path.StartsWith(pathPrefix)); foreach (var group in filteredGroups) { using (logger.BeginScope("Team Name = {0}", group.Team.Name)) { if (group.Pipeline.Process.Type != PipelineYamlProcessType) { continue; } // Get contents of CODEOWNERS logger.LogInformation("Fetching CODEOWNERS file"); var managementUrl = new Uri(group.Pipeline.Repository.Properties["manageUrl"]); var codeownersContent = await gitHubService.GetCodeownersFile(managementUrl); if (codeownersContent == default) { logger.LogInformation("CODEOWNERS file not found, skipping sync"); continue; } var process = group.Pipeline.Process as YamlProcess; // Find matching contacts for the YAML file's path var parser = new CodeOwnersParser(codeownersContent); var matchPath = PathWithoutFilename(process.YamlFilename); var searchPath = $"/{matchPath}/"; logger.LogInformation("Searching CODEOWNERS for matching path Path = {0}", searchPath); var contacts = parser.GetContactsForPath(searchPath); logger.LogInformation("Matching Contacts Path = {0}, NumContacts = {1}", searchPath, contacts.Count); // Get set of team members in the CODEOWNERS file var contactResolutionTasks = contacts .Where(contact => contact.StartsWith("@")) .Select(contact => githubNameResolver.GetInternalUserPrincipal(contact.Substring(1))); var codeownerPrincipals = await Task.WhenAll(contactResolutionTasks); var codeownersDescriptorsTasks = codeownerPrincipals .Where(userPrincipal => !string.IsNullOrEmpty(userPrincipal)) .Select(userPrincipal => devOpsService.GetDescriptorForPrincipal(userPrincipal)); var codeownersDescriptors = await Task.WhenAll(codeownersDescriptorsTasks); var codeownersSet = new HashSet <string>(codeownersDescriptors); // Get set of existing team members var teamMembers = await devOpsService.GetMembersAsync(group.Team); var teamContactTasks = teamMembers .Select(async member => await devOpsService.GetUserFromId(new Guid(member.Identity.Id))); var teamContacts = await Task.WhenAll(teamContactTasks); var teamDescriptors = teamContacts.Select(contact => contact.SubjectDescriptor.ToString()); var teamSet = new HashSet <string>(teamDescriptors); // Synchronize contacts var contactsToRemove = teamSet.Except(codeownersSet); var contactsToAdd = codeownersSet.Except(teamSet); var teamDescriptor = await devOpsService.GetDescriptorAsync(group.Team.Id); foreach (var descriptor in contactsToRemove) { logger.LogInformation("Delete Contact TeamDescriptor = {0}, ContactDescriptor = {1}", teamDescriptor, descriptor); if (!dryRun) { await devOpsService.RemoveMember(teamDescriptor, descriptor); } } foreach (var descriptor in contactsToAdd) { logger.LogInformation("Add Contact TeamDescriptor = {0}, ContactDescriptor = {1}", teamDescriptor, descriptor); if (!dryRun) { await devOpsService.AddToTeamAsync(teamDescriptor, descriptor); } } } } } }
public MapNode(ParsingContext context, OpenApiDiagnostic diagnostic, string yamlString) : this(context, diagnostic, (YamlMappingNode)YamlHelper.ParseYamlString(yamlString)) { }