void OLDdScriptCommand(CommandDetails command)
 {
     string outp = scriptcommand_base(command);
     if (outp == null)
     {
         return;
     }
     Chat(command.Channel.Name, command.Pinger + ColorGeneral + "Scanning " + ColorHighlightMajor + (Utilities.CountChar(outp, '\n') + 1) + ColorGeneral + " lines...");
     try
     {
         YamlStream ys = new YamlStream();
         ys.Load(new StringReader(outp));
         int nodes = 0;
         for (int i = 0; i < ys.Documents.Count; i++)
         {
             nodes += ys.Documents[i].AllNodes.ToArray().Length;
         }
     }
     catch (Exception ex)
     {
         Chat(command.Channel.Name, ColorGeneral + "Error in your YAML: " + ColorHighlightMajor + ex.Message);
     }
     List<string> warnings = dsCheck(outp);
     Chat(command.Channel.Name, ColorGeneral + "Found " + ColorHighlightMajor + warnings.Count + ColorGeneral + " potential issues.");
     for (int i = 0; i < warnings.Count && i < 8; i++)
     {
         Chat(command.Channel.Name, ColorHighlightMinor + "- " + i + ") " + warnings[i]);
     }
 }
    void YamlDotNetYamlRead()
    {
        //textAsset
        string fileName=AssetDatabase.GetAssetPath(textAsset);
        // open
        var input = new StreamReader(fileName, Encoding.UTF8);
        var yaml = new YamlStream();
        yaml.Load(input);
        //var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
        Debug.Log("yaml.Documents.Count="+ yaml.Documents.Count);
        //foreach (YamlMappingNode item in (YamlMappingNode)yaml.Documents) {
        for(int i = 0; i < yaml.Documents.Count; i++){

            string str="";
            //str="(YamlMappingNode)yaml.Documents["+i+"].RootNode= ";
            str=str+(YamlMappingNode)yaml.Documents[i].RootNode+"\n";//Macの場合 optionキーを押しながら¥を押す
            Debug.Log(str);
            //for(int j = 0; j < yaml.Documents[i].AllNodes.Count(); j++){
                //string str1="";
                //str="(YamlMappingNode)yaml.Documents["+i+"].RootNode= ";
            //	str1=str1+(YamlDotNet.RepresentationModel.YamlNode)yaml.Documents[i].AllNodes[j]+"\n";//Macの場合 optionキーを押しながら¥を押す
            //}
            foreach (YamlDotNet.RepresentationModel.YamlNode yamlNode in yaml.Documents[i].AllNodes) {
                Debug.Log(yamlNode.ToString());
            }
            //foreach (var child in item) {
            //	Debug.Log(((YamlScalarNode)child.Key).Value + "\t" +
            //		((YamlScalarNode)child.Value).Value);
            //}

        }
        TextWriter textWriter = new StreamWriter(Application.dataPath + "/YamlDotNetForUnityYAML/Editor/YamlDotNetYamlReadAndSave_yaml.yaml");
        textWriter.WriteLine("%YAML 1.1");//無視される。
        textWriter.WriteLine("%TAG !u! tag:unity3d.com,2011:");//無視される。
        yaml.Save(textWriter);

        textWriter.Close();
        AssetDatabase.Refresh();
        //var Year = (YamlScalarNode)mapping.Children[new YamlScalarNode("Year")];
        //Debug.Log("Year "+ Year.Value);
        //var Description = (YamlScalarNode)mapping.Children[new YamlScalarNode("Description")];
        //Debug.Log("Desciption "+ Description.Value);
        //Debug.Log("Contents:");

        //var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("Contents")];
        //foreach (YamlMappingNode item in items) {
        //	foreach (var child in item) {
        //		Debug.Log(((YamlScalarNode)child.Key).Value + "\t" +
        //			((YamlScalarNode)child.Value).Value);
        //	}
        //}
    }
    void Start () {
        var input = new StringReader(Document);

        var yaml = new YamlStream();
        yaml.Load(input);

        // Examine the stream
        var mapping =
            (YamlMappingNode)yaml.Documents[0].RootNode;

        var output = new StringBuilder();
        foreach (var entry in mapping.Children)
        {
            output.AppendLine(((YamlScalarNode)entry.Key).Value);
        }

        var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("items")];
        foreach (YamlMappingNode item in items)
        {
            output.AppendLine(
                String.Format("{0}\t{1}",
                    item.Children[new YamlScalarNode("part_no")],
                    item.Children[new YamlScalarNode("descrip")]
                )
            );
        }
        Debug.Log(output);
    }
Esempio n. 4
0
File: Yaml.cs Progetto: ibebbs/Wyam
 public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
 {
     return inputs
         .AsParallel()
         .SelectMany(input =>
         {
             List<Dictionary<string, object>> documentMetadata = new List<Dictionary<string, object>>();
             using (TextReader contentReader = new StringReader(input.Content))
             {
                 YamlStream yamlStream = new YamlStream();
                 yamlStream.Load(contentReader);
                 foreach (YamlDocument document in yamlStream.Documents)
                 {
                     // If this is a sequence, get a document for each item
                     YamlSequenceNode rootSequence = document.RootNode as YamlSequenceNode;
                     if (rootSequence != null)
                     {
                         documentMetadata.AddRange(rootSequence.Children.Select(GetDocumentMetadata));
                     }
                     else
                     {
                         // Otherwise, just get a single set of metadata
                         documentMetadata.Add(GetDocumentMetadata(document.RootNode));
                     }
                 }
             }
             return documentMetadata.Select(metadata => context.GetDocument(input, metadata));
         })
         .Where(x => x != null);
 }
        private void Parse(string path)
        {
            var yamlStream = new YamlStream();
            var fileText = File.ReadAllText(path);
            using (var stringReader = new StringReader(fileText))
            {
                yamlStream.Load(stringReader);
            }

            var mapping = (YamlMappingNode)yamlStream.Documents[0].RootNode;

            foreach (var entry in mapping.Children)
            {
                switch (entry.Key.ToString().ToLower())
                {
                    case "source":
                        Source = entry.Value.ToString();
                        break;
                    case "destination":
                        Destination = entry.Value.ToString();
                        break;
                    case "permalink":
                        Permalink = entry.Value.ToString();
                        break;
                    case "exclude":
                        Exclude = ((YamlSequenceNode)entry.Value).Children.Select(n => System.IO.Path.Combine(Source, n.ToString()));
                        break;
                    default:
                        break;
                }
            }
        }
Esempio n. 6
0
        public static IDictionary<string, object> YamlHeader(this string text)
        {
            var results = new Dictionary<string, object>();
            var m = r.Matches(text);
            if (m.Count == 0)
                return results;

            var input = new StringReader(m[0].Groups[1].Value);

            var yaml = new YamlStream();
            yaml.Load(input);

            var root = yaml.Documents[0].RootNode;

            var collection = root as YamlMappingNode;
            if (collection != null)
            {
                foreach (var entry in collection.Children)
                {
                    var node = entry.Key as YamlScalarNode;
                    if (node != null)
                    {
                        results.Add(node.Value, entry.Value);
                    }
                }
            }

            return results;
        }
        public override string Execute(string input)
        {
            var yamlDocument = new StringReader(input);

            var yaml = new YamlStream();
            yaml.Load(yamlDocument);

            var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

            foreach (var entry in mapping.Children)
            {
                var name = entry.Key.ToString();

                if (entry.Value is YamlMappingNode)
                {
                    AddRelationsFromLinks(name, entry.Value);
                }
                else if (entry.Value is YamlSequenceNode)
                {
                    AddAttributesWithExplicitActionFromArray(name, entry.Value);
                }
                else if (entry.Value is YamlScalarNode)
                {
                    AddAttributeFromScalarProperty(name, entry.Value);
                }
            }

            return Builder.GetAssetXml();
        }
Esempio n. 8
0
		public static YamlNode LoadFromTextReader(TextReader reader)
		{
			var yaml = new YamlStream();
			yaml.Load(reader);

			return yaml.Documents.First().RootNode;
		}
Esempio n. 9
0
        public IConfiguration Read(string path)
        {
            var entity = new Configuration();

            try
            {
                var yamlStream = new YamlStream();
                var fileText = File.ReadAllText(path);
                using (var stringReader = new StringReader(fileText))
                {
                    yamlStream.Load(stringReader);
                }
                var mapping = (YamlMappingNode)yamlStream.Documents[0].RootNode;

                if (mapping.Children.ContainsKey(new YamlScalarNode("dateformat")))
                {
                    entity.DateFormat = mapping.Children[new YamlScalarNode("dateformat")].ToString();
                }

                if (mapping.Children.ContainsKey(new YamlScalarNode("title")))
                {
                    entity.Title = mapping.Children[new YamlScalarNode("title")].ToString();
                }

                if (mapping.Children.ContainsKey(new YamlScalarNode("author")))
                {
                    entity.Author = mapping.Children[new YamlScalarNode("author")].ToString();
                }
            }
            catch
            {
            }

            return entity;
        }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of <see cref="DynamicYaml"/> from the specified stream.
        /// </summary>
        /// <param name="stream">A stream that contains a YAML content. The stream will be disposed</param>
        /// <param name="disposeStream">Dispose the stream when reading the YAML content is done. <c>true</c> by default</param>
        public DynamicYaml(Stream stream, bool disposeStream = true)
        {
            if (stream == null) throw new ArgumentNullException(nameof(stream));
            // transform the stream into string.
            string assetAsString;
            try
            {
                using (var assetStreamReader = new StreamReader(stream, Encoding.UTF8))
                {
                    assetAsString = assetStreamReader.ReadToEnd();
                }
            }
            finally
            {
                if (disposeStream)
                {
                    stream.Dispose();
                }
            }

            // Load the asset as a YamlNode object
            var input = new StringReader(assetAsString);
            yamlStream = new YamlStream();
            yamlStream.Load(input);
            
            if (yamlStream.Documents.Count != 1 || !(yamlStream.Documents[0].RootNode is YamlMappingNode))
                throw new YamlException("Unable to load the given stream");
        }
Esempio n. 11
0
    private void openRulesetToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if( ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK )
      {
        string rulesetContents;

        rulesetFilename = ofd.FileName;
        this.Text = "M.A.R.S. for OpenXCOM [" + rulesetFilename + "]";

        rulesetContents = System.IO.File.ReadAllText( ofd.FileName );
        rulesetStream = new YamlStream();

        using( System.IO.StringReader docReader = new System.IO.StringReader(rulesetContents) )
        {
          rulesetStream.Load( docReader );
        }

        rulesetRoot = (YamlMappingNode)rulesetStream.Documents[0].RootNode;

        foreach( System.Collections.Generic.KeyValuePair<YamlNode, YamlNode> child in rulesetRoot.Children )
        {
          // child are "<name>:" markers in the yaml
          TreeNode coreNode = null;
          TreeNode objNode = null;

          switch( child.Key.ToString() )
          {
            case "countries":
              coreNode = oxcTree.Nodes.Add( "Countries" );
              coreNode.Tag = child.Value;

              rulesetCountries = new Rulesets.Countries();
              rulesetCountries.Load( (YamlSequenceNode)child.Value );

              foreach( Rulesets.Country c in rulesetCountries.CountryList )
              {
                objNode = coreNode.Nodes.Add( c.CountryString );
                objNode.Tag = c;
              }

              break;

            case "regions":
              coreNode = oxcTree.Nodes.Add( "Regions" );
              coreNode.Tag = child.Value;
              break;
          }

          /*
          if( coreNode == null )
          {
            coreNode = oxcTree.Nodes.Add( child.Key.ToString() );
            coreNode.Tag = child.Value;
          }
          */

        }
        
      }
    }
Esempio n. 12
0
		public void LoadSimpleDocument() {
			var stream = new YamlStream();
			stream.Load(YamlFile("test2.yaml"));
			
			Assert.AreEqual(1, stream.Documents.Count);
			Assert.IsInstanceOf<YamlScalarNode>(stream.Documents[0].RootNode);
			Assert.AreEqual("a scalar", ((YamlScalarNode)stream.Documents[0].RootNode).Value);
		}
Esempio n. 13
0
		public void LoadSimpleDocument() {
			var stream = new YamlStream();
			stream.Load(Yaml.StreamFrom("02-scalar-in-imp-doc.yaml"));
			
			Assert.Equal(1, stream.Documents.Count);
			Assert.IsType<YamlScalarNode>(stream.Documents[0].RootNode);
			Assert.Equal("a scalar", ((YamlScalarNode)stream.Documents[0].RootNode).Value);
		}
Esempio n. 14
0
 public IEnumerable<YamlDocument> Parse(string yaml)
 {
     using (var stream = new StringReader(yaml))
     {
         var yamlStream = new YamlStream();
         yamlStream.Load (stream);
         return yamlStream.Documents;
     }
 }
        public static Version GetPackageVersion(string fullPath)
        {
            try
            {
                foreach (var packageFullPath in EnumeratePackageFullPaths(fullPath))
                {
                    // Load the package as a Yaml dynamic node, so that we can check Xenko version from dependencies
                    var input = new StringReader(File.ReadAllText(packageFullPath));
                    var yamlStream = new YamlStream();
                    yamlStream.Load(input);
                    dynamic yamlRootNode = new DynamicYamlMapping((YamlMappingNode)yamlStream.Documents[0].RootNode);

                    SemanticVersion dependencyVersion = null;

                    foreach (var dependency in yamlRootNode.Meta.Dependencies)
                    {
                        // Support paradox legacy projects
                        if ((string)dependency.Name == "Xenko" || (string)dependency.Name == "Paradox")
                        {
                            dependencyVersion = new SemanticVersion((string)dependency.Version);

                            // Paradox 1.1 was having incorrect version set (1.0), read it from .props file
                            if (dependencyVersion.Version.Major == 1 && dependencyVersion.Version.Minor == 0)
                            {
                                var propsFilePath = Path.Combine(Path.GetDirectoryName(packageFullPath) ?? "", Path.GetFileNameWithoutExtension(packageFullPath) + ".props");
                                if (File.Exists(propsFilePath))
                                {
                                    using (XmlReader propsReader = XmlReader.Create(propsFilePath))
                                    {
                                        propsReader.MoveToContent();
                                        if (propsReader.ReadToDescendant("SiliconStudioPackageParadoxVersion"))
                                        {
                                            if (propsReader.Read())
                                            {
                                                dependencyVersion = new SemanticVersion(propsReader.Value);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }

                    // Stop after first version
                    if (dependencyVersion != null)
                    {
                        return new Version(dependencyVersion.Version.Major, dependencyVersion.Version.Minor);
                    }
                }
            }
            catch (Exception)
            {
            }

            return null;
        }
        /// <summary>
        /// Create the template output
        /// </summary>
        public virtual string TransformText()
        {
            this.Write("\r\n");
            
            #line 10 "C:\Users\dean\projs\iRacingReplayOverlay.net\iRacingSDK.Net\GenerateDataModels\SessionInfoTemplate.tt"
 
	var data = iRacing.GetDataFeed().First();

	var yaml = new YamlStream();
	yaml.Load(new StringReader(data.SessionData.Raw));

	var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

            
            #line default
            #line hidden
            this.Write(@"
// This file is part of iRacingSDK.
//
// Copyright 2014 Dean Netherton
// https://github.com/vipoo/iRacingSDK.Net
//
// iRacingSDK is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// iRacingSDK is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with iRacingSDK.  If not, see <http://www.gnu.org/licenses/>.



using System;
using System.Collections.Generic;
using System.Linq;

namespace iRacingSDK
{
    public partial class SessionData
    {
        ");
            
            #line 47 "C:\Users\dean\projs\iRacingReplayOverlay.net\iRacingSDK.Net\GenerateDataModels\SessionInfoTemplate.tt"
 foreach(var kv in mapping)
            Process(kv.Key.ToString(), kv.Value);
        
            
            #line default
            #line hidden
            this.Write("    }\r\n}\r\n\r\n");
            return this.GenerationEnvironment.ToString();
        }
Esempio n. 17
0
 public static YamlStream ReadFromFile(string path)
 {
     StreamReader sr = new StreamReader(path);
     string content = sr.ReadToEnd();
     var input = new StringReader(content);
     var yaml = new YamlStream();
     yaml.Load(input);
     return yaml;
 }
Esempio n. 18
0
        public static IEnumerable<Classification> load(StreamReader input)
        {
            // Load the stream
            var yaml = new YamlStream();
            yaml.Load(input);

            var root = (YamlMappingNode)yaml.Documents[0].RootNode;
            return load(root);
        }
Esempio n. 19
0
        public void AccessingAllNodesOnInfinitelyRecursiveDocumentThrows()
        {
            var stream = new YamlStream();
            stream.Load(Yaml.ParserForText("&a [*a]"));

            var accessAllNodes = new Action(() => stream.Documents.Single().AllNodes.ToList());

            accessAllNodes.ShouldThrow<MaximumRecursionLevelReachedException>("because the document is infinitely recursive.");
        }
Esempio n. 20
0
        public static IEnumerable<OptionSource> FromFile(string fileName, string sectionName = null)
        {
            var options = new List<OptionSource>();
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(fileName);
            }
            var yamlStream = new YamlStream();
            var reader = new StringReader(File.ReadAllText(fileName));
            try
            {
                yamlStream.Load(reader);
            }
            catch (Exception ex)
            {
                throw new OptionException(String.Format("An invalid configuration file has been specified. {0}{1}", Environment.NewLine, ex.Message), "config");
            }

            var yamlNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;

            if (!String.IsNullOrEmpty(sectionName))
            {
                Func<KeyValuePair<YamlNode, YamlNode>, bool> predicate = x =>
                    x.Key.ToString() == sectionName && x.Value.GetType() == typeof(YamlMappingNode);

                var nodeExists = yamlNode.Children.Any(predicate);
                if (nodeExists)
                {
                    yamlNode = (YamlMappingNode)yamlNode.Children.First(predicate).Value;
                }
            }
            foreach (var yamlElement in yamlNode.Children)
            {
                var yamlScalarNode = yamlElement.Value as YamlScalarNode;
                var yamlSequenceNode = yamlElement.Value as YamlSequenceNode;
                if (yamlSequenceNode != null)
                {
                    var values = yamlSequenceNode.Children.Select(x => ((YamlScalarNode)x).Value);
                    try
                    {
                        //TODO GFY DO WE PREFER STRINGS OR TYPES HERE?
                        options.Add(OptionSource.String("Config File", yamlElement.Key.ToString(), values.ToArray()));
                    }
                    catch (InvalidCastException)
                    {
                        var message = String.Format("Please ensure that {0} is a valid YAML array.{1}", yamlElement.Key, Environment.NewLine);
                        throw new OptionException(message, yamlElement.Key.ToString());
                    }
                }
                else if (yamlScalarNode != null)
                {
                    options.Add(OptionSource.String("Config File", yamlElement.Key.ToString(), yamlElement.Value.ToString()));
                }
            }
            return options;
        }
Esempio n. 21
0
        public static IList<Endpoint> FromString(string data)
        {
            _fileDirectory = CurrentDirectory;

            var yaml = new YamlStream();

            using(var streamReader = new StringReader(data)) {
                yaml.Load(streamReader);
            }

            return Parse(yaml);
        }
Esempio n. 22
0
        public AddonYamlConfig(string configdir, string configfile)
        {
            var yaml = new YamlStream();
            yaml.Load(File.OpenText(Path.Combine(configdir, configfile)));

            Log.Notice("RssAddonConfig", sLConsole.GetString("Config file is loading."));

            var rssmap = (yaml.Documents.Count > 0 && ((YamlMappingNode)yaml.Documents[0].RootNode).Children.ContainsKey("RssAddon")) ? ((YamlMappingNode)((YamlMappingNode)yaml.Documents[0].RootNode).Children["RssAddon".ToYamlNode()]).Children : YamlExtensions.NullYMap;
            RssMap(rssmap.GetYamlChildren("Rss"));

            Log.Success("RssAddonConfig", sLConsole.GetString("Config database is loading."));
        }
Esempio n. 23
0
 private static NamedModel ParseModel(string input)
 {
     if (input == null) throw new ArgumentNullException("input");
     using (var yamlSource = File.OpenText(input))
     {
         var stream = new YamlStream();
         stream.Load(yamlSource);
         var visitor = new ComposeNamedModelVisitor();
         stream.Accept(visitor);
         return visitor.Model;
     }
 }
        public void YamlNodeGraphsAreBinarySerializeable()
        {
            var stream = new YamlStream();
            stream.Load(Yaml.StreamFrom("fail-backreference.yaml"));

            var formatter = new BinaryFormatter();
            var memoryStream = new MemoryStream();
            formatter.Serialize(memoryStream, stream.Documents[0].RootNode);

            memoryStream.Position = 0;
            var result = (YamlNode)formatter.Deserialize(memoryStream);
            Assert.Equal(stream.Documents[0].RootNode, result);
        }
 public YamlConfigReader(string path)
 {
     _yamlStream = new YamlStream();
     string fileContext = GetContentYamlFile(path);
     try
     {
         _yamlStream.Load(new StringReader(fileContext));
     }
     catch (SyntaxErrorException exception)
     {
         throw new DataSourseException("Incorrect config file.", exception);
     }
 }
Esempio n. 26
0
        public ShortcutProvider()
        {
            string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Keymaps\";
            string filter = "*.yml";
            if (!Directory.Exists(folder)) return;
            string[] files = Directory.GetFiles(folder, filter);

            var yaml = new YamlStream();

            foreach (string file in files)
            {
                yaml.Load(File.OpenText(file));
                var root = yaml.Documents[0].RootNode;

                var collection = root as YamlMappingNode;
                if (collection != null)
                {
                    string group = GetValueByKey(collection, "group");
                    string process = GetValueByKey(collection, "process");
                    var shortcutCollection = new ShortcutCollection { Process = process, Group = group };

                    var groupShortcuts = collection.Children.First(n => n.Key.ToString() == "shortcuts").Value as YamlSequenceNode;

                    foreach (YamlMappingNode entry in groupShortcuts.Children)
                    {
                        string name = GetValueByKey(entry, "name");

                        if (entry.Children.First(n => n.Key.ToString() == "keys").Value as YamlSequenceNode == null)
                            continue;

                        var keys = entry.Children.First(n => n.Key.ToString() == "keys").Value as YamlSequenceNode;

                        foreach (var keyCombo in keys.Children)
                        {
                            var definitions = new List<KeyPressDefinition>();
                            string[] combos = keyCombo.ToString().Split(',');
                            foreach (string combo in combos)
                            {
                                var definition = GetKeyPressDefintion(combo);
                                if (definition != null)
                                    definitions.Add(definition);
                            }
                            if (definitions.Count > 0)
                                shortcutCollection.Add(new KeyShortcut(name, definitions.ToArray()));
                        }
                    }

                    shortcuts.Add(shortcutCollection);
                }
            }
        }
Esempio n. 27
0
File: Yaml.cs Progetto: Chandu/Wyam
        public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
        {
            return inputs
                .AsParallel()
                .Select(x =>
                {
                    try
                    {
                        Dictionary<string, object> items = new Dictionary<string, object>();
                        using (TextReader contentReader = new StringReader(x.Content))
                        {
                            YamlStream yamlStream = new YamlStream();
                            yamlStream.Load(contentReader);
                            if (yamlStream.Documents.Count > 0)
                            {
                                if (!string.IsNullOrEmpty(_key))
                                {
                                    items[_key] = new DynamicYaml(yamlStream.Documents[0].RootNode);
                                }
                                if (_flatten)
                                {
                                    foreach (YamlDocument document in yamlStream.Documents)
                                    {
                                        // Map scalar-to-scalar children
                                        foreach (KeyValuePair<YamlNode, YamlNode> child in
                                            ((YamlMappingNode)document.RootNode).Children.Where(y => y.Key is YamlScalarNode && y.Value is YamlScalarNode))
                                        {
                                            items[((YamlScalarNode)child.Key).Value] = ((YamlScalarNode)child.Value).Value;
                                        }

                                        // Map simple sequences
                                        foreach (KeyValuePair<YamlNode, YamlNode> child in
                                            ((YamlMappingNode) document.RootNode).Children.Where(y => y.Key is YamlScalarNode && y.Value is YamlSequenceNode && ((YamlSequenceNode)y.Value).All(z => z is YamlScalarNode)))
                                        {
                                            items[((YamlScalarNode)child.Key).Value] = ((YamlSequenceNode)child.Value).Select(a => ((YamlScalarNode)a).Value).ToArray();
                                        }
                                    }
                                }
                            }
                        }
                        return x.Clone(items);
                    }
                    catch (Exception ex)
                    {
                        context.Trace.Error("Error processing YAML for {0}: {1}", x.Source, ex.ToString());
                    }
                    return null;
                })
                .Where(x => x != null);
        }
Esempio n. 28
0
        public string Build()
        {
            var htmlwriter = new StringWriter();

            // Load the stream
            var yaml = new YamlStream();
            yaml.Load(new StringReader(_input));

            // Examine the stream

            WriteHtmlForNode(yaml.Documents[0].RootNode, htmlwriter);

            return htmlwriter.ToString();
        }
        public IDictionary<string, string> Parse(Stream stream)
        {
            var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            var yamlConfig = new YamlStream();
            yamlConfig.Load(new StreamReader(stream));

            var mapping =
                (YamlMappingNode)yamlConfig.Documents[0].RootNode;

            VisitYamlMappingNode(mapping);

            return _data;
        }
Esempio n. 30
0
        static IEnumerable<YamlMappingNode> GetYamlMappings(IEnumerable<string> filePaths)
        {
            var yaml = new YamlStream();

            foreach (var file in filePaths)
            {
                yaml.Load(File.OpenText(file));
                var root = yaml.Documents[0].RootNode;

                var collection = root as YamlMappingNode;
                if (collection != null)
                    yield return collection;
            }
        }
Esempio n. 31
0
    /*
     * DoPostprocess() is called when build performed.
     * @param [in] reports	collection of AssetBundleBuildReport from each BundleBuilders.
     */
    public void DoPostprocess(IEnumerable <AssetBundleBuildReport> buildReports, IEnumerable <ExportReport> exportReports)
    {
        // リスト名とversionから、出力するlistの名称を決め、ファイルを移動させる。
        // なんらか対象の設定の把握ができるといいんだけど、exportPathからとるか。

        var sampleExportArray = exportReports.ToArray();

        if (sampleExportArray == null || sampleExportArray.Length == 0)
        {
            // no exports found.
            return;
        }

        // pick first exporter only.
        if (!sampleExportArray[0].ExportedItems.Any())
        {
            // empty exports.
            return;
        }

        Debug.Log("sampleExport destination:" + sampleExportArray[0].ExportedItems[0].destination);

        Debug.Log("currentTargetPlatform:" + EditorUserBuildSettings.activeBuildTarget + " export platform str is:" + BuildTargetUtility.TargetToAssetBundlePlatformName(EditorUserBuildSettings.activeBuildTarget));

        /*
         *              ここは大変まどろっこしいことをしていて、
         *              exporterからexportPathを取得できないので、exportされたAssetから"現在のプラットフォームString/現在のプラットフォームString" というパス/ファイル名になるmanifestファイルを探し出し、
         *              そのパスの直上のディレクトリ名がexportPathの最下位のフォルダ名になるので、それを取得しリスト名として使用している。
         */
        var exportPlatformStr = BuildTargetUtility.TargetToAssetBundlePlatformName(EditorUserBuildSettings.activeBuildTarget);
        var platformDelimiter = exportPlatformStr + "/" + exportPlatformStr + ".manifest";// XPlatform/XPlatform.manifest

        var rootManifestEntry = sampleExportArray[0].ExportedItems.Where(p => p.destination.Contains(platformDelimiter)).FirstOrDefault();

        if (rootManifestEntry == null)
        {
            Debug.Log("no exported root manifest with :" + platformDelimiter + " found.");
            ///もしここに来ているようなら、何かAssetGraphToolsの設定間違えの可能性があります。
            ///元から入っているmain_assetsのAssetGraphToolの設定を見てください。
            return;
        }

        var wholeExportFolderName = rootManifestEntry.destination.Substring(0, rootManifestEntry.destination.IndexOf(platformDelimiter) - 1 /*remove last / */);


        var settingFilePath = wholeExportFolderName + ".json";

        if (!File.Exists(settingFilePath))
        {
            Debug.Log("no setting file exists:" + settingFilePath);
            return;
        }

        var settingFileData = File.ReadAllBytes(settingFilePath);

        if (settingFileData.Length == 0)
        {
            Debug.Log("setting file is empty:" + settingFilePath + " need to define ListProfile class parameters.");
            return;
        }

        var settingProfile = JsonUtility.FromJson <ListProfile>(Encoding.UTF8.GetString(settingFileData));

        var listIdentity = settingProfile.identity;
        var listVersion  = settingProfile.version;

        var rootManifestPath = rootManifestEntry.destination;

        Debug.Log("generating AssetBundleList. rootManifestPath:" + rootManifestPath + " generate list identity:" + listIdentity + " version:" + listVersion);

        var targetDirectory = FileController.PathCombine(wholeExportFolderName, exportPlatformStr, listVersion);

        // check if version folder is exists.
        if (Directory.Exists(targetDirectory))
        {
            Debug.Log("same version files are already exists. list identity:" + listIdentity + " version:" + listVersion + " path:" + targetDirectory + " need to delete directory.");
            return;
            // Directory.Delete(targetDirectory, true);
        }

        // create version directory under exportPlatformStr.
        // then copy necessary files.
        {
            Directory.CreateDirectory(targetDirectory);

            foreach (var exportReport in exportReports)
            {
                var items = exportReport.ExportedItems;
                foreach (var item in items)
                {
                    var currentPath = item.destination;

                    // skip root manifest and root file.
                    if (currentPath.Contains(exportPlatformStr + "/" + exportPlatformStr))
                    {
                        continue;
                    }

                    var fileName = Path.GetFileName(currentPath);
                    if (fileName == listIdentity + ".json")
                    {
                        throw new Exception("generated AssetBundle name:" + listIdentity + ".json is overlapped with list name. please change assetBundle name, extension or list identity.");
                    }

                    var dirPath  = Path.GetDirectoryName(currentPath);
                    var destPath = FileController.PathCombine(dirPath, listVersion, fileName);
                    File.Copy(currentPath, destPath);
                }
            }
        }

        // root manifest から全てのbundleの依存関係を取り出す + 各bundleのManifestから詳細を取得する。
        {
            var bundleAndDependencies = new List <AssetBundleInfo>();

            /*
             *                  load root manifest file and get assetBundle names and dependencies.
             */

            using (var sr = new StreamReader(rootManifestPath))
            {
                // read root manifest file.
                {
                    var rootYaml = new YamlStream();
                    rootYaml.Load(sr);

                    var rootMapping = (YamlMappingNode)rootYaml.Documents[0].RootNode;
                    foreach (var root_item in rootMapping)
                    {
                        var rootKey = ((YamlScalarNode)root_item.Key).Value;
                        switch (rootKey)
                        {
                        case "ManifestFileVersion":
                        {
                            // Debug.LogError("ManifestFileVersion:" + ((YamlScalarNode)root_item.Value).Value);
                            break;
                        }

                        case "AssetBundleManifest":
                        {
                            var assetBundleManifestMapping = (YamlMappingNode)root_item.Value;
                            foreach (var assetBundleManifestMapping_item in assetBundleManifestMapping)
                            {
                                var manifestKey = ((YamlScalarNode)assetBundleManifestMapping_item.Key).Value;
                                switch (manifestKey)
                                {
                                case "AssetBundleInfos":
                                {
                                    var manifestInfoSeq = (YamlMappingNode)assetBundleManifestMapping_item.Value;
                                    foreach (var manifestInfo_item in manifestInfoSeq)
                                    {
                                        var bundleInfo = new AssetBundleInfo();


                                        var bundleInfoMapping = (YamlMappingNode)manifestInfo_item.Value;
                                        foreach (var info_item in bundleInfoMapping)
                                        {
                                            var infoKey = ((YamlScalarNode)info_item.Key).Value;
                                            switch (infoKey)
                                            {
                                            case "Name":
                                            {
                                                var name = ((YamlScalarNode)info_item.Value).Value;
                                                // Debug.LogError("name:" + name);

                                                bundleInfo.bundleName = name;
                                                break;
                                            }

                                            case "Dependencies":
                                            {
                                                var dependenciesMapping = (YamlMappingNode)info_item.Value;
                                                foreach (var dependency_item in dependenciesMapping)
                                                {
                                                    var dependentBundleName = ((YamlScalarNode)dependency_item.Value).Value;
                                                    // Debug.LogError("dependentBundleName:" + dependentBundleName);
                                                }

                                                var dependentBundleNames = dependenciesMapping.Select(t => ((YamlScalarNode)t.Value).Value).ToArray();
                                                bundleInfo.dependsBundleNames = dependentBundleNames;
                                                break;
                                            }
                                            }
                                        }


                                        bundleAndDependencies.Add(bundleInfo);
                                    }

                                    break;
                                }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }


            // create assetBundleList.

            var assetBundleInfos = new List <AssetBundleInfo>();

            /*
             *                  load each assetBundle info from bundle manifests.
             */
            foreach (var bundleAndDependencie in bundleAndDependencies)
            {
                var targetBundleName = bundleAndDependencie.bundleName;

                var newAssetBundleInfo = new AssetBundleInfo();
                newAssetBundleInfo.bundleName         = targetBundleName;
                newAssetBundleInfo.dependsBundleNames = bundleAndDependencie.dependsBundleNames;

                using (var sr = new StreamReader(FileController.PathCombine(wholeExportFolderName, exportPlatformStr, targetBundleName + ".manifest")))
                {
                    var rootYaml = new YamlStream();
                    rootYaml.Load(sr);

                    var rootMapping = (YamlMappingNode)rootYaml.Documents[0].RootNode;
                    foreach (var root_item in rootMapping)
                    {
                        var rootKey = ((YamlScalarNode)root_item.Key).Value;
                        switch (rootKey)
                        {
                        case "CRC":
                        {
                            var crc = Convert.ToUInt32(((YamlScalarNode)root_item.Value).Value);
                            // Debug.LogError("crc:" + crc);

                            newAssetBundleInfo.crc = crc;
                            break;
                        }

                        case "Assets":
                        {
                            var assetNamesSeq = (YamlSequenceNode)root_item.Value;
                            var assetNames    = assetNamesSeq.Select(n => ((YamlScalarNode)n).Value).ToArray();

                            // foreach (var assetName in assetNames) {
                            //  Debug.LogError("assetName:" + assetName);
                            // }

                            newAssetBundleInfo.assetNames = assetNames;
                            break;
                        }

                        case "Hashes":
                        {
                            var hashMapping = (YamlMappingNode)root_item.Value;
                            foreach (var hash_item in hashMapping)
                            {
                                var hashKey = ((YamlScalarNode)hash_item.Key).Value;
                                switch (hashKey)
                                {
                                case "AssetFileHash":
                                {
                                    var assetHashMapping = (YamlMappingNode)hash_item.Value;
                                    foreach (var assetHash_item in assetHashMapping)
                                    {
                                        var assetHashKey = ((YamlScalarNode)assetHash_item.Key).Value;
                                        switch (assetHashKey)
                                        {
                                        case "Hash":
                                        {
                                            var hashStr = ((YamlScalarNode)assetHash_item.Value).Value;

                                            // Debug.LogError("hashStr:" + hashStr);

                                            newAssetBundleInfo.hash = hashStr;
                                            break;
                                        }
                                        }
                                    }

                                    break;
                                }
                                }
                            }
                            break;
                        }
                        }
                    }

                    // set size.
                    newAssetBundleInfo.size = new FileInfo(FileController.PathCombine(wholeExportFolderName, exportPlatformStr, targetBundleName)).Length;

                    // Debug.LogError("newAssetBundleInfo.size:" + newAssetBundleInfo.size);

                    assetBundleInfos.Add(newAssetBundleInfo);
                }
            }

            var assetBundleList = new AssetBundleList(listIdentity, exportPlatformStr, listVersion, assetBundleInfos.ToArray());
            var str             = JsonUtility.ToJson(assetBundleList, true);


            var listOutputPaht = FileController.PathCombine(wholeExportFolderName, exportPlatformStr, listVersion, listIdentity + ".json");
            using (var sw = new StreamWriter(listOutputPaht))
            {
                sw.WriteLine(str);
            }
        }
    }
Esempio n. 32
0
        static void Main(string[] args)
        {
            string[] markdownFiles =
                Directory.GetFiles(args[0], "*");

            foreach (string s in markdownFiles)
            {
                string content = File.ReadAllText(s);

                int startOfymlBlock = content.IndexOf("---", StringComparison.Ordinal);
                int endOfymlBlock   = content.IndexOf("---", startOfymlBlock + 1, StringComparison.Ordinal);

                if (startOfymlBlock < 0 || endOfymlBlock < 0)
                {
                    Console.WriteLine("Cant find Yaml Block");
                    continue;
                }


                string ymlBlock = content.Substring(startOfymlBlock, endOfymlBlock + 3);

                string markdown = content.Substring(endOfymlBlock + 3);

                var yaml = new YamlStream();
                yaml.Load(new StringReader(ymlBlock));

                var mapping =
                    (YamlMappingNode)yaml.Documents[0].RootNode;

                if (!mapping.Children.ContainsKey("slug"))
                {
                    string filename            = Path.GetFileNameWithoutExtension(s);
                    string filenameWithoutDate = filename.Substring(11);

                    mapping.Children.Add(new KeyValuePair <YamlNode, YamlNode>("slug", filenameWithoutDate));

                    var serializer = new SerializerBuilder().Build();

                    string newYml = serializer.Serialize(mapping);

                    File.WriteAllText(s, $"---\n{newYml}\n---\n {markdown}");
                    Console.WriteLine(s);
                }

                //if you want to replace existing aliases with new ones use the following to remove old ones:

                mapping.Children.Remove("aliases");
                mapping.Children.Remove("disqus_identifier");
                mapping.Children.Remove("disqus_url");

                if (!mapping.Children.ContainsKey("aliases"))
                {
                    string filename            = Path.GetFileNameWithoutExtension(s);
                    string filenameWithoutDate = filename.Substring(11);

                    var dateString = mapping.Children["date"].ToString();

                    DateTime date;
                    if (!DateTime.TryParse(dateString, out date))
                    {
                        Console.WriteLine("Date not parsable");
                        continue;
                    }

                    string dateFormat = "yyyy/MM/dd";

                    string alias = $"{date.ToString(dateFormat)}/{filenameWithoutDate}.html";

                    string[] aliases =
                    {
                        alias,
                        alias.ToLower()
                    };

                    //mapping.Children.Add(new KeyValuePair<YamlNode, YamlNode>("aliases", aliases));

                    mapping.Children.Add(
                        new KeyValuePair <YamlNode, YamlNode>("disqus_identifier", $"https://www.tiernanotoole.ie/{alias}"));

                    mapping.Children.Add(
                        new KeyValuePair <YamlNode, YamlNode>("disqus_url", $"https://www.tiernanotoole.ie/{alias}"));


                    var serializer = new SerializerBuilder().Build();

                    string newYml = serializer.Serialize(mapping);

                    File.WriteAllText(s, $"---\n{newYml}\n---\n {markdown.Trim()}");
                    Console.WriteLine(s);
                }
                else
                {
                    var aliases = mapping.Children["aliases"];
                }
            }

            Console.ReadLine();
        }
Esempio n. 33
0
    /*
     * {
     * "ManifestFileVersion": "0",
     * "CRC": "2462514955",
     * "AssetBundleManifest": {
     *      "AssetBundleInfos": {
     *              "Info_0": {
     *                      "Name": "bundlename",
     *                      "Dependencies": {}
     *              },
     *              "Info_1": {
     *                      "Name": "dependsbundlename",
     *                      "Dependencies": {// うーん複数階層持つことがあり得るのか〜〜きっちーな。このレイヤーは紛れもなく辞書なんだ。
     *                              "Dependency_0": "bundlename"
     *                      }
     *              },
     *              "Info_2": {
     *                      "Name": "dependsbundlename2",
     *                      "Dependencies": {
     *                              "Dependency_0": "bundlename"
     *                      }
     *              },
     *              "Info_3": {
     *                      "Name": "nestedprefab",
     *                      "Dependencies": {
     *                              "Dependency_0": "dependsbundlename"
     *                      }
     *              },
     *              "Info_4": {
     *                      "Name": "updatable",
     *                      "Dependencies": {
     *                              "Dependency_0": "bundlename"
     *                      }
     *              }
     *      }
     * }
     * }
     *
     */


    public void MakeList()
    {
        var targetOSStr = targetOS.ToString();

        if (!Directory.Exists(PATH_ASSETBUNDLES_EXPORTED))
        {
            Debug.LogError("no directory found:" + PATH_ASSETBUNDLES_EXPORTED);
            return;
        }

        var platformPath = FileController.PathCombine(PATH_ASSETBUNDLES_EXPORTED, targetOSStr);

        if (!Directory.Exists(platformPath))
        {
            Debug.LogError("no platform folder found:" + platformPath);
            return;
        }

        var assumedListFilePath = FileController.PathCombine(platformPath, "AssetBundles." + targetOSStr + "_" + version.Replace(".", "_") + ".json");

        if (File.Exists(assumedListFilePath) && !shouldOverwrite)
        {
            Debug.LogError("same version file:" + assumedListFilePath + " is already exists.");
            return;
        }

        var bundleAndDependencies = new List <AssetBundleInfo>();

        /*
         *      load root manifest file and get assetBundle names and dependencies.
         */

        using (var sr = new StreamReader(FileController.PathCombine(PATH_ASSETBUNDLES_EXPORTED, targetOSStr, targetOSStr + ".manifest"))) {
            // read root manifest file.
            {
                var rootYaml = new YamlStream();
                rootYaml.Load(sr);

                var rootMapping = (YamlMappingNode)rootYaml.Documents[0].RootNode;
                foreach (var root_item in rootMapping)
                {
                    var rootKey = ((YamlScalarNode)root_item.Key).Value;
                    switch (rootKey)
                    {
                    case "ManifestFileVersion": {
                        // Debug.LogError("ManifestFileVersion:" + ((YamlScalarNode)root_item.Value).Value);
                        break;
                    }

                    case "AssetBundleManifest": {
                        var assetBundleManifestMapping = (YamlMappingNode)root_item.Value;
                        foreach (var assetBundleManifestMapping_item in assetBundleManifestMapping)
                        {
                            var manifestKey = ((YamlScalarNode)assetBundleManifestMapping_item.Key).Value;
                            switch (manifestKey)
                            {
                            case "AssetBundleInfos": {
                                var manifestInfoSeq = (YamlMappingNode)assetBundleManifestMapping_item.Value;
                                foreach (var manifestInfo_item in manifestInfoSeq)
                                {
                                    var bundleInfo = new AssetBundleInfo();


                                    var bundleInfoMapping = (YamlMappingNode)manifestInfo_item.Value;
                                    foreach (var info_item in bundleInfoMapping)
                                    {
                                        var infoKey = ((YamlScalarNode)info_item.Key).Value;
                                        switch (infoKey)
                                        {
                                        case "Name": {
                                            var name = ((YamlScalarNode)info_item.Value).Value;
                                            // Debug.LogError("name:" + name);

                                            bundleInfo.bundleName = name;
                                            break;
                                        }

                                        case "Dependencies": {
                                            var dependenciesMapping = (YamlMappingNode)info_item.Value;
                                            foreach (var dependency_item in dependenciesMapping)
                                            {
                                                var dependentBundleName = ((YamlScalarNode)dependency_item.Value).Value;
                                                // Debug.LogError("dependentBundleName:" + dependentBundleName);
                                            }

                                            var dependentBundleNames = dependenciesMapping.Select(t => ((YamlScalarNode)t.Value).Value).ToArray();
                                            bundleInfo.dependsBundleNames = dependentBundleNames;
                                            break;
                                        }
                                        }
                                    }


                                    bundleAndDependencies.Add(bundleInfo);
                                }

                                break;
                            }
                            }
                        }
                        break;
                    }
                    }
                }
            }
        }

        var assetBundleInfos = new List <AssetBundleInfo>();

        /*
         *      load each assetBundle info from bundle manifests.
         */
        foreach (var bundleAndDependencie in bundleAndDependencies)
        {
            var targetBundleName = bundleAndDependencie.bundleName;

            var newAssetBundleInfo = new AssetBundleInfo();
            newAssetBundleInfo.bundleName         = targetBundleName;
            newAssetBundleInfo.dependsBundleNames = bundleAndDependencie.dependsBundleNames;

            using (var sr = new StreamReader(FileController.PathCombine(PATH_ASSETBUNDLES_EXPORTED, targetOSStr, targetBundleName + ".manifest"))) {
                var rootYaml = new YamlStream();
                rootYaml.Load(sr);

                var rootMapping = (YamlMappingNode)rootYaml.Documents[0].RootNode;
                foreach (var root_item in rootMapping)
                {
                    var rootKey = ((YamlScalarNode)root_item.Key).Value;
                    switch (rootKey)
                    {
                    case "CRC": {
                        var crc = Convert.ToUInt32(((YamlScalarNode)root_item.Value).Value);
                        // Debug.LogError("crc:" + crc);

                        newAssetBundleInfo.crc = crc;
                        break;
                    }

                    case "Assets": {
                        var assetNamesSeq = (YamlSequenceNode)root_item.Value;
                        var assetNames    = assetNamesSeq.Select(n => ((YamlScalarNode)n).Value).ToArray();

                        // foreach (var assetName in assetNames) {
                        //  Debug.LogError("assetName:" + assetName);
                        // }

                        newAssetBundleInfo.assetNames = assetNames;
                        break;
                    }

                    case "Hashes": {
                        var hashMapping = (YamlMappingNode)root_item.Value;
                        foreach (var hash_item in hashMapping)
                        {
                            var hashKey = ((YamlScalarNode)hash_item.Key).Value;
                            switch (hashKey)
                            {
                            case "AssetFileHash": {
                                var assetHashMapping = (YamlMappingNode)hash_item.Value;
                                foreach (var assetHash_item in assetHashMapping)
                                {
                                    var assetHashKey = ((YamlScalarNode)assetHash_item.Key).Value;
                                    switch (assetHashKey)
                                    {
                                    case "Hash": {
                                        var hashStr = ((YamlScalarNode)assetHash_item.Value).Value;

                                        // Debug.LogError("hashStr:" + hashStr);

                                        newAssetBundleInfo.hash = hashStr;
                                        break;
                                    }
                                    }
                                }

                                break;
                            }
                            }
                        }
                        break;
                    }
                    }
                }

                // set size.
                newAssetBundleInfo.size = new FileInfo(FileController.PathCombine(PATH_ASSETBUNDLES_EXPORTED, targetOSStr, targetBundleName)).Length;

                // Debug.LogError("newAssetBundleInfo.size:" + newAssetBundleInfo.size);

                assetBundleInfos.Add(newAssetBundleInfo);
            }
        }

        var assetBundleList = new AssetBundleList(targetOSStr, version, assetBundleInfos.ToArray());
        var str             = JsonUtility.ToJson(assetBundleList, true);

        var listExportPath = FileController.PathCombine(PATH_ASSETBUNDLES_EXPORTED, targetOSStr, "AssetBundles." + targetOSStr + "_" + version.Replace(".", "_") + ".json");

        /*
         *      write out to file.
         *              "AssetBundles/OS/AssetBundles.OS_v_e_r.json".
         */
        using (var sw = new StreamWriter(listExportPath)) {
            sw.WriteLine(str);
        }
        Debug.Log("list exported at:" + listExportPath);
    }
Esempio n. 34
0
        public void ParseYmlFileTest()
        {
            //String filepath = Application + "/StreamingAssets/SolarSystem/";
            string path  = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;
            string path1 = AppDomain.CurrentDomain.BaseDirectory;
            string path2 = System.IO.Directory.GetCurrentDirectory();

            Console.WriteLine("path: " + path2 + "..\\..\\Data\\Data.txt");
            var Document1 = path1 + "..\\..\\Data\\Data.txt";

            var yaml1 = @"
Groups:
  - Name: ATeam
    FirstName, LastName, Age, Height:
      - [Joe, Soap, 21, 184]
      - [Mary, Ryan, 20, 169]
      - [Alex, Dole, 24, 174]
";

            var yaml2 = @"
-Label: entry
    - Layer: x
    - id: B35E246039E1CB70
    - Ref: B35E246039E1CB70
 Label: Info
    - Layer: x
    - id: CE0BEFC7022283A6
    - Ref: CE0BEFC7022283A6
 Label: entry
    - Layer: HttpWebRequest
    - id: 6DAA24FF5B777506
          ";

            var Document = @"
            receipt:    Oz-Ware Purchase Invoice
            date:        2007-08-06
            customer:
                given:   Dorothy
                family:  Gale

            items:
                - part_no:   A4786
                  descrip:   Water Bucket (Filled)
                  price:     1.47
                  quantity:  4

                - part_no:   E1628
                  descrip:   High Heeled ""Ruby"" Slippers
                  price:     100.27
                  quantity:  1

            bill-to:  &id001
                street: |
                        123 Tornado Alley
                        Suite 16
                city:   East Westville
                state:  KS

            ship-to:  *id001

            specialDelivery:  >
                Follow the Yellow Brick
                Road to the Emerald City.
                Pay no attention to the
                man behind the curtain.
  ";

            var Iconyml = @"
icons:
  - name:       Glass
    id:         glass
    unicode:    f000
    created:    1.0
    filter:
      - martini
      - drink
      - bar
      - alcohol
      - liquor
    categories:
      - Web Application Icons

  - name:       Music
    id:         music
    unicode:    f001
    created:    1.0
    filter:
      - note
      - sound
    categories:
      - Web Application Icons

  - name:       Search
    id:         search
    unicode:    f002
    created:    1.0
    filter:
      - magnify
      - zoom
      - enlarge
      - bigger
    categories:
      - Web Application Icons
";

            Console.WriteLine("Read YAML Data File.");
            // Setup the input
            var input = new StringReader(Document);
            // Load the stream
            var yaml = new YamlStream();

            yaml.Load(input);
            // Examine the stream
            var mapping =
                (YamlMappingNode)yaml.Documents[0].RootNode;
            // Loop trough all child entries and print our keys
            string key = string.Empty;

            foreach (var entry in mapping.Children)
            {
                var myKey = ((YamlScalarNode)entry.Key).Value;
                Console.WriteLine("Print Key: {0}", myKey);
                var receiptNode  = new YamlScalarNode("receipt");
                var customerNode = new YamlScalarNode("customer");

                Assert.IsTrue(mapping.Children.ContainsKey(receiptNode), "Document is missing receipt node.");
                if (mapping.Children.ContainsKey(receiptNode))
                {
                    Console.WriteLine("Print root node count: {0}", mapping.Children.Count());
                }
                if (mapping.Children.ContainsKey(customerNode))
                {
                    var customer = mapping.Children[customerNode] as YamlMappingNode;

                    Console.WriteLine("Print customer node children count: {0}", customer.Count());
                }
                //The next line works fine
                //var node = entry.Key as YamlScalarNode;
                //alternative to above line
                var node = (YamlScalarNode)entry.Key;
                if (node != null)
                {
                    Console.WriteLine("Key: {0} {1}", node.Value, entry.Value);
                }

                if (myKey != "items")
                {
                    continue;
                }
                YamlScalarNode myYamlScalarNode = new YamlScalarNode(myKey);
                var            tmpItem          = mapping.Children[myYamlScalarNode];

                var items = (YamlSequenceNode)tmpItem;
                foreach (YamlMappingNode item in items)
                {
                    Console.WriteLine(
                        "{0}\t{1}",
                        item.Children[new YamlScalarNode("part_no")],
                        item.Children[new YamlScalarNode("descrip")]
                        );
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Executes the framework using the given command line options.
        /// </summary>
        /// <param name="commandLineOptions">Command line options.</param>
        static async Task RunAsync(CommandLineOptions commandLineOptions)
        {
            // Configuration file supplied?
            if (commandLineOptions.ConfigurationFile == null)
            {
                Console.WriteLine("Please specify a configuration file, as described in the documentation.");
                Console.WriteLine();

                // Print module list
                Console.WriteLine("Available modules:");
                Console.WriteLine("  Testcase generation:");
                foreach (var(name, description) in TestcaseStage.Factory.GetSupportedModules())
                {
                    Console.WriteLine(new string(' ', 4) + name + new string(' ', Math.Max(1, 24 - name.Length)) + description);
                }
                Console.WriteLine();
                Console.WriteLine("  Trace generation:");
                foreach (var(name, description) in TraceStage.Factory.GetSupportedModules())
                {
                    Console.WriteLine(new string(' ', 4) + name + new string(' ', Math.Max(1, 24 - name.Length)) + description);
                }
                Console.WriteLine();
                Console.WriteLine("  Trace preprocessing:");
                foreach (var(name, description) in PreprocessorStage.Factory.GetSupportedModules())
                {
                    Console.WriteLine(new string(' ', 4) + name + new string(' ', Math.Max(1, 24 - name.Length)) + description);
                }
                Console.WriteLine();
                Console.WriteLine("  Analysis:");
                foreach (var(name, description) in AnalysisStage.Factory.GetSupportedModules())
                {
                    Console.WriteLine(new string(' ', 4) + name + new string(' ', Math.Max(1, 24 - name.Length)) + description);
                }
                Console.WriteLine();

                // Done
                return;
            }

            // Load configuration file
            try
            {
                // Open file and read YAML
                YamlStream yaml = new YamlStream();
                using (var configFileStream = new StreamReader(File.Open(commandLineOptions.ConfigurationFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
                    yaml.Load(configFileStream);
                var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode;

                // Read general configuration first
                var generalConfigurationNode = rootNode.GetChildNodeWithKey("general");

                // Initialize logger
                if (generalConfigurationNode == null)
                {
                    Logger.Initialize(null);
                }
                else
                {
                    Logger.Initialize((YamlMappingNode)generalConfigurationNode.GetChildNodeWithKey("logger"));
                }
                await Logger.LogDebugAsync("Loaded configuration file, initialized logger");

                // Read stages
                await Logger.LogDebugAsync("Reading pipeline configuration");

                foreach (var mainNode in rootNode.Children)
                {
                    // Read key
                    switch (mainNode.Key.GetNodeString())
                    {
                    case "testcase":
                    {
                        await Logger.LogDebugAsync("Reading and applying 'testcase' stage configuration");

                        // There must be a module name node
                        string moduleName = mainNode.Value.GetChildNodeWithKey("module").GetNodeString();

                        // Check for options
                        var optionNode = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("module-options");

                        // Create module, if possible
                        _moduleConfiguration.TestcaseStageModule = await TestcaseStage.Factory.CreateAsync(moduleName, optionNode);

                        // Remember general stage options
                        _moduleConfiguration.TestcaseStageOptions = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("options");

                        break;
                    }

                    case "trace":
                    {
                        await Logger.LogDebugAsync("Reading and applying 'trace' stage configuration");

                        // There must be a module name node
                        string moduleName = mainNode.Value.GetChildNodeWithKey("module").GetNodeString();

                        // Check for options
                        var optionNode = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("module-options");

                        // Create module, if possible
                        _moduleConfiguration.TraceStageModule = await TraceStage.Factory.CreateAsync(moduleName, optionNode);

                        // Remember general stage options
                        _moduleConfiguration.TraceStageOptions = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("options");

                        break;
                    }

                    case "preprocess":
                    {
                        await Logger.LogDebugAsync("Reading and applying 'preprocess' stage configuration");

                        // There must be a module name node
                        string moduleName = mainNode.Value.GetChildNodeWithKey("module").GetNodeString();

                        // Check for options
                        var optionNode = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("module-options");

                        // Create module, if possible
                        _moduleConfiguration.PreprocessorStageModule = await PreprocessorStage.Factory.CreateAsync(moduleName, optionNode);

                        // Remember general stage options
                        _moduleConfiguration.PreprocessorStageOptions = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("options");

                        break;
                    }

                    case "analysis":
                    {
                        await Logger.LogDebugAsync("Reading and applying 'analysis' stage configuration");

                        // There must be a module list node
                        var moduleListNode = mainNode.Value.GetChildNodeWithKey("modules");
                        if (!(moduleListNode is YamlSequenceNode moduleListSequenceNode))
                        {
                            throw new ConfigurationException("Module list node does not contain a sequence.");
                        }
                        _moduleConfiguration.AnalysesStageModules = new List <AnalysisStage>();
                        foreach (YamlMappingNode moduleEntryNode in moduleListSequenceNode)
                        {
                            // There must be a module name node
                            string moduleName = moduleEntryNode.GetChildNodeWithKey("module").GetNodeString();

                            // Check for options
                            var optionNode = (YamlMappingNode)moduleEntryNode.GetChildNodeWithKey("module-options");

                            // Create module, if possible
                            _moduleConfiguration.AnalysesStageModules.Add(await AnalysisStage.Factory.CreateAsync(moduleName, optionNode));
                        }

                        // Remember general stage options
                        _moduleConfiguration.AnalysisStageOptions = (YamlMappingNode)mainNode.Value.GetChildNodeWithKey("options");

                        break;
                    }
                    }
                }

                // Check presence of needed pipeline modules
                await Logger.LogDebugAsync("Doing some sanity checks");

                if (_moduleConfiguration.TestcaseStageModule == null ||
                    _moduleConfiguration.TraceStageModule == null ||
                    _moduleConfiguration.PreprocessorStageModule == null ||
                    !_moduleConfiguration.AnalysesStageModules.Any())
                {
                    throw new ConfigurationException("Incomplete module specification. Make sure that there is at least one module for testcase generation, trace generation, preprocessing and analysis, respectively.");
                }

                // Initialize pipeline stages
                // -> [buffer] -> trace -> [buffer]-> preprocess -> [buffer] -> analysis
                await Logger.LogDebugAsync("Initializing pipeline stages");

                var traceStageBuffer = new BufferBlock <TraceEntity>(new DataflowBlockOptions
                {
                    BoundedCapacity = _moduleConfiguration.TraceStageOptions.GetChildNodeWithKey("input-buffer-size").GetNodeInteger(1),
                    EnsureOrdered   = true
                });
                var traceStage = new TransformBlock <TraceEntity, TraceEntity>(TraceStageFunc, new ExecutionDataflowBlockOptions
                {
                    BoundedCapacity        = 1,
                    EnsureOrdered          = true,
                    MaxDegreeOfParallelism = _moduleConfiguration.TraceStageModule.SupportsParallelism ? _moduleConfiguration.TraceStageOptions.GetChildNodeWithKey("max-parallel-threads").GetNodeInteger(1) : 1,
                });
                var preprocessorStageBuffer = new BufferBlock <TraceEntity>(new DataflowBlockOptions
                {
                    BoundedCapacity = _moduleConfiguration.PreprocessorStageOptions.GetChildNodeWithKey("input-buffer-size").GetNodeInteger(1),
                    EnsureOrdered   = true
                });
                var preprocessorStage = new TransformBlock <TraceEntity, TraceEntity>(PreprocessorStageFunc, new ExecutionDataflowBlockOptions
                {
                    BoundedCapacity        = 1,
                    EnsureOrdered          = true,
                    MaxDegreeOfParallelism = _moduleConfiguration.PreprocessorStageModule.SupportsParallelism ? _moduleConfiguration.PreprocessorStageOptions.GetChildNodeWithKey("max-parallel-threads").GetNodeInteger(1) : 1,
                });
                var analysisStageBuffer = new BufferBlock <TraceEntity>(new DataflowBlockOptions
                {
                    BoundedCapacity = _moduleConfiguration.AnalysisStageOptions.GetChildNodeWithKey("input-buffer-size").GetNodeInteger(1),
                    EnsureOrdered   = true
                });
                var analysisStage = new ActionBlock <TraceEntity>(AnalysisStageFunc, new ExecutionDataflowBlockOptions
                {
                    BoundedCapacity        = 1,
                    EnsureOrdered          = true,
                    MaxDegreeOfParallelism = _moduleConfiguration.AnalysesStageModules.All(asm => asm.SupportsParallelism) ? _moduleConfiguration.AnalysisStageOptions.GetChildNodeWithKey("max-parallel-threads").GetNodeInteger(1) : 1,
                });

                // Link pipeline stages
                await Logger.LogDebugAsync("Linking pipeline stages");

                var linkOptions = new DataflowLinkOptions
                {
                    PropagateCompletion = true
                };
                traceStageBuffer.LinkTo(traceStage, linkOptions);
                traceStage.LinkTo(preprocessorStageBuffer, linkOptions);
                preprocessorStageBuffer.LinkTo(preprocessorStage, linkOptions);
                preprocessorStage.LinkTo(analysisStageBuffer, linkOptions);
                analysisStageBuffer.LinkTo(analysisStage, linkOptions);

                // Start posting test cases
                await Logger.LogInfoAsync("Start testcase thread -> pipeline start");

                var testcaseTaskCancellationTokenSource = new CancellationTokenSource();
                var testcaseTask = PostTestcases(traceStageBuffer, testcaseTaskCancellationTokenSource.Token)
                                   .ContinueWith(async(t) =>
                {
                    if (t.IsFaulted && !t.Exception.Flatten().InnerExceptions.Any(e => e is TaskCanceledException))
                    {
                        // Log exception
                        await Logger.LogErrorAsync("Testcase generation has stopped due to an unhandled exception:");
                        await Logger.LogErrorAsync(t.Exception.ToString());
                        await Logger.LogWarningAsync("Pipeline execution will be continued with the existing test cases.");
                    }
                }, testcaseTaskCancellationTokenSource.Token);

                // Handle pipeline exceptions
                try
                {
                    // Wait for all stages to complete
                    await analysisStage.Completion;
                    await Logger.LogInfoAsync("Pipeline completed.");

                    // Do final analysis steps
                    foreach (var module in _moduleConfiguration.AnalysesStageModules)
                    {
                        await module.FinishAsync();
                    }
                }
                catch (Exception ex)
                {
                    // Stop test case generator for clean exit
                    testcaseTaskCancellationTokenSource.Cancel();

                    // Log exception
                    await Logger.LogErrorAsync("An exception occured in the pipeline:");

                    await Logger.LogErrorAsync(ex.ToString());

                    await Logger.LogInfoAsync("Trying to stop gracefully");
                }

                // Wait for test case generator to stop
                try
                {
                    await testcaseTask;
                    await Logger.LogDebugAsync("Testcase thread completed.");
                }
                catch (TaskCanceledException)
                {
                    // Ignore
                }
                finally
                {
                    testcaseTaskCancellationTokenSource.Dispose();
                }

                // Do some cleanup
                await Logger.LogDebugAsync("Performing some clean up");

                await _moduleConfiguration.TestcaseStageModule.UninitAsync();

                await _moduleConfiguration.TraceStageModule.UninitAsync();

                await _moduleConfiguration.PreprocessorStageModule.UninitAsync();

                await Task.WhenAll(_moduleConfiguration.AnalysesStageModules.Select(module => module.UninitAsync()));

                // Done
                await Logger.LogInfoAsync("Program completed.");
            }
            catch (Exception ex)
            {
                // Use logger, if already initialized
                if (Logger.IsInitialized())
                {
                    await Logger.LogErrorAsync("A general error ocurred:");

                    await Logger.LogErrorAsync(ex.ToString());
                }
                else
                {
                    Console.WriteLine("A general error occured:");
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Esempio n. 36
0
        public static Racefile Parse(TextReader reader)
        {
            var yaml = new YamlStream();

            yaml.Load(reader);

            if (yaml.Documents.Count == 0)
            {
                throw new FormatException("No YAML documents found.");
            }

            if (yaml.Documents.Count > 1)
            {
                throw new FormatException("Multiple YAML documents found.");
            }

            var doc = yaml.Documents[0];

            if (doc.RootNode is YamlMappingNode root)
            {
                var racefile = new Racefile();
                foreach (var pair in root.Children)
                {
                    switch (pair.Key)
                    {
                    case YamlScalarNode s when s.Value == "name":
                        if (pair.Value is YamlScalarNode name)
                        {
                            racefile.Name = name.Value;
                        }
                        else
                        {
                            throw new FormatException("Invalid non-scalar value for 'name'.");
                        }
                        break;

                    case YamlScalarNode s when s.Value == "configs":
                        ProcessConfigs(pair.Value, racefile.Configs);
                        break;

                    case YamlScalarNode s when s.Value == "warmup":
                        ProcessLaps(pair.Value, racefile.Warmup);
                        break;

                    case YamlScalarNode s when s.Value == "benchmark":
                        ProcessLaps(pair.Value, racefile.Benchmark);
                        break;

                    case YamlScalarNode s when s.Value == "collectors":
                        ProcessCollectors(pair.Value, racefile.Collectors);
                        break;
                    }

                    // Ignore unknown keys.
                }

                return(racefile);
            }

            throw new FormatException("Root node is not a YAML mapping.");
        }
        public static string UpdateCodeLocationInYamlTemplate(string templateBody, string s3Bucket, string s3Key)
        {
            var s3Url = $"s3://{s3Bucket}/{s3Key}";

            // Setup the input
            var input = new StringReader(templateBody);

            // Load the stream
            var yaml = new YamlStream();

            yaml.Load(input);

            // Examine the stream
            var root = (YamlMappingNode)yaml.Documents[0].RootNode;

            if (root == null)
            {
                return(templateBody);
            }

            var resourcesKey = new YamlScalarNode("Resources");

            if (!root.Children.ContainsKey(resourcesKey))
            {
                return(templateBody);
            }

            var resources = (YamlMappingNode)root.Children[resourcesKey];

            foreach (var resource in resources.Children)
            {
                var resourceBody = (YamlMappingNode)resource.Value;
                var type         = (YamlScalarNode)resourceBody.Children[new YamlScalarNode("Type")];
                var properties   = (YamlMappingNode)resourceBody.Children[new YamlScalarNode("Properties")];

                if (properties == null)
                {
                    continue;
                }
                if (type == null)
                {
                    continue;
                }

                if (string.Equals(type?.Value, "AWS::Serverless::Function", StringComparison.Ordinal))
                {
                    properties.Children.Remove(new YamlScalarNode("CodeUri"));
                    properties.Add("CodeUri", s3Url);
                }
                else if (string.Equals(type?.Value, "AWS::Lambda::Function", StringComparison.Ordinal))
                {
                    properties.Children.Remove(new YamlScalarNode("Code"));
                    var code = new YamlMappingNode();
                    code.Add("S3Bucket", s3Bucket);
                    code.Add("S3Key", s3Key);

                    properties.Add("Code", code);
                }
            }
            var myText = new StringWriter();

            yaml.Save(myText);

            return(myText.ToString());
        }
        public JournalFrontMatter(string yamlFrontMatter, LocalDate?journalEntryDate)
        {
            if (string.IsNullOrWhiteSpace(yamlFrontMatter))
            {
                return;
            }

            var skipChars = Environment.NewLine.ToCharArray().Concat(new[] { '-' });

            if (yamlFrontMatter.All(x => skipChars.Contains(x)))
            {
                return;
            }

            yamlFrontMatter = yamlFrontMatter.Trim();
            var yamlLines         = yamlFrontMatter.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var originalLineCount = yamlLines.Count;

            if (yamlLines[0] == BlockIndicator)
            {
                yamlLines.RemoveAt(0);
            }

            var lastIndex = yamlLines.Count - 1;

            if (yamlLines[lastIndex] == BlockIndicator)
            {
                yamlLines.RemoveAt(lastIndex);
            }

            if (originalLineCount != yamlLines.Count)
            {
                yamlFrontMatter = string.Join(Environment.NewLine, yamlLines);
            }

            using (var reader = new System.IO.StringReader(yamlFrontMatter))
            {
                var yamlStream = new YamlStream();
                yamlStream.Load(reader);

                var keys = yamlStream.Documents[0].RootNode.AllNodes
                           .Where(x => x.NodeType == YamlNodeType.Mapping)
                           .Cast <YamlMappingNode>()
                           .SelectMany(x => x.Children.Keys)
                           .Cast <YamlScalarNode>()
                           .ToList();

                var tagsKey   = keys.FirstOrDefault(k => k.Value.ToLowerInvariant() == "tags");
                var readMeKey = keys.FirstOrDefault(k => k.Value.ToLowerInvariant() == "readme");

                if (tagsKey != null)
                {
                    var node = yamlStream.Documents[0].RootNode[tagsKey];
                    if (node.NodeType == YamlNodeType.Sequence)
                    {
                        var tags = (YamlSequenceNode)node;
                        Tags = tags.Select(x => x.ToString()).Where(x => x != "(untagged)").Distinct().OrderBy(x => x).ToList();
                    }
                }

                if (readMeKey != null && journalEntryDate != null)
                {
                    var readme     = (YamlScalarNode)yamlStream.Documents[0].RootNode[readMeKey];
                    var expression = new ReadmeParser(readme.Value).ToExpression(journalEntryDate.Value);
                    Readme     = expression.FormattedExpirationDate;
                    ReadmeDate = expression.ExpirationDate;
                }
            }
        }
Esempio n. 39
0
        private GlobalConfig()
        {
            const string configFile = "Config.yaml";

            using (StreamReader fileStream = File.OpenText(configFile))
            {
                try
                {
                    var yaml = new YamlStream();
                    yaml.Load(fileStream);

                    var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
                    TaskbarProgress  = mapping.GetValidBoolean(nameof(TaskbarProgress));
                    RefreshRate      = (ushort)mapping.GetValidValue(nameof(RefreshRate), 1, 1000);
                    CenterIndicators = mapping.GetValidBoolean(nameof(CenterIndicators));
                    PanpotIndicators = mapping.GetValidBoolean(nameof(PanpotIndicators));
                    try
                    {
                        PlaylistMode = (PlaylistMode)Enum.Parse(typeof(PlaylistMode), mapping.Children.GetValue(nameof(PlaylistMode)).ToString());
                    }
                    catch (Exception ex) when(ex is ArgumentException || ex is OverflowException)
                    {
                        throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + string.Format(Strings.ErrorConfigKeyInvalid, nameof(PlaylistMode))));
                    }
                    PlaylistSongLoops           = mapping.GetValidValue(nameof(PlaylistSongLoops), 0, long.MaxValue);
                    PlaylistFadeOutMilliseconds = mapping.GetValidValue(nameof(PlaylistFadeOutMilliseconds), 0, long.MaxValue);

                    var cmap = (YamlMappingNode)mapping.Children[nameof(Colors)];
                    Colors = new HSLColor[256];
                    foreach (KeyValuePair <YamlNode, YamlNode> c in cmap)
                    {
                        int i = (int)Utils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Colors)), c.Key.ToString(), 0, 127);
                        if (Colors[i] != null)
                        {
                            throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + string.Format(Strings.ErrorConfigColorRepeated, i)));
                        }
                        double h = 0, s = 0, l = 0;
                        foreach (KeyValuePair <YamlNode, YamlNode> v in ((YamlMappingNode)c.Value).Children)
                        {
                            string key       = v.Key.ToString();
                            string valueName = string.Format(Strings.ConfigKeySubkey, string.Format("{0} {1}", nameof(Colors), i));
                            if (key == "H")
                            {
                                h = Utils.ParseValue(valueName, v.Value.ToString(), 0, 240);
                            }
                            else if (key == "S")
                            {
                                s = Utils.ParseValue(valueName, v.Value.ToString(), 0, 240);
                            }
                            else if (key == "L")
                            {
                                l = Utils.ParseValue(valueName, v.Value.ToString(), 0, 240);
                            }
                            else
                            {
                                throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + string.Format(Strings.ErrorConfigColorInvalidKey, i)));
                            }
                        }
                        Colors[i] = Colors[i + 128] = new HSLColor(h, s, l);
                    }
                    for (int i = 0; i < Colors.Length; i++)
                    {
                        if (Colors[i] == null)
                        {
                            throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + string.Format(Strings.ErrorConfigColorMissing, i)));
                        }
                    }
                }
                catch (BetterKeyNotFoundException ex)
                {
                    throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + string.Format(Strings.ErrorConfigKeyMissing, ex.Key)));
                }
                catch (Exception ex) when(ex is InvalidValueException || ex is YamlDotNet.Core.YamlException)
                {
                    throw new Exception(string.Format(Strings.ErrorParseConfig, configFile, Environment.NewLine + ex.Message));
                }
            }
        }
Esempio n. 40
0
        public static void 最新版にバージョンアップする()
        {
            using var _ = new LogBlock(Log.現在のメソッド名);

            var path    = new VariablePath(@"$(AppData)\Configuration.yaml");
            int version = 0;

            if (!File.Exists(path.数なしパス))
            {
                return;
            }

            #region " YAML階層のルートノード 'Version' を検索し、バージョン値を取得する。"
            //----------------
            {
                var yamlText   = File.ReadAllText(path.数なしパス);
                var yamlStream = new YamlStream();
                yamlStream.Load(new StringReader(yamlText));
                var rootMapping = (YamlMappingNode)yamlStream.Documents[0].RootNode;
                var versionNode = new YamlScalarNode("Version");
                if (rootMapping.Children.ContainsKey(versionNode))
                {
                    var versionValue = rootMapping.Children[versionNode] as YamlScalarNode;
                    version = int.Parse(versionValue?.Value ?? "1");    // 取得
                }
            }
            //----------------
            #endregion

            while (version < SystemConfig.VERSION)
            {
                switch (version)
                {
                case 1:
                {
                    break;      // 存在しない
                }

                case 2:
                {
                    #region " 2 → 3 "
                    //----------------
                    var v2 = old.SystemConfig.v002_システム設定.読み込む(path);
                    var v3 = new old.SystemConfig.v003_システム設定(v2);
                    v3.保存する(path);
                    version = v3.Version;
                    break;
                    //----------------
                    #endregion
                }

                case 3:
                {
                    #region " 3 → 4 "
                    //----------------
                    var v3 = old.SystemConfig.v003_システム設定.読み込む(path);
                    var v4 = new old.SystemConfig.v004_SystemConfig(v3);
                    v4.保存する();
                    version = v4.Version;
                    break;
                    //----------------
                    #endregion
                }

                case 4:
                {
                    #region " 4 → 5 "
                    //----------------
                    var v4 = old.SystemConfig.v004_SystemConfig.読み込む(path);
                    var v5 = new old.SystemConfig.v005_SystemConfig(v4);
                    v5.保存する();
                    version = v5.Version;
                    break;
                    //----------------
                    #endregion
                }

                case 5:
                {
                    #region " 5 → 6 "
                    //----------------
                    var v5 = old.SystemConfig.v005_SystemConfig.読み込む(path);
                    var v6 = new old.SystemConfig.v006_SystemConfig(v5);
                    v6.保存する();
                    version = v6.Version;
                    break;
                    //----------------
                    #endregion
                }

                case 6:
                {
                    #region " 6 → 最新版 "
                    //----------------
                    var v6 = old.SystemConfig.v006_SystemConfig.読み込む(path);
                    var v7 = new SystemConfig(v6);
                    v7.保存する();
                    version = v7.Version;
                    break;
                    //----------------
                    #endregion
                }
                }
            }
        }
Esempio n. 41
0
    public void LoadLarge()
    {
        var yamlStream = new YamlStream();

        yamlStream.Load(new StringReader(yamlString));
    }
Esempio n. 42
0
        public static bool MigrateAssetIfNeeded(AssetMigrationContext context, PackageLoadingAssetFile loadAsset)
        {
            var assetFullPath = loadAsset.FilePath.FullPath;

            // Determine if asset was Yaml or not
            var assetFileExtension = Path.GetExtension(assetFullPath);

            if (assetFileExtension == null)
            {
                return(false);
            }

            assetFileExtension = assetFileExtension.ToLowerInvariant();

            var serializer = AssetSerializer.FindSerializer(assetFileExtension);

            if (!(serializer is AssetYamlSerializer))
            {
                return(false);
            }

            // We've got a Yaml asset, let's get expected and serialized versions
            var  serializedVersion = 0;
            int  expectedVersion;
            Type assetType;

            // Read from Yaml file the asset version and its type (to get expected version)
            // Note: It tries to read as few as possible (SerializedVersion is expected to be right after Id, so it shouldn't try to read further than that)
            using (var assetStream = loadAsset.OpenStream())
                using (var streamReader = new StreamReader(assetStream))
                {
                    var yamlEventReader = new EventReader(new Parser(streamReader));

                    // Skip header
                    yamlEventReader.Expect <StreamStart>();
                    yamlEventReader.Expect <DocumentStart>();
                    var mappingStart = yamlEventReader.Expect <MappingStart>();

                    var  yamlSerializerSettings = YamlSerializer.GetSerializerSettings();
                    var  tagTypeRegistry        = yamlSerializerSettings.TagTypeRegistry;
                    bool typeAliased;
                    assetType = tagTypeRegistry.TypeFromTag(mappingStart.Tag, out typeAliased);

                    expectedVersion = AssetRegistry.GetCurrentFormatVersion(assetType);

                    Scalar assetKey;
                    while ((assetKey = yamlEventReader.Allow <Scalar>()) != null)
                    {
                        // Only allow Id before SerializedVersion
                        if (assetKey.Value == "Id")
                        {
                            yamlEventReader.Skip();
                            continue;
                        }
                        if (assetKey.Value == "SerializedVersion")
                        {
                            serializedVersion = Convert.ToInt32(yamlEventReader.Expect <Scalar>().Value, CultureInfo.InvariantCulture);
                            break;
                        }
                    }
                }

            if (serializedVersion > expectedVersion)
            {
                // Try to open an asset newer than what we support (probably generated by a newer Paradox)
                throw new InvalidOperationException(string.Format("Asset of type {0} has been serialized with newer version {1}, but only version {2} is supported. Was this asset created with a newer version of Paradox?", assetType, serializedVersion, expectedVersion));
            }

            if (serializedVersion < expectedVersion)
            {
                // Perform asset upgrade
                context.Log.Verbose("{0} needs update, from version {1} to version {2}", Path.GetFullPath(assetFullPath), serializedVersion, expectedVersion);

                // transform the stream into string.
                string assetAsString;
                using (var assetStream = loadAsset.OpenStream())
                    using (var assetStreamReader = new StreamReader(assetStream, Encoding.UTF8))
                    {
                        assetAsString = assetStreamReader.ReadToEnd();
                    }

                // Load the asset as a YamlNode object
                var input      = new StringReader(assetAsString);
                var yamlStream = new YamlStream();
                yamlStream.Load(input);
                var yamlRootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;

                // Check if there is any asset updater
                var assetUpgraders = AssetRegistry.GetAssetUpgraders(assetType);
                if (assetUpgraders == null)
                {
                    throw new InvalidOperationException(string.Format("Asset of type {0} should be updated from version {1} to {2}, but no asset migration path was found", assetType, serializedVersion, expectedVersion));
                }

                // Instantiate asset updaters
                var currentVersion = serializedVersion;
                while (currentVersion != expectedVersion)
                {
                    int targetVersion;
                    // This will throw an exception if no upgrader is available for the given version, exiting the loop in case of error.
                    var upgrader = assetUpgraders.GetUpgrader(currentVersion, out targetVersion);
                    upgrader.Upgrade(context, currentVersion, targetVersion, yamlRootNode, loadAsset);
                    currentVersion = targetVersion;
                }

                // Make sure asset is updated to latest version
                YamlNode serializedVersionNode;
                var      newSerializedVersion = 0;
                if (yamlRootNode.Children.TryGetValue(new YamlScalarNode("SerializedVersion"), out serializedVersionNode))
                {
                    newSerializedVersion = Convert.ToInt32(((YamlScalarNode)serializedVersionNode).Value);
                }

                if (newSerializedVersion != expectedVersion)
                {
                    throw new InvalidOperationException(string.Format("Asset of type {0} was migrated, but still its new version {1} doesn't match expected version {2}.", assetType, newSerializedVersion, expectedVersion));
                }

                context.Log.Info("{0} updated from version {1} to version {2}", Path.GetFullPath(assetFullPath), serializedVersion, expectedVersion);

                var preferredIndent = YamlSerializer.GetSerializerSettings().PreferredIndent;

                // Save asset back to disk
                using (var memoryStream = new MemoryStream())
                {
                    using (var streamWriter = new StreamWriter(memoryStream))
                    {
                        yamlStream.Save(streamWriter, true, preferredIndent);
                    }
                    loadAsset.AssetContent = memoryStream.ToArray();
                }

                return(true);
            }

            return(false);
        }
Esempio n. 43
0
        static void ProcessData(CommandLineOptions options)
        {
            if (!string.IsNullOrWhiteSpace(options.ContentPath) && !string.IsNullOrWhiteSpace(options.BaseUrl) &&
                !string.IsNullOrWhiteSpace(options.TargetFolder) && !string.IsNullOrWhiteSpace(options.RepoRoot))
            {
                RedirectionRoot root = new RedirectionRoot();


                if (options.MetaType == "ASPNET_LEGACY")
                {
                    var filesNeedingToBeRedirected = Directory.GetFiles(options.ContentPath);

                    if (filesNeedingToBeRedirected != null)
                    {
                        Parallel.ForEach(filesNeedingToBeRedirected, async(file) =>
                        {
                            if (!Path.GetFileName(file).StartsWith(".") && !Path.GetFileName(file).StartsWith("toc.yml"))
                            {
                                var targetUrl = "https://docs.microsoft.com" + options.BaseUrl + "/" + Path.GetFileNameWithoutExtension(file);

                                HttpWebRequest request         = (HttpWebRequest)WebRequest.Create(targetUrl);
                                request.Method                 = "HEAD";
                                request.Timeout                = int.MaxValue;
                                request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                                try
                                {
                                    var response = (HttpWebResponse)request.GetResponse();

                                    if (options.DeleteFiles)
                                    {
                                        File.Delete(file);
                                    }
                                    root.RedirectionObjects.Add(new RedirectionObject()
                                    {
                                        SourcePath         = file.Replace(options.RepoRoot, "").Replace(@"\", @"/").Remove(0, 1),
                                        RedirectUrl        = options.BaseUrl + "/" + Path.GetFileNameWithoutExtension(file),
                                        RedirectDocumentId = true
                                    });

                                    Console.WriteLine("Created redirect for " + targetUrl);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Failed redirect for " + targetUrl);
                                }
                            }
                        });
                    }
                }
                else if (options.MetaType == "NODEJS")
                {
                    var pathToToc = Path.Combine(options.ContentPath, "toc.yml");
                    var tocInput  = new StringReader(File.ReadAllText(pathToToc));

                    var tocYaml = new YamlStream();
                    tocYaml.Load(tocInput);

                    var mapping = (YamlSequenceNode)tocYaml.Documents[0].RootNode;
                    foreach (var entry in mapping.Children)
                    {
                        // TODO: Here we create package redirections. Thos are currently custom-written,
                        // so we just need a list.
                        var serviceName = ((YamlMappingNode)entry).Children["uid"].ToString();

                        root.RedirectionObjects.Add(new RedirectionObject()
                        {
                            SourcePath         = "docs-ref-autogen/overview/azure/INSERT_SERVICE_NAME/" + serviceName + ".yml",
                            RedirectUrl        = "/javascript/api/overview/azure/INSER_SERVICE_NAME_HERE/" + serviceName,
                            RedirectDocumentId = true
                        });

                        YamlSequenceNode items = ((YamlMappingNode)entry).Children["items"] as YamlSequenceNode;

                        foreach (var child in items.Children)
                        {
                            var redirectionTarget = ((YamlMappingNode)child).Children["uid"].ToString().Replace('.', '/');

                            var targetUrl = "https://docs.microsoft.com" + options.BaseUrl + "/" + redirectionTarget;

                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
                            request.Method  = "HEAD";
                            request.Timeout = int.MaxValue;
                            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                            try
                            {
                                var response = (HttpWebResponse)request.GetResponse();

                                Console.WriteLine("Existing cotnent will be redirected: " + redirectionTarget);

                                root.RedirectionObjects.Add(new RedirectionObject()
                                {
                                    SourcePath         = "docs-ref-autogen/" + redirectionTarget + ".yml",
                                    RedirectUrl        = "/javascript/api/" + redirectionTarget,
                                    RedirectDocumentId = true
                                });

                                Console.WriteLine("Created redirect for " + targetUrl);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed redirect for " + targetUrl);
                            }
                        }
                    }
                }

                var jsonString = JsonConvert.SerializeObject(root);

                File.WriteAllText(Path.Combine(options.TargetFolder, ".openpublishing.redirection.json"), jsonString);
                Console.WriteLine("Redirection file generation complete.");
            }
        }
Esempio n. 44
0
        private void LoadKeyFile(ResourcePath yamlFile)
        {
            YamlDocument document;

            using (var stream = _resourceMan.ContentFileRead(yamlFile))
                using (var reader = new StreamReader(stream, EncodingHelpers.UTF8))
                {
                    var yamlStream = new YamlStream();
                    yamlStream.Load(reader);
                    document = yamlStream.Documents[0];
                }

            var mapping = (YamlMappingNode)document.RootNode;

            foreach (var keyMapping in mapping.GetNode <YamlSequenceNode>("binds").Cast <YamlMappingNode>())
            {
                var function = keyMapping.GetNode("function").AsString();
                if (!NetworkBindMap.FunctionExists(function))
                {
                    Logger.ErrorS("input", "Key function in {0} does not exist: '{1}'", yamlFile, function);
                    continue;
                }

                var key = keyMapping.GetNode("key").AsEnum <Keyboard.Key>();

                var canFocus = false;
                if (keyMapping.TryGetNode("canFocus", out var canFocusName))
                {
                    canFocus = canFocusName.AsBool();
                }

                var canRepeat = false;
                if (keyMapping.TryGetNode("canRepeat", out var canRepeatName))
                {
                    canRepeat = canRepeatName.AsBool();
                }

                var mod1 = Keyboard.Key.Unknown;
                if (keyMapping.TryGetNode("mod1", out var mod1Name))
                {
                    mod1 = mod1Name.AsEnum <Keyboard.Key>();
                }

                var mod2 = Keyboard.Key.Unknown;
                if (keyMapping.TryGetNode("mod2", out var mod2Name))
                {
                    mod2 = mod2Name.AsEnum <Keyboard.Key>();
                }

                var mod3 = Keyboard.Key.Unknown;
                if (keyMapping.TryGetNode("mod3", out var mod3Name))
                {
                    mod3 = mod3Name.AsEnum <Keyboard.Key>();
                }

                var type = keyMapping.GetNode("type").AsEnum <KeyBindingType>();

                var binding = new KeyBinding(function, type, key, canFocus, canRepeat, mod1, mod2, mod3);
                RegisterBinding(binding);
            }
        }
Esempio n. 45
0
        static void LoadGames()
        {
            var yaml = new YamlStream();

            yaml.Load(new StringReader(File.ReadAllText("Games.yaml")));

            var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

            Games = new Dictionary <string, AGame>();
            foreach (var g in mapping)
            {
                string           code, name, creator;
                EngineType       engineType = EngineType.M4A; ReverbType reverbType = ReverbType.Normal;
                byte             engineReverb = 0, engineVolume = 0xF; uint engineFrequency = 13379;
                uint[]           tables, tableSizes;
                List <APlaylist> playlists;
                uint             voiceTable = 0, sampleTable = 0, sampleTableSize = 0;

                code = g.Key.ToString();
                var game = (YamlMappingNode)g.Value;

                // Basic info
                name = game.Children["Name"].ToString();

                // SongTables
                var songTables = game.Children["SongTable"].ToString().Split(' ');
                tables = new uint[songTables.Length]; tableSizes = new uint[songTables.Length];
                for (int i = 0; i < songTables.Length; i++)
                {
                    tables[i] = (uint)Utils.ParseValue(songTables[i]);
                }

                // MLSS info
                if (game.Children.TryGetValue("VoiceTable", out YamlNode vTable))
                {
                    voiceTable = (uint)Utils.ParseValue(vTable.ToString());
                }
                if (game.Children.TryGetValue("SampleTable", out YamlNode sTable))
                {
                    sampleTable = (uint)Utils.ParseValue(sTable.ToString());
                }
                if (game.Children.TryGetValue("SampleTableSize", out YamlNode saTableSize))
                {
                    sampleTableSize = (uint)Utils.ParseValue(saTableSize.ToString());
                }

                // If we are to copy another game's config
                if (game.Children.TryGetValue("Copy", out YamlNode copy))
                {
                    game = (YamlMappingNode)mapping.Children[copy];
                }

                // SongTable Sizes
                string[] sizes = { };
                if (game.Children.TryGetValue("SongTableSize", out YamlNode soTableSize))
                {
                    sizes = soTableSize.ToString().Split(' ');
                }
                for (int i = 0; i < songTables.Length; i++)
                {
                    tableSizes[i] = DefaultTableSize;
                    if (i < sizes.Length)
                    {
                        tableSizes[i] = (uint)Utils.ParseValue(sizes[i]);
                    }
                }

                // Creator name
                creator = game.Children["Creator"].ToString();

                // Engine
                if (game.Children.TryGetValue("Engine", out YamlNode yeng))
                {
                    var eng = (YamlMappingNode)yeng;
                    if (eng.Children.TryGetValue("Type", out YamlNode type))
                    {
                        engineType = (EngineType)Enum.Parse(typeof(EngineType), type.ToString());
                    }
                    if (eng.Children.TryGetValue("ReverbType", out YamlNode rType))
                    {
                        reverbType = (ReverbType)Enum.Parse(typeof(ReverbType), rType.ToString());
                    }
                    if (eng.Children.TryGetValue("Reverb", out YamlNode reverb))
                    {
                        engineReverb = (byte)Utils.ParseValue(reverb.ToString());
                    }
                    if (eng.Children.TryGetValue("Volume", out YamlNode volume))
                    {
                        engineVolume = (byte)Utils.ParseValue(volume.ToString());
                    }
                    if (eng.Children.TryGetValue("Frequency", out YamlNode frequency))
                    {
                        engineFrequency = (uint)Utils.ParseValue(frequency.ToString());
                    }
                }
                var engine = new AnEngine(engineType, reverbType, engineReverb, engineVolume, engineFrequency);

                // Load playlists
                playlists = new List <APlaylist>();
                if (game.Children.TryGetValue("Music", out YamlNode ymusic))
                {
                    var music = (YamlMappingNode)ymusic;
                    foreach (var kvp in music)
                    {
                        var songs = new List <ASong>();
                        foreach (var song in (YamlMappingNode)kvp.Value)
                        {
                            songs.Add(new ASong(ushort.Parse(song.Key.ToString()), song.Value.ToString())); // No hex values. It prevents putting in duplicates by having one hex and one dec of the same song index
                        }
                        playlists.Add(new APlaylist(kvp.Key.ToString(), songs.ToArray()));
                    }
                }

                // Full playlist
                if (!playlists.Any(p => p.Name == "Music"))
                {
                    playlists.Insert(0, new APlaylist("Music", playlists.Select(p => p.Songs).UniteAll().OrderBy(s => s.Index).ToArray()));
                }

                // If playlist is empty, add an empty entry
                for (int i = 0; i < playlists.Count; i++)
                {
                    if (playlists[i].Songs.Length == 0)
                    {
                        playlists[i] = new APlaylist(playlists[i].Name, new ASong[] { new ASong(0, "Playlist is empty.") });
                    }
                }

                Games.Add(code, new AGame(code, name, creator, engine, tables, tableSizes, playlists,
                                          voiceTable, sampleTable, sampleTableSize));
            }
        }
Esempio n. 46
0
        public void AllAliasesMustBeResolved()
        {
            var original = new YamlStream();

            Assert.Throws <AnchorNotFoundException>(() => original.Load(Yaml.StreamFrom("invalid-reference.yaml")));
        }
Esempio n. 47
0
        public void LoadConfig(string filefullname)
        {
            using (StreamReader reader = File.OpenText(filefullname))
            {
                YamlStream yaml = new YamlStream();
                yaml.Load(reader);
                var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
                resolution = Convert.ToDouble(mapping.Children[new YamlScalarNode("resolution")].ToString());
                negate     = Convert.ToInt32(mapping.Children[new YamlScalarNode("negate")].ToString());
                occ_th     = Convert.ToDouble(mapping.Children[new YamlScalarNode("occupied_thresh")].ToString());
                free_th    = Convert.ToDouble(mapping.Children[new YamlScalarNode("free_thresh")].ToString());
                try
                {
                    string modeS = "";
                    modeS = ((YamlScalarNode)mapping.Children[new YamlScalarNode("mode")]).Value;
                    if (modeS == "trinary")
                    {
                        mode = MapMode.TRINARY;
                    }
                    else if (modeS == "scale")
                    {
                        mode = MapMode.SCALE;
                    }
                    else if (modeS == "raw")
                    {
                        mode = MapMode.RAW;
                    }
                    else
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                }
                origin    = new double[3];
                origin[0] = Convert.ToDouble(mapping.Children[new YamlScalarNode("origin")][0].ToString());
                origin[1] = Convert.ToDouble(mapping.Children[new YamlScalarNode("origin")][1].ToString());
                origin[2] = Convert.ToDouble(mapping.Children[new YamlScalarNode("origin")][2].ToString());

                mapfname = ((YamlScalarNode)mapping.Children[new YamlScalarNode("image")]).Value;
            }

            PGM.PGM img = new PGM.PGM(Path.Combine(Path.GetDirectoryName(filefullname), mapfname));
            map_resp_.map                 = new nm.OccupancyGrid();
            map_resp_.map.info            = new nm.MapMetaData();
            map_resp_.map.info.width      = (uint)img.Width;
            map_resp_.map.info.height     = (uint)img.Length;
            map_resp_.map.info.resolution = (float)resolution;

            map_resp_.map.info.origin            = new gm.Pose();
            map_resp_.map.info.origin.position   = new gm.Point();
            map_resp_.map.info.origin.position.x = origin[0];
            map_resp_.map.info.origin.position.y = origin[1];
            map_resp_.map.info.origin.position.z = 0;


            tf.net.emQuaternion q = emQuaternion.FromRPY(new emVector3(0, 0, origin[2]));
            map_resp_.map.info.origin.orientation   = new gm.Quaternion();
            map_resp_.map.info.origin.orientation.x = 0;
            map_resp_.map.info.origin.orientation.y = 0;
            map_resp_.map.info.origin.orientation.z = 0;
            map_resp_.map.info.origin.orientation.w = 1;

            map_resp_.map.data = new sbyte[map_resp_.map.info.width * map_resp_.map.info.height];

            int    rowstride = img.Width;
            byte   thevalue  = 0;
            double occ;

            for (int j = 0; j < map_resp_.map.info.height; j++)
            {
                for (int i = 0; i < map_resp_.map.info.width; i++)
                {
                    double color_avg = img.Data[j * rowstride + i];
                    if (!(negate == 0))
                    {
                        color_avg = 255 - color_avg;
                    }
                    if (mode == MapMode.RAW)
                    {
                        thevalue = (byte)color_avg;
                        map_resp_.map.data[(map_resp_.map.info.width * (map_resp_.map.info.height - j - 1) + i)] = (sbyte)thevalue;
                        continue;
                    }
                    occ = (255 - color_avg) / 255.0;
                    if (occ > occ_th)
                    {
                        thevalue = +100;
                    }
                    else if (occ < free_th)
                    {
                        thevalue = 0;
                    }
                    else if (mode == MapMode.TRINARY)
                    {
                        thevalue = 255;
                    }
                    else
                    {
                        double ratio = (occ - free_th) / (occ_th - free_th);
                        thevalue = (byte)(99 * ratio);
                    }
                    map_resp_.map.data[map_resp_.map.info.width * (map_resp_.map.info.height - j - 1) + i] = (sbyte)thevalue;
                }
            }
            map_resp_.map.info.map_load_time = ROS.GetTime();
            map_resp_.map.header             = new m.Header();
            map_resp_.map.header.frame_id    = fram_id;
            map_resp_.map.header.stamp       = ROS.GetTime();
            mete_data_message_ = map_resp_.map.info;
        }
Esempio n. 48
0
        // private readonly ITestOutputHelper output;

        //   public LoadingAYamlStream(ITestOutputHelper output)
        //   {
        //       this.output = output;
        //   }

        /*[Sample(
         *  DisplayName = "Loading a YAML Stream",
         *  Description = "Explains how to load YAML using the representation model."
         * )]*/


        public void Read()
        {
            // Setup the input
            var input = new StringReader(Document);

            // Load the stream
            var yaml = new YamlStream();

            yaml.Load(input);

            // Examine the stream
            var mapping =
                (YamlMappingNode)yaml.Documents[0].RootNode;

            foreach (var entry in mapping.Children)
            {
                Console.Write(((YamlScalarNode)entry.Key).Value + " : ");

                Console.Write((entry.Value));

                Console.WriteLine();
                //output.WriteLine(((YamlScalarNode)entry.Key).Value);
            }

            Console.WriteLine("====================");

            // List all the items
            var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("Financial")];

            foreach (YamlScalarNode item in items)
            {
                Console.WriteLine(
                    item.ToString()
                    );

                /*  output.WriteLine(
                 *    "{0}\t{1}",
                 *    item.Children[new YamlScalarNode("part_no")],
                 *    item.Children[new YamlScalarNode("descrip")]
                 * ); */
            }

            Console.WriteLine("====================");

            var dataParameters = (YamlMappingNode)mapping.Children[new YamlScalarNode("Data-Parameters")];

            var cards = (YamlSequenceNode)dataParameters.Children[new YamlScalarNode("Cards")];

            foreach (YamlMappingNode data in cards)
            {
                Console.WriteLine(
                    data.Children[new YamlScalarNode("Card_Type")]
                    );

                /*  output.WriteLine(
                 *    "{0}\t{1}",
                 *    item.Children[new YamlScalarNode("part_no")],
                 *    item.Children[new YamlScalarNode("descrip")]
                 * ); */
            }

            Console.WriteLine("====================");

            var amount = (YamlScalarNode)dataParameters.Children[new YamlScalarNode("Amount")];

            Console.WriteLine(amount);

            Console.WriteLine("====================");

            /*foreach (var entry in amount)
             * {
             *  Console.WriteLine(((YamlScalarNode)entry.Value).Value);
             *  //output.WriteLine(((YamlScalarNode)entry.Key).Value);
             * }*/
        }
Esempio n. 49
0
 static YamlElement ParseYamlScripts(string resource)
 {
     using var stream = EmbeddedStream.For(resource);
     using var reader = new StreamReader(stream);
     return(YamlStream.Load(reader).First().Contents);
 }
Esempio n. 50
0
        /// <summary>
        /// Loads a configuration from any TextReader
        /// </summary>
        /// <param name="configReader">the reader</param>
        /// <exception cref="InvalidConfigurationException">if an error occurs during configuration loading</exception>
        public void loadProvider(TextReader configReader)
        {
            YamlStream yaml = new YamlStream();

            try
            {
                yaml.Load(configReader);
            }
            catch (Exception e)
            {
                throw new InvalidConfigurationException(e.Message, e);
            }

            YamlNode node;
            IDictionary <YamlNode, YamlNode> rootNodes = ((YamlMappingNode)yaml.Documents[0].RootNode).Children;

            string loaderName;

            node = (rootNodes.ContainsKey(Node.LOADER) ? rootNodes[Node.LOADER] : null);
            if (node is YamlScalarNode)
            {
                loaderName = ((YamlScalarNode)node).Value.Trim().ToLower();
            }
            else
            {
                loaderName = "static";
            }
            if (!loaderFactories.ContainsKey(loaderName))
            {
                throw new InvalidConfigurationException("Unknown provider type " + loaderName + ", skipping");
            }
            LyricsLoaderFactory loaderFactory = loaderFactories[loaderName];

            node = (rootNodes.ContainsKey(Node.NAME) ? rootNodes[Node.NAME] : null);
            if (!(node is YamlScalarNode))
            {
                throw new InvalidConfigurationException("No provider name given!");
            }
            string name = ((YamlScalarNode)node).Value.Trim();

            ushort quality = 50;

            node = (rootNodes.ContainsKey(Node.QUALITY) ? rootNodes[Node.QUALITY] : null);
            if (node is YamlScalarNode)
            {
                try
                {
                    quality = Convert.ToUInt16(((YamlScalarNode)node).Value.Trim());
                }
                catch (FormatException e)
                {
                    throw new InvalidConfigurationException("Invalid quality value given, only positive numbers >= 0 are allowed!", e);
                }
            }

            RateLimit rateLimit = null;

            node = (rootNodes.ContainsKey(Node.RATE_LIMIT) ? rootNodes[Node.RATE_LIMIT] : null);
            if (node is YamlScalarNode)
            {
                rateLimit = RateLimit.parse(((YamlScalarNode)node).Value.Trim());
            }

            node = (rootNodes.ContainsKey(Node.VARIABLES) ? rootNodes[Node.VARIABLES] : null);
            Dictionary <string, Variable> variables = new Dictionary <string, Variable>();

            if (node is YamlMappingNode)
            {
                foreach (KeyValuePair <YamlNode, YamlNode> preparationEntry in ((YamlMappingNode)node).Children)
                {
                    node = preparationEntry.Key;
                    if (node is YamlScalarNode)
                    {
                        string variableName = ((YamlScalarNode)node).Value.ToLower();

                        if (variables.ContainsKey(variableName))
                        {
                            throw InvalidConfigurationException.fromFormat("{0}: Variable already defined!", variableName);
                        }

                        node = preparationEntry.Value;
                        // variable value without filters
                        if (node is YamlScalarNode)
                        {
                            string typeString = ((YamlScalarNode)node).Value.ToLower();
                            try
                            {
                                Variable.Type variableType = VARIABLE_TYPES[typeString];
                                variables.Add(variableName, new Variable(variableName, variableType));
                            }
                            catch
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString);
                            }
                        }
                        // value with filters expected
                        else if (node is YamlMappingNode)
                        {
                            YamlMappingNode variableConfig = (YamlMappingNode)node;

                            node = variableConfig.Children[Node.Variables.TYPE];
                            if (!(node is YamlScalarNode))
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Invalid variable type!", variableName);
                            }

                            Variable.Type type;
                            string        typeString = ((YamlScalarNode)node).Value.ToLower();
                            try
                            {
                                type = VARIABLE_TYPES[typeString];
                            }
                            catch
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString);
                            }

                            FilterCollection filterCollection;

                            node = (variableConfig.Children.ContainsKey(Node.Variables.FILTERS) ? variableConfig.Children[Node.Variables.FILTERS] : null);
                            // variable reference
                            if (node is YamlScalarNode)
                            {
                                string referencedVar = ((YamlScalarNode)node).Value.ToLower();
                                try
                                {
                                    filterCollection = variables[referencedVar].getFilters();
                                }
                                catch
                                {
                                    throw InvalidConfigurationException.fromFormat("{0}: Unknown variable {1} referenced!", variableName, referencedVar);
                                }
                            }
                            // a list of filters
                            else if (node is YamlSequenceNode)
                            {
                                filterCollection = FilterCollection.parseList((YamlSequenceNode)node, filters);
                            }
                            else
                            {
                                throw new InvalidConfigurationException("Invalid filter option specified!");
                            }

                            variables.Add(variableName, new Variable(variableName, type, filterCollection));
                        }
                    }
                    else
                    {
                        throw new InvalidConfigurationException("Invalid configration, aborting the configuration.");
                    }
                }
            }

            foreach (KeyValuePair <string, Variable.Type> entry in VARIABLE_TYPES)
            {
                if (!variables.ContainsKey(entry.Key))
                {
                    variables.Add(entry.Key, new Variable(entry.Key, entry.Value));
                }
            }

            node = (rootNodes.ContainsKey(Node.POST_FILTERS) ? rootNodes[Node.POST_FILTERS] : null);
            FilterCollection postFilters;

            if (node is YamlSequenceNode)
            {
                postFilters = FilterCollection.parseList((YamlSequenceNode)node, filters);
            }
            else
            {
                postFilters = new FilterCollection();
            }

            node = (rootNodes.ContainsKey(Node.VALIDATIONS) ? rootNodes[Node.VALIDATIONS] : null);
            ValidationCollection validations;

            if (node is YamlSequenceNode)
            {
                validations = ValidationCollection.parseList((YamlSequenceNode)node, validators);
            }
            else
            {
                validations = new ValidationCollection();
            }

            IDictionary <String, String> headers = new Dictionary <String, String>();

            node = (rootNodes.ContainsKey(Node.HEADERS) ? rootNodes[Node.HEADERS] : null);
            if (node is YamlMappingNode)
            {
                foreach (KeyValuePair <YamlNode, YamlNode> entry in (YamlMappingNode)node)
                {
                    if (entry.Key is YamlScalarNode && entry.Value is YamlScalarNode)
                    {
                        headers.Add(((YamlScalarNode)entry.Key).Value.Trim(), ((YamlScalarNode)entry.Value).Value);
                    }
                }
            }

            YamlMappingNode configNode;

            node = (rootNodes.ContainsKey(Node.CONFIG) ? rootNodes[Node.CONFIG] : null);
            if (node is YamlMappingNode)
            {
                configNode = (YamlMappingNode)node;
            }
            else
            {
                configNode = new YamlMappingNode();
            }

            LyricsLoader loader = loaderFactory.newLoader(configNode);

            Provider provider = new Provider(lyricsReloaded, name, quality, variables, postFilters, validations, headers, loader, rateLimit);

            logger.info("Provider loaded: " + provider.getName());

            lock (providerLock)
            {
                if (providers.ContainsKey(provider.getName()))
                {
                    logger.info("The provider {0} does already exist and will be replaced.", provider.getName());
                    providers.Remove(provider.getName());
                }
                providers.Add(provider.getName(), provider);
            }
        }
        /// <summary>
        /// Parses a YAML block of text into a WeblogPostMetaData structure.
        /// Any fields that don't match the meta structure are parsed into
        /// ExtraFields
        /// </summary>
        /// <param name="yaml"></param>
        /// <returns></returns>
        public static WeblogPostMetadata ParseFromYaml(string yaml)
        {
            var parser = new YamlStream();

            try
            {
                parser.Load(new StringReader(yaml));
            }
            catch
            {
                return(null);
            }

            var meta = new WeblogPostMetadata();

            var root = (YamlMappingNode)parser.Documents[0].RootNode;

            foreach (var entry in root.Children)
            {
                var key = entry.Key?.ToString();

                if (string.IsNullOrEmpty(key))
                {
                    continue;
                }
                if (key.Equals("Title", StringComparison.OrdinalIgnoreCase))
                {
                    meta.Title = entry.Value?.ToString();
                }
                else if (key.Equals("Abstract", StringComparison.OrdinalIgnoreCase))
                {
                    meta.Abstract = entry.Value?.ToString();
                }
                else if (key.Equals("PostId", StringComparison.OrdinalIgnoreCase))
                {
                    meta.PostId = entry.Value?.ToString();
                }
                else if (key.Equals("PostStatus", StringComparison.OrdinalIgnoreCase))
                {
                    meta.PostStatus = entry.Value?.ToString();
                }

                else if (key.Equals("PostDate", StringComparison.OrdinalIgnoreCase))
                {
                    if (!DateTime.TryParse(entry.Value.ToString(), out DateTime dt))
                    {
                        meta.PostDate = DateTime.UtcNow;
                    }
                    else
                    {
                        meta.PostDate = dt;
                    }
                }
                else if (key.Equals("WeblogName", StringComparison.OrdinalIgnoreCase))
                {
                    meta.WeblogName = entry.Value?.ToString();
                }
                else if (key.Equals("Keywords", StringComparison.OrdinalIgnoreCase))
                {
                    meta.Keywords = entry.Value?.ToString();
                }
                else if (key.Equals("Categories", StringComparison.OrdinalIgnoreCase))
                {
                    meta.Categories = entry.Value?.ToString();
                }
                else if (key.Equals("PermaLink", StringComparison.OrdinalIgnoreCase))
                {
                    meta.Permalink = entry.Value?.ToString();
                }
                else if (key.Equals("FeaturedImageUrl", StringComparison.OrdinalIgnoreCase))
                {
                    meta.FeaturedImageUrl = entry.Value?.ToString();
                }
                else if (key.Equals("FeaturedImageId", StringComparison.OrdinalIgnoreCase))
                {
                    meta.FeaturedImageId = entry.Value?.ToString();
                }
                else if (key.Equals("DontInferFeaturedImage", StringComparison.OrdinalIgnoreCase))
                {
                    bool.TryParse(entry.Value.ToString(), out bool val);
                    meta.DontInferFeaturedImage = val;
                }
                else if (key.Equals("DontStripH1Header", StringComparison.OrdinalIgnoreCase))
                {
                    bool.TryParse(entry.Value.ToString(), out bool val);
                    meta.DontStripH1Header = val;
                }
                else if (key.Equals("CustomFields", StringComparison.OrdinalIgnoreCase))
                {
                    YamlMappingNode fields;
                    try
                    {
                        fields = (YamlMappingNode)entry.Value;
                    }
                    catch
                    {
                        continue; // empty or missing
                    }

                    foreach (var item in fields.Children)
                    {
                        string k = item.Key.ToString();
                        string v = ((YamlMappingNode)item.Value).Children["value"].ToString();
                        meta.CustomFields.Add(k, new CustomField {
                            Value = v, Key = k
                        });
                    }
                }
                else
                {
                    meta.ExtraValues.Add(entry.Key.ToString(), entry.Value?.ToString());
                }
            }

            return(meta);
        }
Esempio n. 52
0
        public MainWindow()
        {
            InitializeComponent();

            StreamReader sr    = new StreamReader("example1.yaml");
            string       text  = sr.ReadToEnd();
            var          input = new StringReader(text);

            // Load the stream
            var yaml = new YamlStream();

            yaml.Load(input);

            // Examine the stream
            var mapping =
                (YamlMappingNode)yaml.Documents[0].RootNode;

            var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("form-elements")];

            foreach (YamlMappingNode item in items)
            {
                var type = item.Children[new YamlScalarNode("type")];

                switch (type.ToString())
                {
                case "textbox":
                {
                    var textboxItem = new TextBox()
                    {
                        Id      = item.Children[new YamlScalarNode("id")].ToString(),
                        Caption = item.Children[new YamlScalarNode("caption")].ToString(),
                        Size    = item.Children[new YamlScalarNode("size")].ToString(),
                    };

                    break;
                }

                case "checkbox":
                {
                    var checkboxItem = new CheckBox()
                    {
                        Id    = item.Children[new YamlScalarNode("id")].ToString(),
                        Label = item.Children[new YamlScalarNode("label")].ToString(),
                        Size  = item.Children[new YamlScalarNode("size")].ToString(),
                    };
                    break;
                }

                case "radiobuttons":
                {
                    var optionListItems = (YamlSequenceNode)item.Children[new YamlScalarNode("optionList")];
                    var list            = new List <string>();
                    foreach (YamlScalarNode x in optionListItems)
                    {
                        list.Add(x.ToString());
                    }
                    var radiobuttonsItem = new RadioButtonGroup()
                    {
                        Id          = item.Children[new YamlScalarNode("id")].ToString(),
                        Label       = item.Children[new YamlScalarNode("label")].ToString(),
                        Orientation = item.Children[new YamlScalarNode("orientation")].ToString(),
                        OptionList  = list,
                    }
                    ;
                    break;
                }
                }
            }
        }
Esempio n. 53
0
        private void ConvertPrefabsDataInScene(ref string[] scene, string oldRootPath, YamlStream yamlStream,
                                               List <ScriptMapping> scriptMappings)
        {
            // Copy prefabs
            List <YamlDocument> yamlPrefabs =
                yamlStream.Documents.Where(document => document.GetName() == "PrefabInstance").ToList();

            List <PrefabModel> oldPrefabs = prefabController.ExportPrefabs(oldRootPath);

            foreach (YamlDocument prefabInstance in yamlPrefabs)
            {
                //Get the prefab file we're working with
                string      prefabGuid  = (string)prefabInstance.RootNode["PrefabInstance"]["m_SourcePrefab"]["guid"];
                PrefabModel prefabModel = oldPrefabs.FirstOrDefault(prefabFile => prefabFile.Guid == prefabGuid);
                if (prefabModel == null || string.IsNullOrEmpty(prefabModel.Path))
                {
                    Debug.LogWarning(
                        "Found reference to prefab, but could not find the prefab. Might be a model file, not migrating. Prefab guid: " +
                        prefabGuid);
                    continue;
                }

                //Load in the prefab file
                YamlStream   prefabStream     = new YamlStream();
                string[]     lines            = File.ReadAllLines(prefabModel.Path).PrepareSceneForYaml();
                StringReader tempStringReader = new StringReader(string.Join("\r\n", lines));
                prefabStream.Load(tempStringReader);
                tempStringReader.Close();


                //Get the modifications that have been done
                YamlSequenceNode modifications =
                    (YamlSequenceNode)prefabInstance.RootNode["PrefabInstance"]["m_Modification"]["m_Modifications"];

                //change the modifications
                foreach (YamlNode modification in modifications)
                {
                    YamlNode target       = modification["target"];
                    string   fileID       = (string)target["fileID"];
                    string   propertyPath = (string)modification["propertyPath"];

                    YamlDocument scriptReference =
                        prefabStream.Documents.FirstOrDefault(document =>
                                                              document.RootNode.Anchor == fileID);
                    if (scriptReference == null)
                    {
//                        // handle nested prefab
//
//                        int FileID_of_nested_PrefabInstance = 0;
//                        int FileID_of_object_in_nested_Prefab = 0;
//                        var a = (FileID_of_nested_PrefabInstance ^ FileID_of_object_in_nested_Prefab) & 0x7fffffffffffffff;


                        Debug.LogError(
                            "Nested prefab detected! Can not migrate fields in the scene. If there are any field name changes these will not be migrated. Could not find reference to script in file! Currently nested prefabs are not supported.  fileID : " +
                            fileID);
                        continue;
                    }

                    if (scriptReference.GetName() != "MonoBehaviour")
                    {
                        continue;
                    }

                    YamlNode IDs = scriptReference.RootNode["MonoBehaviour"]["m_Script"];

                    string scriptGuid   = (string)IDs["guid"];
                    string scriptFileID = (string)IDs["fileID"];

                    ScriptMapping scriptMappingType =
                        scriptMappings.FirstOrDefault(node =>
                                                      node.oldClassModel.Guid == scriptGuid && node.oldClassModel.FileID == scriptFileID);
                    if (scriptMappingType == null)
                    {
//                        Debug.Log("Could not find mapping for guid: " + scriptGuid + " fileID: " + scriptFileID);
                        continue;
                    }

                    string[]         properties        = propertyPath.Split('.');
                    List <MergeNode> currentMergeNodes = scriptMappingType.MergeNodes;

                    for (var i = 0; i < properties.Length; i++)
                    {
                        string property = properties[i];
                        if (property == "Array" && properties.Length > i + 1 && properties[i + 1].StartsWith("data["))
                        {
                            // this is a list or array and can be skipped;
                            i++;
                            continue;
                        }


                        MergeNode currentMergeNode =
                            currentMergeNodes.FirstOrDefault(node => node.OriginalValue == property);
                        if (currentMergeNode == null)
                        {
                            Debug.Log("Could not find mergeNode for property: " + property);
                            continue;
                        }

                        properties[i] = currentMergeNode.NameToExportTo;

                        currentMergeNodes =
                            scriptMappings
                            .FirstOrDefault(script => script.oldClassModel.FullName == currentMergeNode.Type)
                            ?.MergeNodes;
                    }

                    int line = modification["propertyPath"].Start.Line - 1;
                    scene[line] = scene[line].ReplaceFirst(propertyPath, string.Join(".", properties));
                }
            }
        }
Esempio n. 54
0
 public void ReadYamlStream(YamlStream yaml, Stream stream)
 {
     using var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, leaveOpen: true);
     yaml.Load(reader);
 }
Esempio n. 55
0
        public void Parse_TomeTest4()
        {
            var yaml = new YamlStream();

            yaml.Load(GetReader("TomeTest_4.yml"));
            var mapping    = (YamlMappingNode)yaml.Documents[0].RootNode;
            var yamlParser = new BrigitYamlParser(mapping);
            var conv       = yamlParser.CreateGraphFromYaml();

            var constructed = new BrigitGraph();

            constructed.AddNode(new Node
            {
                Data = new Dialog("Diego", "Hey what's happening")
            });

            // first choice
            Choice ch1 = new Choice("This sets one to true", 0);

            ch1.Attributes.SetFlags.Add("one", Attributes.Flag.True);
            Choice ch2 = new Choice("This sets two to true", 0);

            ch2.Attributes.SetFlags.Add("two", Attributes.Flag.True);

            // the decsion block
            var choices = new Node()
            {
                Data = new Decision()
                {
                    Choices = new List <Choice>
                    {
                        ch1,
                        ch2
                    }
                }
            };

            constructed.AddNode(choices);

            // Dialog Node
            var dialog  = new Dialog("Person");
            var speech1 = new SpeechText("Hello");

            speech1.Attributes.Expression = new Variable("one");
            var speech2 = new SpeechText("Hey");

            speech2.Attributes.Expression = new Variable("two");
            dialog.Text = new List <SpeechText>()
            {
                speech1,
                speech2,
                new SpeechText("Blah")
            };

            constructed.AddNode(new Node()
            {
                Data = dialog
            });

            // second dialog node
            var dialog2 = new Dialog("Other", "Heyo", "What's going on");

            dialog2.Attributes.Expression = new Variable("one");

            constructed.AddNode(new Node()
            {
                Data = dialog2
            });

            //assertion
            bool checker = conv.Equals(constructed);

            Assert.AreEqual(true, checker);
        }
Esempio n. 56
0
    protected override void OnStart()
    {
        base.OnStart();

        // Setup the keys - load YAML asset
        var loader = new StringReader(layout.ToString());
        var yaml   = new YamlStream();

        yaml.Load(loader);

        var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
        var rows    = (YamlSequenceNode)mapping.Children[new YamlScalarNode("rows")];

        foreach (YamlMappingNode row in rows)
        {
            var savedRow = new KeyRow();
            var keys     = (YamlSequenceNode)row.Children[new YamlScalarNode("keys")];
            foreach (YamlMappingNode key in keys)
            {
                var savedKey = new PhysicsKey();
                savedKey.normal  = ((YamlScalarNode)key.Children[new YamlScalarNode("std")]).Value;
                savedKey.shifted = ((YamlScalarNode)key.Children[new YamlScalarNode("shift")]).Value;
                savedKey.width   = float.Parse(((YamlScalarNode)key.Children[new YamlScalarNode("width")]).Value);
                //Debug.LogFormat("{0} {1} w:{2}", savedKey.normal, savedKey.shifted, savedKey.width);

                savedRow.keys.Add(savedKey);
            }

            this.keyRows.Add(savedRow);
        }

        // Build the keyboard
        keyContainer = new GameObject("KeyContainer");
        keyContainer.transform.SetParent(this.transform, false);
        keyContainer.transform.localEulerAngles = new Vector3(0.0f, 180.0f, 0.0f);

        float size = keySize / 100;
        float gap  = keyGap / 100;

        float xLim = 0.0f;
        float yLim = 0.0f;

        float y = 0.0f;

        foreach (var row in this.keyRows)
        {
            float x = 0.0f;
            foreach (var key in row.keys)
            {
                // Instantiate key
                GameObject newKey = Instantiate(keyPrefab);
                newKey.transform.SetParent(keyContainer.transform, false);
                var pos = new Vector3();
                pos.x = x + size * key.width * 0.5f;
                pos.y = y;
                newKey.transform.localPosition = pos;

                // Scale
                newKey.transform.localScale = new Vector3(size, size, size);

                // Set the Visible label string and the width
                var dim = newKey.GetComponentInChildren <RectTransform>().sizeDelta;
                dim.x *= key.width;
                newKey.GetComponentInChildren <RectTransform>().sizeDelta = dim;
                newKey.GetComponentInChildren <Text>().text = labelKey(false, key);

                // Save key properties
                key.x   = x;
                key.y   = y;
                key.dim = new Vector2(size * key.width, size);
                key.obj = newKey;

                x += size * key.width + gap;
            }
            if (x > xLim)
            {
                xLim = x;
            }
            yLim = y;
            y   -= size + gap;
        }

        // Place key container to center keyboard
        keyContainer.transform.localPosition = new Vector3(xLim / 2 + gap, -yLim / 2 - gap);

        // Resize background panel
        if (panel)
        {
            var scale = panel.transform.localScale;
            panel.transform.localScale = new Vector3(xLim + 2 * gap, -y + 2 * gap, scale.z);
        }
    }
Esempio n. 57
0
        private void CheckModUpdate_Click(object sender, EventArgs e)
        {
            SaveConfig();

            var gamedir = profiles[MinecraftProfileList.SelectedIndex].GameDir;
            var moddir  = gamedir + @"\mods";

            var      remoteMods = new Dictionary <string, string>();
            string   version = null;
            DateTime lastModified = DateTime.Now;
            Dictionary <string, string> addMods = null, delMods = null;

            // check update
            var dialog = new TaskDialog()
            {
                Caption         = Application.ProductName,
                InstructionText = "Mod の更新を確認しています...",
                StandardButtons = TaskDialogStandardButtons.Cancel,
                ProgressBar     = new TaskDialogProgressBar()
                {
                    State = TaskDialogProgressBarState.Marquee
                },
                OwnerWindowHandle = Handle,
            };

            dialog.Opened += async(_sender, _e) => {
                dialog.Text = "Mod の一覧を取得しています...";
                try {
                    var req = WebRequest.Create(config.RepositoryUrl + "modlist.yml") as HttpWebRequest;
                    using (var res = await req.GetResponseAsync() as HttpWebResponse) {
                        // header
                        lastModified = DateTime.Parse(res.GetResponseHeader("Last-Modified"));
                        // body
                        using (var stream = res.GetResponseStream())
                            using (var sr = new StreamReader(stream, Encoding.UTF8)) {
                                var yml = new YamlStream();
                                yml.Load(sr);

                                var map = yml.Documents[0].RootNode as YamlMappingNode;
                                version = (map.Children[new YamlScalarNode("version")] as YamlScalarNode).Value;
                                var mods = map.Children[new YamlScalarNode("mods")] as YamlSequenceNode;
                                foreach (YamlMappingNode mod in mods)
                                {
                                    foreach (var info in mod)
                                    {
                                        remoteMods.Add((info.Key as YamlScalarNode).Value, (info.Value as YamlScalarNode).Value);
                                    }
                                }
                            }
                    }
                } catch (Exception ex) {
                    Debug.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                    dialog.Close(TaskDialogResult.No);
                    return;
                }

                dialog.Text = "Mod の更新を確認しています...";
                var excluded = config.ExcludedMods.ToDictionary(i => i, i => GetFileSHA1Hash(moddir + @"\" + i));
                addMods = remoteMods.Except(localMods).ToDictionary(i => i.Key, i => i.Value);
                delMods = localMods.Except(remoteMods).ToDictionary(i => i.Key, i => i.Value).Except(excluded).ToDictionary(i => i.Key, i => i.Value);
                if (addMods.Count == 0 && delMods.Count == 0)
                {
                    dialog.Close(TaskDialogResult.Ok);
                    return;
                }

                dialog.Close(TaskDialogResult.Yes);
            };
            var result = dialog.Show();

            if (result == TaskDialogResult.Ok)
            {
                new TaskDialog()
                {
                    Caption           = Application.ProductName,
                    InstructionText   = "Mod の更新はありません",
                    Icon              = TaskDialogStandardIcon.Information,
                    OwnerWindowHandle = Handle,
                }.Show();
                return;
            }
            else if (result == TaskDialogResult.No)
            {
                new TaskDialog()
                {
                    Caption           = Application.ProductName,
                    InstructionText   = "エラーが発生しました",
                    Text              = "更新の確認中にエラーが発生しました。",
                    Icon              = TaskDialogStandardIcon.Error,
                    OwnerWindowHandle = Handle,
                }.Show();
                return;
            }
            else if (result != TaskDialogResult.Yes)
            {
                return;
            }

            var br = Environment.NewLine;

            var adds = string.Join(br, addMods.Keys.ToArray());
            var dels = string.Join(br, delMods.Keys.ToArray());

            if (adds == string.Empty)
            {
                adds = "なし";
            }
            if (dels == string.Empty)
            {
                dels = "なし";
            }

            string detail =
                "Forge バージョン: " + version + br
                + "変更日時: " + lastModified.ToLocalTime().ToString() + br
                + br
                + "追加される Mod:" + br
                + adds + br
                + br
                + "削除される Mod:" + br
                + dels;

            dialog = new TaskDialog()
            {
                Caption               = Application.ProductName,
                InstructionText       = "Mod の更新を適用しますか?",
                Text                  = "これにより、" + addMods.Count + " 個の Mod が追加、" + delMods.Count + " 個の Mod が削除されます。",
                Icon                  = TaskDialogStandardIcon.Warning,
                StandardButtons       = TaskDialogStandardButtons.Yes | TaskDialogStandardButtons.No,
                OwnerWindowHandle     = Handle,
                DetailsCollapsedLabel = "詳細情報",
                DetailsExpandedLabel  = "詳細情報を非表示",
                ExpansionMode         = TaskDialogExpandedDetailsLocation.ExpandFooter,
                DetailsExpandedText   = detail,
            };
            var confirmResult = dialog.Show();

            if (confirmResult != TaskDialogResult.Yes)
            {
                return;
            }

            // apply update
            dialog = new TaskDialog()
            {
                Caption         = Application.ProductName,
                InstructionText = "Mod ファイルの変更を開始しています...",
                StandardButtons = TaskDialogStandardButtons.Cancel,
                ProgressBar     = new TaskDialogProgressBar()
                {
                    State = TaskDialogProgressBarState.Marquee
                },
                OwnerWindowHandle = Handle,
            };
            dialog.Opened += async(_sender, _e) => {
                bool flag;
                do
                {
                    flag = false;
                    string pid = null;
                    using (var win32proc = new System.Management.ManagementClass("Win32_Process"))
                        using (var ps = win32proc.GetInstances()) {
                            foreach (var p in ps)
                            {
                                if (p.GetPropertyValue("Name").ToString().Contains("java") && p.GetPropertyValue("CommandLine").ToString().Contains("minecraft"))
                                {
                                    flag = true;
                                    pid  = p.GetPropertyValue("ProcessId").ToString();
                                    break;
                                }
                            }
                        }
                    if (flag)
                    {
                        var confirm = new TaskDialog()
                        {
                            Caption           = Application.ProductName,
                            InstructionText   = "Minecraft が起動中です",
                            Text              = "Minecraft が起動しているため Mod の更新ができません。" + br + "アプリケーションを終了後させ [再試行] を押してください。" + br + "中止する場合は [キャンセル] を押してください。",
                            Icon              = TaskDialogStandardIcon.Warning,
                            StandardButtons   = TaskDialogStandardButtons.Retry | TaskDialogStandardButtons.Cancel,
                            OwnerWindowHandle = Handle,
                        }.Show();
                        if (confirm == TaskDialogResult.Cancel)
                        {
                            dialog.Close(TaskDialogResult.Cancel);
                            return;
                        }
                    }
                } while (flag);

                var i = 0;
                dialog.InstructionText = "Mod を削除しています...";
                foreach (var mod in delMods)
                {
                    dialog.Text = "(" + ++i + "/" + delMods.Count + ") " + mod.Key;
                    File.Delete(moddir + @"\" + mod.Key);
                    await Task.Run(() => System.Threading.Thread.Sleep(100));
                }

                i = 0;
                var failed = 0;
                dialog.InstructionText = "Mod をダウンロードしています...";
                using (var wc = new WebClient()) {
                    foreach (var mod in addMods)
                    {
                        dialog.Text = "(" + ++i + "/" + addMods.Count + ") " + mod.Key;
                        try {
                            wc.DownloadFileAsync(new Uri(config.RepositoryUrl + @"/" + version + @"/" + mod.Key), moddir + @"\" + mod.Key);
                        } catch (Exception ex) {
                            Debug.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                            failed++;
                        }
                        await Task.Run(() => System.Threading.Thread.Sleep(100));
                    }
                }

                dialog.Close();

                new TaskDialog()
                {
                    Caption           = Application.ProductName,
                    InstructionText   = "変更を適用しました",
                    Text              = addMods.Count + "個の Mod を追加、" + delMods.Count + "個の Mod を削除しました。" + (failed > 0 ? br + failed + " 個の Mod のダウンロードが失敗しました。" : ""),
                    Icon              = TaskDialogStandardIcon.Information,
                    StandardButtons   = TaskDialogStandardButtons.Ok,
                    OwnerWindowHandle = Handle,
                }.Show();
            };
            result = dialog.Show();
            UpdateLocalMods();
        }
Esempio n. 58
0
        // The multiple lines to the tail node are being created
        // because of the recurisve nature of the ToString function i wrote
        public void Parse_TomeTest3()
        {
            var yaml = new YamlStream();

            yaml.Load(GetReader("TomeTest_3.yml"));
            var mapping    = (YamlMappingNode)yaml.Documents[0].RootNode;
            var yamlParser = new BrigitYamlParser(mapping);
            var conv       = yamlParser.CreateGraphFromYaml();

            var constructed = new BrigitGraph();

            constructed.AddNode(new Node
            {
                Data = new Dialog("Diana", "I didn't want to be the one to forget")
            });
            constructed.AddNode(new Node
            {
                Data = new Dialog("Diego", "I thought of everything I'd never regret")
            });

            // looks like they're routing to the wrong places
            var choice = new Node()
            {
                Data = new Decision()
                {
                    Choices = new List <Choice>()
                    {
                        new Choice("A little time with you is all that I get", 0),
                        new Choice("That's all we need because that's all we can take", 1),
                        new Choice("I don't believe in him - his lips on the ground", 2),
                        new Choice("I wanna take you back to the place by the rock", 2)
                    }
                }
            };

            constructed.AddNode(choice);

            // chorus creation and then addition
            var chorusSubGraph = new BrigitGraph();

            chorusSubGraph.AddNode(new Node
            {
                Data = new Dialog("Diego", "I gotta be in your arms baby", "But far away I seek for your light",
                                  "I hold on because for you my heart keeps beating")
            });
            constructed.AddBranch(choice, chorusSubGraph);


            var diegoChoiceSubGraph = new BrigitGraph();

            diegoChoiceSubGraph.AddNode(new Node()
            {
                Data = new Dialog("Diego", "One thing I never see the same when you're round")
            });

            // will probably check here to make sure this works
            // the error may happen some where around here
            constructed.AddBranch(choice, diegoChoiceSubGraph);

            // everything seems fine up to this point
            constructed.AddNode(new Node()
            {
                Data = new Dialog("Diana", "But no one gives us time anymore")
            });

            constructed.AddNode(new Node()
            {
                Data = new Dialog("Diego", "Will you be my light?")
            });


            bool checker = conv.Equals(constructed);

            Assert.AreEqual(true, checker);
        }
Esempio n. 59
0
        void LoadConfig()
        {
            var yaml = new YamlStream();

            yaml.Load(new StringReader(File.ReadAllText("Config.yaml")));

            var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

            DirectCount  = (byte)Utils.ParseValue(mapping.Children["DirectCount"].ToString());
            InterFrames  = (int)Utils.ParseValue(mapping.Children["InterFrames"].ToString());
            SampleRate   = (int)Utils.ParseValue(mapping.Children["SampleRate"].ToString());
            All256Voices = bool.Parse(mapping.Children["All256Voices"].ToString());
            MIDIKeyboardFixedVelocity = bool.Parse(mapping.Children["MIDIKeyboardFixedVelocity"].ToString());
            TaskbarProgress           = bool.Parse(mapping.Children["TaskbarProgress"].ToString());
            RefreshRate      = (byte)Utils.ParseValue(mapping.Children["RefreshRate"].ToString());
            CenterIndicators = bool.Parse(mapping.Children["CenterIndicators"].ToString());
            PanpotIndicators = bool.Parse(mapping.Children["PanpotIndicators"].ToString());
            Volume           = (byte)Utils.ParseValue(mapping.Children["Volume"].ToString());

            var cmap = (YamlMappingNode)mapping.Children["Colors"];

            Colors = new HSLColor[256];
            foreach (var c in cmap)
            {
                int    i = (int)Utils.ParseValue(c.Key.ToString());
                var    children = ((YamlMappingNode)c.Value).Children;
                double h = 0, s = 0, l = 0;
                foreach (var v in children)
                {
                    if (v.Key.ToString() == "H")
                    {
                        h = byte.Parse(v.Value.ToString());
                    }
                    else if (v.Key.ToString() == "S")
                    {
                        s = byte.Parse(v.Value.ToString());
                    }
                    else if (v.Key.ToString() == "L")
                    {
                        l = byte.Parse(v.Value.ToString());
                    }
                }
                HSLColor color = new HSLColor(h, s, l);
                Colors[i] = Colors[i + 0x80] = color;
            }

            var rmap = (YamlMappingNode)mapping.Children["InstrumentRemaps"];

            InstrumentRemaps = new Dictionary <string, ARemap>();
            foreach (var r in rmap)
            {
                var remaps = new List <Tuple <byte, byte> >();

                var children = ((YamlMappingNode)r.Value).Children;
                foreach (var v in children)
                {
                    remaps.Add(new Tuple <byte, byte>(byte.Parse(v.Key.ToString()), byte.Parse(v.Value.ToString())));
                }

                InstrumentRemaps.Add(r.Key.ToString(), new ARemap(remaps.ToArray()));
            }
        }
Esempio n. 60
0
        public void Parse_TomeTest2()
        {
            var yaml = new YamlStream();

            yaml.Load(GetReader("TomeTest_2.yml"));
            var mapping    = (YamlMappingNode)yaml.Documents[0].RootNode;
            var yamlParser = new BrigitYamlParser(mapping);
            var conv       = yamlParser.CreateGraphFromYaml();

            BrigitGraph constructed = new BrigitGraph();

            constructed.AddNode(new Node()
            {
                Data = new Dialog("Yulia", "What the f**k is this", "What are you doing?")
            });

            // the choice sub graph
            BrigitGraph subGraph = new BrigitGraph();
            Decision    root     = new Decision()
            {
                Choices = new List <Choice>()
                {
                    new Choice("Nothing", 0),
                    new Choice("Everything", 2),
                    new Choice("Go away", 1),
                }
            };

            subGraph.AddNode(new Node()
            {
                Data = root
            });

            // the first branch
            BrigitGraph nothingBranch = new BrigitGraph();

            nothingBranch.AddNode(new Node()
            {
                Data = new Dialog("Yulia", "You're lying")
            });
            nothingBranch.AddNode(new Node()
            {
                Data = new Dialog("Diego", "Yeah she is")
            });

            subGraph.AddBranch(subGraph.Head, nothingBranch);

            // the second branch pointed to by the 3rd choice
            BrigitGraph goAwayBranch = new BrigitGraph();

            goAwayBranch.AddNode(new Node()
            {
                Data = new Dialog("Yulia", "NO")
            });
            subGraph.AddBranch(subGraph.Head, goAwayBranch);

            constructed.AddGraph(subGraph);
            constructed.AddNode(new Node()
            {
                Data = new Dialog("Diego", "There's a lot of yelling going on right now")
            });


            bool checker = conv.Equals(constructed);

            Assert.AreEqual(true, checker);
        }