private string GetDesignSettingsFilePath() { var directoryPath = System.IO.Path.Combine( System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Settings" ); var filePath = System.IO.Path.Combine( directoryPath, "DesignSettings.yaml" ); System.IO.Directory.CreateDirectory(directoryPath); if (!System.IO.File.Exists(filePath)) { var serializer = new YamlDotNet.Serialization.SerializerBuilder().Build(); var yamlString = serializer.Serialize(new DesignSettingsYamlObject()); using (var stream = new StreamWriter(filePath, false, Encoding.UTF8)) { stream.Write(yamlString); } } return(filePath); }
public void YAML出力Test() { var keybindings = new キーバインディング(); var sr = new YamlDotNet.Serialization.SerializerBuilder() .WithTypeInspector(inner => new FDK.シリアライズ.YAML.CommentGatheringTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new FDK.シリアライズ.YAML.CommentsObjectGraphVisitor(args.InnerVisitor)) .Build(); var yaml = sr.Serialize(keybindings.キーボードtoドラム); var 正答 = @"0,16: LeftCrash 0,28: LeftCrash 0,30: HiHat_Open 0,44: HiHat_Close 0,31: HiHat_Foot 0,45: Snare 0,46: Bass 0,57: Bass 0,47: Tom1 0,48: Tom2 0,49: Tom3 0,50: RightCrash 0,37: Ride "; Assert.AreEqual(正答, yaml); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //var yamlStream = new YamlStream(); using (var reader = new StreamReader(request.Body)) { string s = await reader.ReadToEndAsync(); // yamlStream.Load(reader); var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); var obj = deserializer.Deserialize <object>(s); var serializer = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build(); return(new HttpResponseMessage { Content = new PushStreamContent((stream, content, context) => { using (var writer = new StreamWriter(stream)) serializer.Serialize(writer, obj); }), }); } //return name != null // ? (ActionResult)new OkObjectResult($"Hello, {name}") // : new BadRequestObjectResult("Please pass a name on the query string or in the request body"); }
public static string ToYaml <T>(this T target) { var serializer = new YamlDotNet.Serialization.SerializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) .Build(); return(serializer.Serialize(target)); }
private string ReadConfigYamlToJson(string path) { var yamlReader = new StringReader(File.ReadAllText(path)); var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); var yamlObject = deserializer.Deserialize(yamlReader); var serializer = new YamlDotNet.Serialization.SerializerBuilder() .JsonCompatible() .Build(); return(serializer.Serialize(yamlObject)); }
public static void ExportDocument(string fileName, string mimeType, object data) { StreamWriter writer = new StreamWriter(fileName); writer.WriteLine("### YamlMime:" + mimeType); YamlDotNet.Serialization.SerializerBuilder builder = new YamlDotNet.Serialization.SerializerBuilder(); YamlDotNet.Serialization.Serializer s = builder.Build(); s.Serialize(writer, data); writer.Close(); writer.Dispose(); }
/// <summary> /// 設定ファイルを保存します。 /// </summary> /// <param name="config">設定データ</param> private static void StoreConfig(Config config) { using (var fs = File.Open(ConfigPath, FileMode.Create)) { using (var writer = new StreamWriter(fs)) { var serializer = new YamlDotNet.Serialization.SerializerBuilder().Build(); serializer.Serialize(writer, config); } } }
public static string TestSerialize(object value) { System.Console.WriteLine(typeof(YamlDotNet.Serialization.SerializerBuilder).AssemblyQualifiedName); YamlDotNet.Serialization.ISerializer serializer = new YamlDotNet.Serialization.SerializerBuilder() .Build(); // Note: Must be properties - doesn't work with public fields... string yaml = serializer.Serialize(value); return(yaml); }
public static string ToYaml(this object value) { var serializer = new YamlDotNet.Serialization.SerializerBuilder() .EmitDefaults() .Build(); using (TextWriter writer = new StringWriter()) { serializer.Serialize(writer, value); return(writer.ToString()); } }
public void Save(string path) { var yamlBuilder = new YamlDotNet.Serialization.SerializerBuilder(); yamlBuilder.EmitDefaults(); foreach (var type in _GetMappingTypes()) { yamlBuilder.WithTagMapping("!" + type.Name, type); } File.WriteAllText(path, yamlBuilder.Build().Serialize(this)); }
private void SerializeAsYaml(DiagramElements diagramElementsObj) { var serializer = new YamlDotNet.Serialization.SerializerBuilder() .WithEmissionPhaseObjectGraphVisitor(args => new YamlIEnumerableSkipEmptyObjectGraphVisitor(args.InnerVisitor)) .Build(); using (var writer = new StringWriter()) { serializer.Serialize(writer, diagramElementsObj); yamlData = writer.ToString(); outputYamlString = yamlData.Replace("'", string.Empty); } }
public void Serialize(SERIALIZER_TYPE DATA, string FilePath) { if (File.Exists(FilePath)) { File.Delete(FilePath); } YamlDotNet.Serialization.ISerializer SERIALIZER = new YamlDotNet.Serialization.SerializerBuilder() .Build(); using (StreamWriter YAML_STREAM = new StreamWriter(FilePath)) { SERIALIZER.Serialize(YAML_STREAM, (SERIALIZER_TYPE)DATA); } }
public void 保存する() { using (Log.Block(FDKUtilities.現在のメソッド名)) { var serializer = new YamlDotNet.Serialization.SerializerBuilder() .WithTypeInspector(inner => new FDK.シリアライズ.YAML.CommentGatheringTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new FDK.シリアライズ.YAML.CommentsObjectGraphVisitor(args.InnerVisitor)) .Build(); var yaml = serializer.Serialize(this); File.WriteAllText(システム設定ファイルパス.数なしパス, yaml); Log.Info($"システム設定 を保存しました。[{システム設定ファイルパス.変数付きパス}]"); } }
public void 保存する(VariablePath path) { using var _ = new LogBlock(Log.現在のメソッド名); var serializer = new YamlDotNet.Serialization.SerializerBuilder() .WithTypeInspector(inner => new CommentGatheringTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new CommentsObjectGraphVisitor(args.InnerVisitor)) .Build(); // ※ 値が既定値であるプロパティは出力されないので注意。 var yaml = serializer.Serialize(this); File.WriteAllText(path.数なしパス, yaml); Log.Info($"システム設定を保存しました。[{path.変数付きパス}]"); }
// Use only in editor mode public static void SaveScripts(string name, ScriptTree tree) { var rootText = Resources.Load <TextAsset>("meta/root"); var docStream = new StringReader(rootText.text); RootGraph root = RootGraph.Construct(docStream); var scriptGraph = root.Scriptgraphs.Find(sg => sg.Name == name); string fullPath = path + scriptGraph.Path + ".yaml"; var sr = new YamlDotNet.Serialization.SerializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) .Build(); using (FileStream fs = new FileStream(fullPath, FileMode.Create)) { using (StreamWriter writer = new StreamWriter(fs)) { writer.Write(sr.Serialize(tree)); } } UnityEditor.AssetDatabase.Refresh(); }
private static void Main(string[] args) { var serializer = new YamlDotNet.Serialization.SerializerBuilder().Build(); var str = serializer.Serialize(new Test() { fffff = "ddddddddddd", aaa = new vector3 { x = 1, y = 6, z = 8 }, vector = new vector[] { new vector { x = 1, y = 6, z = 8 }, new vector { x = 1, y = 6, z = 8 }, new vector { x = 1, y = 6, z = 8 } }, }); Console.WriteLine(str); }
public static async Task <string> GenerateMethodMapJsonAsync( string profileName, string stackName) { if (string.IsNullOrEmpty(profileName)) { throw new Exception($"Error: No ProfileName provided"); } if (string.IsNullOrEmpty(stackName)) { throw new Exception($"Error: No StackName provided"); } var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us CredentialProfile profile = null; if (!sharedCredentialsFile.TryGetProfile(profileName, out profile)) { throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store."); } AWSCredentials creds = null; if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds)) { throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\"."); } var awsSettings = new AwsSettings(); if (!awsSettings.ContainsKey("StackName")) { awsSettings.Add("StackName", stackName); } else { awsSettings["StackName"] = stackName; } // Get Original Template var cfClient = new AmazonCloudFormationClient(creds); var getTemplateRequestOriginal = new GetTemplateRequest() { StackName = stackName, TemplateStage = Amazon.CloudFormation.TemplateStage.Original }; var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult(); //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original"); var templateBody = templateReponse.TemplateBody; // Original is in yaml form //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody)); var tmplYaml = new StringReader(templateBody); var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml); templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj); var jTemplateObjOriginal = JObject.Parse(templateBody); // Get all Stack Resources string nextToken = null; bool foundResources = false; var methodMap = new Dictionary <string, string>(); do { var listStackResourcesRequest = new ListStackResourcesRequest() { StackName = stackName, NextToken = nextToken }; var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest); nextToken = listStackResourcesResponse.NextToken; foreach (var resource in listStackResourcesResponse.StackResourceSummaries) { switch (resource.ResourceType) { case "AWS::Lambda::Function": foundResources = true; var funcName = resource.LogicalResourceId; var lambdaEvents = jTemplateObjOriginal["Resources"][funcName]["Properties"]["Events"].Children(); foreach (JToken le in lambdaEvents) { var jObject = new JObject(le); var name = jObject.First.First.Path; var type = jObject[name]["Type"].ToString(); var apiId = string.Empty; if (type.Equals("HttpApi")) { apiId = jObject[name]["Properties"]["ApiId"]["Ref"].ToString(); } else if (type.Equals("Api")) { apiId = jObject[name]["Properties"]["RestApiId"]["Ref"].ToString(); } if (!string.IsNullOrEmpty(apiId)) { methodMap.Add(name + "Async", apiId); } } break; } } } while (nextToken != null); if (!foundResources) { throw new Exception($"Error: No Lambda resources found for specified stack."); } var result = $"{{\"MethodMap\": {Newtonsoft.Json.JsonConvert.SerializeObject(methodMap, Newtonsoft.Json.Formatting.Indented)}}}"; return(result); }
public string Serialize() { YamlDotNet.Serialization.ISerializer yamlSerializer = new YamlDotNet.Serialization.SerializerBuilder().WithNamingConvention(PascalCaseNamingConvention.Instance).Build(); return(yamlSerializer.Serialize(this)); }
public static async Task <AwsSettings> GetAwsSettings(string profileName, string stackName) { if (string.IsNullOrEmpty(profileName)) { throw new Exception($"Error: No ProfileName provided"); } if (string.IsNullOrEmpty(stackName)) { throw new Exception($"Error: No StackName provided"); } var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us CredentialProfile profile = null; if (!sharedCredentialsFile.TryGetProfile(profileName, out profile)) { throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store."); } AWSCredentials creds = null; if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds)) { throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\"."); } var awsSettings = new AwsSettings(); awsSettings["StackName"] = stackName; // Get Original Template AmazonCloudFormationClient cfClient = null; GetTemplateRequest getTemplateRequestOriginal = null; try { // Note the need to extract region from the profile! cfClient = new AmazonCloudFormationClient(creds, profile.Region); getTemplateRequestOriginal = new GetTemplateRequest() { StackName = stackName, TemplateStage = Amazon.CloudFormation.TemplateStage.Original }; } catch (Exception ex) { throw new Exception($"Could not create AmazonCloudFormationClient"); } var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult(); //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original"); var templateBody = templateReponse.TemplateBody; // Original is in yaml form //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody)); var tmplYaml = new StringReader(templateBody); var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml); templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj); var jTemplateObjOriginal = JObject.Parse(templateBody); // Get Processed Template var getTemplateRequestProcessed = new GetTemplateRequest() { StackName = stackName, TemplateStage = Amazon.CloudFormation.TemplateStage.Processed }; templateReponse = cfClient.GetTemplateAsync(getTemplateRequestProcessed).GetAwaiter().GetResult(); //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original"); templateBody = templateReponse.TemplateBody; var jTemplateObjProcessed = JObject.Parse(templateBody); // Get Stack Resources - note: this call only returns the first 100 resources. // We are calling it to get the StackId var describeStackResourcesRequest = new DescribeStackResourcesRequest() { StackName = stackName }; var describeStackResourcesResponse = await cfClient.DescribeStackResourcesAsync(describeStackResourcesRequest); if (describeStackResourcesResponse.StackResources.Count == 0) { throw new Exception($"Error: No resources found for specified stack."); } // Extract region from StackId ARN -- "arn:aws:cloudformation:us-east-1:..." var stackIdParts = describeStackResourcesResponse.StackResources[0].StackId.Split(':'); var region = stackIdParts[3]; awsSettings["Region"] = region; // Get all stack resources - paginated // The the ListStackResourcesResponse does not contain the StackId. string nextToken = null; string apiName = null; int resourceCount = 0; var apiGateways = new Dictionary <string, AwsSettings.Api>(); awsSettings["ApiGateways"] = apiGateways; do { var listStackResourcesRequest = new ListStackResourcesRequest() { StackName = stackName, NextToken = nextToken }; var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest); nextToken = listStackResourcesResponse.NextToken; foreach (var resource in listStackResourcesResponse.StackResourceSummaries) { resourceCount++; switch (resource.ResourceType) { case "AWS::Cognito::UserPool": case "AWS::Cognito::IdentityPool": case "AWS::Cognito::UserPoolClient": awsSettings[resource.LogicalResourceId] = resource.PhysicalResourceId; break; case "AWS::ApiGatewayV2::Api": var httpApi = new AwsSettings.Api(); apiGateways.Add(resource.LogicalResourceId, httpApi); httpApi.Id = resource.PhysicalResourceId; httpApi.Type = "HttpApi"; apiName = resource.LogicalResourceId; try { var HttpApiSecureAuthType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["components"]["securitySchemes"]["OpenIdAuthorizer"]["type"]; if (HttpApiSecureAuthType.Equals("oauth2")) { httpApi.SecurityLevel = AwsSettings.SecurityLevel.JWT; } else { httpApi.SecurityLevel = AwsSettings.SecurityLevel.None; } } catch { httpApi.SecurityLevel = AwsSettings.SecurityLevel.None; } httpApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"]; break; case "AWS::ApiGateway::RestApi": var restApi = new AwsSettings.Api(); apiGateways.Add(resource.LogicalResourceId, restApi); restApi.Id = resource.PhysicalResourceId; restApi.Type = "Api"; apiName = resource.LogicalResourceId; try { var apiAuthSecurityType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["securityDefinitions"]["AWS_IAM"]["x-amazon-apigateway-authtype"]; if (apiAuthSecurityType.Equals("awsSigv4")) { restApi.SecurityLevel = AwsSettings.SecurityLevel.AwsSignatureVersion4; } else { restApi.SecurityLevel = AwsSettings.SecurityLevel.None; } } catch { restApi.SecurityLevel = AwsSettings.SecurityLevel.None; } restApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"]; break; } } } while (nextToken != null); if (resourceCount == 0) { throw new Exception($"Error: No resources found for specified stack."); } return(awsSettings); }