/// <summary> /// Validate if the contents of the GitVersion.yml file are changed correctly. /// </summary> /// <param name="originalContents">The contents of the GitVersion.yml file from the main branch.</param> /// <param name="updatedContents">The contents of the GitVersion.yml file from the PR.</param> /// <returns>Wether the changes to the GitVersion file were valid.</returns> public static bool IsValidGitversion(string originalContents, string updatedContents) { // If the files are empty, it's not valid. if (string.IsNullOrEmpty(originalContents) || string.IsNullOrEmpty(updatedContents)) { return(false); } var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(HyphenatedNamingConvention.Instance) .IgnoreUnmatchedProperties() .Build(); // Parse both YAML files to a POCO, so we can compare content. var originalYaml = deserializer.Deserialize <GitVersion>(originalContents); var updatedYaml = deserializer.Deserialize <GitVersion>(updatedContents); // If both files have the same version, the contents aren't really updated, but rather reverted to the original state. if (originalYaml.NextVersion == updatedYaml.NextVersion) { return(false); } // Return wether the new YAML version is higher then the original. return(ParseAndValidateGitVersion(originalYaml.NextVersion, updatedYaml.NextVersion)); }
public static UpdateInfo Deserialize(string data) { var yamlDeserializer = new YamlDotNet.Serialization.DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(PascalCaseNamingConvention.Instance).Build(); UpdateInfo deserialized = yamlDeserializer.Deserialize <UpdateInfo>(data); return(deserialized); }
private static PSObject YamlHeader(string markdown) { var stream = new MarkdownStream(markdown); if (stream.EOF || stream.Line > 1 || stream.Current != Dash) { return(null); } // Check if the line is just dashes indicating start of yaml header if (!stream.PeakLine(Dash, out int count) || count < 2) { return(null); } stream.Skip(count + 1); stream.SkipLineEnding(); var yaml = stream.CaptureUntil(TripleDash, onNewLine: true).Trim(); var d = new YamlDotNet.Serialization.DeserializerBuilder() .IgnoreUnmatchedProperties() .WithTypeConverter(new PSObjectYamlTypeConverter()) .WithNodeTypeResolver(new PSObjectYamlTypeResolver()) .Build(); return(d.Deserialize <PSObject>(yaml)); }
public static void Test() { // SchemaPorter.YamlSpace.RootNode retVal = null; // SchemaPorter.foofoo.RootNode retVal = null; SchemaPorter.SimpleYamlSchema.RootObject retVal = null; YamlDotNet.Serialization.IDeserializer deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) //.IgnoreUnmatchedProperties() .Build(); using (System.IO.Stream fs = System.IO.File.OpenRead(@"d:\username\Documents\Visual Studio 2017\Projects\BlueMine\BlueMine\Code\de.yml")) { //using (System.IO.TextReader r = new System.IO.StringReader(@"")) using (System.IO.TextReader r = new System.IO.StreamReader(fs, System.Text.Encoding.UTF8)) { // retVal = deserializer.Deserialize<SchemaPorter.YamlSpace.RootNode>(r); // retVal = deserializer.Deserialize<SchemaPorter.foofoo.RootNode>(r); retVal = deserializer.Deserialize <SchemaPorter.SimpleYamlSchema.RootObject>(r); } // End using r } // End Using fs System.Console.WriteLine(retVal); } // End Sub Test
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 T FromYaml <T>(this string target) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) .Build(); return(deserializer.Deserialize <T>(target)); }
private static T LoadFromString <T>(string content) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) .Build(); var obj = deserializer.Deserialize <T>(content); return(obj); }
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 void ReadSimpleTypesFromYamlParser() { // The .NET SDK allows flag data to be read from a YAML file by first running it through a YAML // parser, which produces types like Dictionary, and then feeding that into JReader. So we'll // verify that a basic use case like that works, using YamlDotNet. var yamlContent = @" --- flags: flag1: key: flag1 ""on"": true version: 1 fallthrough: variation: 2 variations: - fall - ""off"" - ""on"" flagValues: flag2: value2 segments: seg1: key: seg1 version: 1 include: [""user1""] "; var yaml = new YamlDotNet.Serialization.DeserializerBuilder().Build(); var dataIn = yaml.Deserialize <object>(yamlContent); var r = JReader.FromAdapter(ReaderAdapters.FromSimpleTypes(dataIn)); var dataOut = JsonStreamConvert.ConvertSimpleTypes.ReadJson(ref r); var jsonOut = JsonStreamConvert.SerializeObject(dataOut, JsonStreamConvert.ConvertSimpleTypes); var expectedJson = @"{ ""flags"": { ""flag1"": { ""key"": ""flag1"", ""on"": ""true"", ""version"": ""1"", ""fallthrough"": { ""variation"": ""2"" }, ""variations"": [ ""fall"", ""off"", ""on"" ] } }, ""flagValues"": { ""flag2"": ""value2"" }, ""segments"": { ""seg1"": { ""key"": ""seg1"", ""version"": ""1"", ""include"": [""user1""] } } }"; // Note that YamlDotNet parses all the booleans and numbers as strings; that's why we provide a // type coercion option. TestUtil.AssertJsonEqual(expectedJson, jsonOut); }
public static YamlConfig Parse(string filepath) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); using (Stream stream = File.OpenRead(filepath)) { using (TextReader reader = new StreamReader(stream)) { var preparsedConfig = deserializer.Deserialize <YamlConfig>(reader); return(preparsedConfig); } } }
private static int MergeToc(string mkdocsPath, string newTocPath) { var mkdocs = new YamlStream(); using (var reader = new StreamReader(mkdocsPath)) { mkdocs.Load(reader); } Toc toc = null; using (var reader = new StreamReader(newTocPath)) { // Examine the new toc var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); toc = deserializer.Deserialize <Toc>(reader); } // the mkdocs format is not ammenable to object serialization unfortunately... var root = (YamlMappingNode)mkdocs.Documents[0].RootNode; // Examine the stream var items = (YamlSequenceNode)root.Children[new YamlScalarNode("nav")]; var apitoc = items.Where(it => it is YamlMappingNode ym && ym.Children.Count > 0 && ym.Children[0].Key is YamlScalarNode s && s.Value == "API documentation").FirstOrDefault() as YamlMappingNode; if (apitoc == null) { apitoc = new YamlMappingNode(); items.Add(apitoc); } apitoc.Children.Clear(); var s = new YamlSequenceNode(); apitoc.Add(new YamlScalarNode("API documentation"), s); int count = AddLinks(s, toc.toc); // save the updated mkdocs using (var writer = new StreamWriter(mkdocsPath)) { mkdocs.Save(writer, false); } Console.WriteLine("Added {0} api documentation links to the nav: section in {1}", count, mkdocsPath); return(0); }
private static void ConfigMain(ConfigOptions options) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithTagMapping("!whitelist", typeof(Config.WhitelistFilter)) .WithTagMapping("!blacklist", typeof(Config.BlacklistFilter)) .WithTypeConverter(new Config.YamlTypeConverter()) .Build(); var cfg = deserializer.Deserialize <Config>(File.ReadAllText(options.ConfigFile)); cfg.ApplyDefault(); if (options.Debug) { Console.WriteLine("{0}", ObjectDumper.Dump(cfg)); } RealMain(cfg, options.Verbose); }
private static void Main(string[] _) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); cfg = deserializer.Deserialize <Config>(input: System.IO.File.ReadAllText("config.yaml")); db = new DB(cfg.Database); botClient = new TelegramBotClient(token: cfg.TelegramToken); var me = botClient.GetMeAsync().Result; botname = me.Username; Console.WriteLine($"UserID {me.Id} NAME: {me.Username}."); cfg.Admins = botClient.GetChatAdministratorsAsync(cfg.MainChatId).Result.Select(x => x.User.Id); botClient.StartReceiving(allowedUpdates: new UpdateType[] { UpdateType.Message, UpdateType.CallbackQuery }); botClient.OnMessage += BotClient_OnMessage; botClient.OnCallbackQuery += BotClient_OnCallbackQuery; while (true) { Thread.Sleep(millisecondsTimeout: int.MaxValue); } }
public List <Config> DeserializeConfigFile(string configFile) { var fileInfo = new FileInfo(configFile); var isYaml = fileInfo.Extension.EndsWith("yaml", StringComparison.OrdinalIgnoreCase) || fileInfo.Extension.EndsWith("yml", StringComparison.OrdinalIgnoreCase); var configs = new List <Config>(); var text = File.ReadAllText(fileInfo.FullName); if (isYaml) { var s = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); configs = s.Deserialize <List <Config> >(text); } else { configs = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Config> >(text); } return(configs); }
public SERIALIZER_TYPE Deserialize(string FilePath, bool ShowError = true) { if (!(File.Exists(FilePath))) { if (ShowError) { throw new FileNotFoundException(); } else { return(new SERIALIZER_TYPE()); } } SERIALIZER_TYPE DESERIALIZED_OBJECT = new SERIALIZER_TYPE(); YamlDotNet.Serialization.IDeserializer DESERIALIZER = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); using (StringReader YAML_STREAM = new StringReader(FilePath)) { DESERIALIZED_OBJECT = DESERIALIZER.Deserialize <SERIALIZER_TYPE>(YAML_STREAM); } return(DESERIALIZED_OBJECT); }
protected int OnExecute(CommandLineApplication app) { try { var yamlReader = new YamlDotNet.Serialization.DeserializerBuilder() .IgnoreUnmatchedProperties() .Build(); MapBuilder builder; MapGenConfig config; string baseDir; string outMapFile; if (FileExtUtil.IsExtension(InputFile, ".yml")) { var ymlFile = Path.GetFullPath(InputFile); baseDir = Path.GetDirectoryName(ymlFile); logger.Debug($"ymlFile is \"{ymlFile}\""); logger.Debug($"baseDir is \"{baseDir}\""); config = yamlReader.Deserialize <MapGenConfig>(File.ReadAllText(ymlFile)); var modelFile = Path.Combine(baseDir, config.inputFile); outMapFile = Path.GetFullPath(OutputMap ?? Path.Combine(baseDir, config.outputFile)); builder = new MapBuilder(modelFile, config, CreateImageLoader(baseDir, config, FileLoader)); } else { var modelFile = Path.GetFullPath(InputFile); baseDir = Path.GetDirectoryName(modelFile); var ymlFile = Path.Combine(baseDir, "mapdef.yml"); outMapFile = Path.GetFullPath(OutputMap ?? Path.Combine(baseDir, Path.ChangeExtension(InputFile, ".map"))); logger.Debug($"ymlFile is \"{ymlFile}\""); logger.Debug($"baseDir is \"{baseDir}\""); config = File.Exists(ymlFile) ? yamlReader.Deserialize <MapGenConfig>(File.ReadAllText(ymlFile)) : new MapGenConfig(); builder = new MapBuilder(modelFile, config, CreateImageLoader(baseDir, config, FileLoader)); } logger.Debug("Building map file structure."); var buff = new MemoryStream(); void trySaveTo(string toFile, MemoryStream stream) { if (!string.IsNullOrWhiteSpace(toFile)) { toFile = Path.Combine(baseDir, toFile); logger.Debug($"Writing raw data to \"{toFile}\"."); Directory.CreateDirectory(Path.GetDirectoryName(toFile)); File.WriteAllBytes(toFile, stream.ToArray()); } } Bar.Write( buff, builder.GetBarEntries(trySaveTo) .Concat(LoadAdditionalBarEntries(config, CreateRawFileLoader(baseDir))) .ToArray() ); logger.Debug($"Writing to \"{outMapFile}\"."); File.WriteAllBytes(outMapFile, buff.ToArray()); logger.Debug("Done"); return(0); } finally { LogManager.Shutdown(); } }
static Hash OpenYaml(string file) { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); return(deserializer.Deserialize <Hash>(File.OpenText(file))); }
public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { var dictionary = args.ToDictionary(Configuration, PrependLinkRoot); var prependLinkRoot = dictionary.GetBool(PrependLinkRoot); var configuration = dictionary.GetString(Configuration, "advanced"); var contentBuilder = new StringBuilder(); var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention()) .Build(); var tabGroup = deserializer.Deserialize <TabGroup>(content); contentBuilder.AppendLine("<div class=\"tab-wrap\">"); var first = true; foreach (var tab in tabGroup.Tabs) { contentBuilder.AppendLine($"<input type=\"radio\" id=\"{tabGroup.Id}-{tab.Id}\" name=\"{tabGroup.Id}\" class=\"tab\" {(first ? "checked" : string.Empty)}><label for=\"{tabGroup.Id}-{tab.Id}\" >{tab.Name}</label>"); first = false; } foreach (var tab in tabGroup.Tabs) { contentBuilder.AppendLine("<div class=\"tab__content\">"); contentBuilder.AppendLine(); using (var writer = new StringWriter()) { if (!string.IsNullOrWhiteSpace(tab.Content)) { MarkdownHelper.RenderMarkdown( context, document, tab.Content, writer, prependLinkRoot, configuration, null ); } document.RenderExternalDocument( context, writer, prependLinkRoot, configuration, isCodeBlock: false, filePath: tab.Include ); document.RenderExternalDocument( context, writer, prependLinkRoot, configuration, overrideCodeLang: tab.CodeLang, isCodeBlock: true, filePath: tab.Code ); contentBuilder.AppendLine(writer.ToString()); } contentBuilder.AppendLine(); contentBuilder.AppendLine("</div>"); } contentBuilder.AppendLine("</div>"); return(new ShortcodeResult( contentBuilder.ToString() )); }
protected override async Task <StageResultList <Stream, string, TransformStageCache <TInCache> > > DoInternal([AllowNull] TransformStageCache <TInCache>?cache, OptionToken options) { var input = await this.input(cache?.ParentCache, options).ConfigureAwait(false); var task = LazyTask.Create(async() => { var inputList = await input.Perform; var sidecarLookup = inputList.result.Where(x => Path.GetExtension(x.Id) == this.SidecarExtension) .ToDictionary(x => Path.Combine(Path.GetDirectoryName(x.Id) ?? string.Empty, Path.GetFileNameWithoutExtension(x.Id))); var files = inputList.result.Where(x => Path.GetExtension(x.Id) != this.SidecarExtension); var list = await Task.WhenAll(files.Select(async file => { if (sidecarLookup.TryGetValue(file.Id, out var sidecar) && (file.HasChanges || sidecar.HasChanges)) { var(fileResult, fileCache) = await file.Perform; var(sidecarResult, sidecarCache) = await sidecar.Perform; var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .WithNamingConvention(YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention.Instance) .Build(); var oldMetadata = fileResult.Metadata; MetadataContainer?newMetadata; try { using var stream = sidecarResult.Value; using var reader = new StreamReader(stream); var metadata = deserializer.Deserialize <TMetadata>(reader); if (metadata != null) { if (this.update != null) { newMetadata = oldMetadata.AddOrUpdate(metadata.GetType(), metadata, (oldValue, newValue) => this.update((TMetadata)oldValue !/*AllowNull is set, so why the warnign?*/, (TMetadata)newValue)); } else { newMetadata = oldMetadata.Add(metadata.GetType(), metadata); } } else { newMetadata = null; } } catch (YamlDotNet.Core.YamlException e) when(e.InnerException is null) // Hope that only happens when it does not match. { newMetadata = null; } if (newMetadata != null) { fileResult = fileResult.With(newMetadata); } var hasChanges = true; if (cache != null && cache.Transformed.TryGetValue(fileResult.Id, out var oldHash)) { hasChanges = oldHash != fileResult.Hash; } return(result: StageResult.Create <Stream, string>(fileResult, fileResult.Hash, hasChanges, fileResult.Id), inputId: file.Id, outputHash: fileResult.Hash); } else if (file.HasChanges) { var(fileResult, fileCache) = await file.Perform; var hasChanges = true; if (cache != null && cache.Transformed.TryGetValue(fileResult.Id, out var oldHash)) { hasChanges = oldHash != fileResult.Hash; } System.Diagnostics.Debug.Assert(hasChanges); // if the original file had changes so must this have. return(result: StageResult.Create <Stream, string>(fileResult, fileResult.Hash, hasChanges, fileResult.Id), inputId: file.Id, outputHash: fileResult.Hash); } else { if (cache == null || !cache.InputToOutputId.TryGetValue(file.Id, out var oldOutputId) || !cache.Transformed.TryGetValue(file.Id, out var oldOutputHash)) { throw this.Context.Exception("No changes, so old value should be there."); } var task = LazyTask.Create(async() => { var(fileResult, fileCache) = await file.Perform; return(fileResult, fileResult.Hash); }); return(result: StageResult.Create(task, false, oldOutputId), inputId: file.Id, outputHash: oldOutputHash); } })).ConfigureAwait(false); var newCache = new TransformStageCache <TInCache>() { InputToOutputId = list.ToDictionary(x => x.inputId, x => x.result.Id), OutputIdOrder = list.Select(x => x.result.Id).ToArray(), ParentCache = inputList.cache, Transformed = list.ToDictionary(x => x.result.Id, x => x.outputHash) }; return(result: list.Select(x => x.result).ToImmutableList(), cache: newCache); }); bool hasChanges = input.HasChanges; var newCache = cache; if (input.HasChanges || newCache == null) { var(list, c) = await task; newCache = c; if (!hasChanges && list.Count != cache?.OutputIdOrder.Length) { hasChanges = true; } if (!hasChanges && cache != null) { for (int i = 0; i < cache.OutputIdOrder.Length && !hasChanges; i++) { if (list[i].Id != cache.OutputIdOrder[i]) { hasChanges = true; } if (list[i].HasChanges) { hasChanges = true; } } } } return(StageResultList.Create(task, hasChanges, newCache.OutputIdOrder.ToImmutableList())); }
private CodeGenResult GenerateCodeCore(String inputFilePath, String inputFileContent, String fileNamespace) { String fileName, workingDirectory, baseName; try { var fileInfo = new FileInfo(inputFilePath); fileName = fileInfo.Name; // Base name is commonly used to generate the class name baseName = fileName; while (baseName.Contains(".")) { baseName = Path.GetFileNameWithoutExtension(baseName); } workingDirectory = fileInfo.Directory.FullName; } catch (Exception exc) { var message = $"// Unable to access input file: {inputFilePath}"; return(new CodeGenResult(message)); } String metaPath, metaContents; try { (metaPath, metaContents) = metaFileNameCandidates .Select(name => Path.Combine(workingDirectory, name)) .Where(path => File.Exists(path)) .Select(path => (path, File.ReadAllText(path))) .FirstOrDefault(); } catch (Exception exc) { var message = $"// Unable to access \"{metaFileNameCandidates.First()}\" in same directory as input: {inputFilePath}"; return(new CodeGenResult(message)); } Yaml.Spec spec; if (metaContents == null) { spec = null; } else { var deserializer = new YamlDotNet.Serialization.DeserializerBuilder() .Build(); try { spec = deserializer.Deserialize <Yaml.Spec>(metaContents); } catch (YamlDotNet.Core.YamlException yamlException) { var start = yamlException.Start; String message = $"Unable to parse YAML from {metaPath}\nLine: {start.Line}, Column: {start.Column}\n{yamlException.Message}"; this.GeneratorErrorCallback(false, 0, message, start.Line, start.Column); return(new CodeGenResult($"// {message}")); } } String toolName; Boolean isGlobalTool; if (spec != null && spec.Files.FirstOrDefault(i => i.FileName == fileName) is Yaml.File file) { toolName = file.Tool; isGlobalTool = false; // Set file extension from config if (!(file.Extension is String fileExtension)) { fileExtension = ".cs"; // Most code is C#, right? :-D } else if (!fileExtensionRegex.IsMatch(fileExtension)) { return(new CodeGenResult($"// Invalid extension: {fileExtension}")); } else if (!fileExtension.StartsWith(".")) { fileExtension = "." + fileExtension; } this.fileExtension = fileExtension; }