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);
        //	}
        //}
    }
Ejemplo n.º 3
0
    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);
    }
Ejemplo n.º 4
0
Archivo: Yaml.cs Proyecto: 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);
 }
Ejemplo n.º 5
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;
        }
Ejemplo n.º 6
0
        public static void load()
        {
            coal_seams = new List<CoalSeam>();
            if (_yaml == null)
                _yaml = YamlHelper.ReadFromFile("config.yaml");

            server_ip = get_attribute("server_ip");
            db_instance = get_attribute("db_instance");
            uid = get_attribute("uid");
            password = get_attribute("password");
            update_url = get_attribute("update_url");
            update_file = get_attribute("update_file");

            var mapping = (YamlMappingNode)_yaml.Documents[0].RootNode;
            var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("coal_seams")];
            foreach (var item in items.Cast<YamlMappingNode>())
            {
                var coalSeam = new CoalSeam
                {
                    name = item.Children[new YamlScalarNode("name")].ToString(),
                    db_name = item.Children[new YamlScalarNode("db_name")].ToString(),
                    gis_name = item.Children[new YamlScalarNode("gis_name")].ToString(),
                    mxd_name = item.Children[new YamlScalarNode("mxd_name")].ToString(),
                    port = item.Children[new YamlScalarNode("port")].ToString(),
                    rest_port = item.Children[new YamlScalarNode("rest_port")].ToString()
                };
                coal_seams.Add(coalSeam);
            }
        }
        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();
        }
Ejemplo n.º 8
0
		public static YamlNode LoadFromTextReader(TextReader reader)
		{
			var yaml = new YamlStream();
			yaml.Load(reader);

			return yaml.Documents.First().RootNode;
		}
Ejemplo n.º 9
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");
        }
Ejemplo n.º 10
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;
        }
Ejemplo n.º 11
0
        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;
                }
            }
        }
Ejemplo n.º 12
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;
          }
          */

        }
        
      }
    }
Ejemplo n.º 13
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);
		}
Ejemplo n.º 14
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);
		}
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
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;
 }
        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;
        }
Ejemplo n.º 18
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.");
        }
Ejemplo n.º 19
0
 public IEnumerable<YamlDocument> Parse(string yaml)
 {
     using (var stream = new StringReader(yaml))
     {
         var yamlStream = new YamlStream();
         yamlStream.Load (stream);
         return yamlStream.Documents;
     }
 }
Ejemplo n.º 20
0
        /// <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();
        }
Ejemplo n.º 21
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;
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
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."));
        }
Ejemplo n.º 24
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 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);
     }
 }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
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);
                }
            }
        }
Ejemplo n.º 28
0
Archivo: Yaml.cs Proyecto: 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);
        }
Ejemplo n.º 29
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;
            }
        }
        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;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Writes a YAML representation of this callable to a text writer.
        /// </summary>
        /// <param name="text">The writer to output to</param>
        internal override void WriteToFile(TextWriter text)
        {
            YamlNode BuildInputNode()
            {
                var inputNode = new YamlMappingNode();

                inputNode.AddStringMapping(Utils.ContentsKey, this.inputContent);

                var typesNode = new YamlSequenceNode();

                inputNode.Add(Utils.TypesListKey, typesNode);

                foreach (var declaration in SyntaxGenerator.ExtractItems(this.callable.ArgumentTuple))
                {
                    var argNode = new YamlMappingNode();
                    var argName = ((QsLocalSymbol.ValidName)declaration.VariableName).Item.Value;
                    argNode.AddStringMapping(Utils.NameKey, argName);
                    if (this.comments.Input.TryGetValue(argName, out string summary))
                    {
                        argNode.AddStringMapping(Utils.SummaryKey, summary);
                    }
                    Utils.ResolvedTypeToYaml(declaration.Type, argNode);
                    typesNode.Add(argNode);
                }

                return(inputNode);
            }

            YamlNode BuildOutputNode()
            {
                var outputNode = new YamlMappingNode();

                outputNode.AddStringMapping(Utils.ContentsKey, this.outputType);

                var typesNode = new YamlSequenceNode();

                outputNode.Add(Utils.TypesListKey, typesNode);

                var outputTypeNode = new YamlMappingNode();

                typesNode.Add(outputTypeNode);

                if (!string.IsNullOrEmpty(this.comments.Output))
                {
                    outputTypeNode.AddStringMapping(Utils.SummaryKey, this.comments.Output);
                }
                Utils.ResolvedTypeToYaml(this.callable.Signature.ReturnType, outputTypeNode);

                return(outputNode);
            }

            var rootNode = new YamlMappingNode();

            rootNode.AddStringMapping(Utils.UidKey, this.uid);
            rootNode.AddStringMapping(Utils.NameKey, this.name);
            rootNode.AddStringMapping(Utils.TypeKey, this.itemType);
            rootNode.AddStringMapping(Utils.NamespaceKey, this.namespaceName);
            if (!string.IsNullOrWhiteSpace(this.comments.Documentation))
            {
                rootNode.AddStringMapping(Utils.SummaryKey, this.comments.Documentation);
            }
            if (!string.IsNullOrWhiteSpace(this.comments.Remarks))
            {
                rootNode.AddStringMapping(Utils.RemarksKey, this.comments.Remarks);
            }
            if (!string.IsNullOrWhiteSpace(this.comments.Example))
            {
                rootNode.AddStringMapping(Utils.ExamplesKey, this.comments.Example);
            }
            rootNode.AddStringMapping(Utils.SyntaxKey, this.syntax);
            if (!string.IsNullOrWhiteSpace(this.comments.References))
            {
                rootNode.AddStringMapping(Utils.ReferencesKey, this.comments.References);
            }
            rootNode.Add(Utils.InputKey, BuildInputNode());
            rootNode.Add(Utils.OutputKey, BuildOutputNode());
            if (this.comments.TypeParameters.Count > 0)
            {
                rootNode.Add(Utils.TypeParamsKey, Utils.BuildSequenceMappingNode(this.comments.TypeParameters));
            }
            if (this.functors.Count > 0)
            {
                rootNode.Add(Utils.FunctorsKey, Utils.BuildSequenceNode(this.functors));
            }
            if (this.comments.SeeAlso.Count > 0)
            {
                rootNode.Add(Utils.SeeAlsoKey, Utils.BuildSequenceNode(this.comments.SeeAlso));
            }

            var doc    = new YamlDocument(rootNode);
            var stream = new YamlStream(doc);

            text.WriteLine("### " + Utils.QsYamlMime + Utils.AutogenerationWarning);
            stream.Save(text, false);
        }
    /*
     * 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;
        }

        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.");
            return;
        }

        // full path for export base path.
        var wholeExportFolderPath = rootManifestEntry.destination.Substring(0, rootManifestEntry.destination.IndexOf(platformDelimiter) - 1 /*remove last / */);

        var graphName       = new DirectoryInfo(wholeExportFolderPath).Name;
        var settingFilePath = EditVersionJson(graphName);

        var settingFileData = string.Empty;

        using (var sr = new StreamReader(settingFilePath))
        {
            settingFileData = sr.ReadToEnd();
        }

        var settingProfile = JsonUtility.FromJson <ListProfile>(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(wholeExportFolderPath, 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 or modify list version. for editing list version, open Window > Autoya > Open AssetBundleListVersionEditor. ");
            return;
        }

        // 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;
                    }

                    // skip manifest file.
                    if (currentPath.EndsWith(".manifest"))
                    {
                        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>();
            var classIdSet       = new HashSet <int>();

            /*
             *  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(wholeExportFolderPath, 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;
                        }

                        case "ClassTypes":
                        {
                            var seq = (YamlSequenceNode)root_item.Value;
                            foreach (var iSeq in seq)
                            {
                                var innerMap = (YamlMappingNode)iSeq;
                                foreach (var map in innerMap)
                                {
                                    switch ((string)map.Key)
                                    {
                                    case "Class":
                                    {
                                        classIdSet.Add(Convert.ToInt32((string)map.Value));
                                        break;
                                    }
                                    }
                                }
                            }
                            break;
                        }

                        default:
                        {
                            // ignore.
                            break;
                        }
                        }
                    }

                    // set size.
                    newAssetBundleInfo.size = new FileInfo(FileController.PathCombine(wholeExportFolderPath, 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 listOutputPath = FileController.PathCombine(wholeExportFolderPath, exportPlatformStr, listVersion, listIdentity + ".json");
            using (var sw = new StreamWriter(listOutputPath))
            {
                sw.WriteLine(str);
            }

            // generate Link.xml
            LinkXMLGenerator.ExportLinkXMLWithUsingClassIds(Application.dataPath, classIdSet.ToArray());
        }
    }
Ejemplo n.º 33
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();
        }
Ejemplo n.º 34
0
    public void LoadLarge()
    {
        var yamlStream = new YamlStream();

        yamlStream.Load(new StringReader(yamlString));
    }
Ejemplo n.º 35
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);
        }
Ejemplo n.º 36
0
        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, engineTrackLimit = 0x10;
                int              engineFrequency = 13379; bool engineHasGoldenSunSynths = false;
                int[]            tables, tableSizes;
                List <APlaylist> playlists;
                string           remap = string.Empty;
                int              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 int[songTables.Length]; tableSizes = new int[songTables.Length];
                for (int i = 0; i < songTables.Length; i++)
                {
                    tables[i] = (int)Utils.ParseValue(songTables[i]);
                }

                // MLSS info
                if (game.Children.TryGetValue("VoiceTable", out YamlNode vTable))
                {
                    voiceTable = (int)Utils.ParseValue(vTable.ToString());
                }
                if (game.Children.TryGetValue("SampleTable", out YamlNode sTable))
                {
                    sampleTable = (int)Utils.ParseValue(sTable.ToString());
                }
                if (game.Children.TryGetValue("SampleTableSize", out YamlNode saTableSize))
                {
                    sampleTableSize = (int)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] = (int)Utils.ParseValue(sizes[i]);
                    }
                }

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

                // Remap
                if (game.Children.TryGetValue("Remap", out YamlNode rmap))
                {
                    remap = rmap.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("TrackLimit", out YamlNode trackLim))
                    {
                        engineTrackLimit = (byte)Utils.ParseValue(trackLim.ToString());
                    }
                    if (eng.Children.TryGetValue("Frequency", out YamlNode frequency))
                    {
                        engineFrequency = (int)Utils.ParseValue(frequency.ToString());
                    }
                    if (eng.Children.TryGetValue("GoldenSunSynths", out YamlNode synths))
                    {
                        engineHasGoldenSunSynths = bool.Parse(synths.ToString());
                    }
                }
                var engine = new AnEngine(engineType, reverbType, engineReverb, engineVolume, engineTrackLimit, engineFrequency, engineHasGoldenSunSynths);

                // 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(short.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, "La Playlist è vuota.") });
                    }
                }

                Games.Add(code, new AGame(code, name, creator, engine, tables, tableSizes, playlists, remap,
                                          voiceTable, sampleTable, sampleTableSize));
            }
        }
Ejemplo n.º 37
0
        public (World, Camera) LoadYaml(string yaml)
        {
            var    world  = new World();
            Camera camera = null;

            Materials  = new Dictionary <string, Material>();
            Transforms = new Dictionary <string, Matrix4x4>();
            Objects    = new Dictionary <string, Matrix4x4>();

            using var reader = new StringReader(yaml);
            var yamlStream = new YamlStream();

            yamlStream.Load(reader);

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

            foreach (var node in mapping)
            {
                var nodes = node.AllNodes.ToArray();

                string command = ((YamlScalarNode)nodes[1]).Value.ToUpperInvariant();
                string type    = ((YamlScalarNode)nodes[2]).Value.ToUpperInvariant();

                switch (command)
                {
                case "ADD":
                    switch (type)
                    {
                    case "CAMERA":
                        camera = ParseCamera(node);
                        break;

                    case "LIGHT":
                        world.Lights.Add(ParseLight(node));
                        break;

                    case "PLANE":
                    case "SPHERE":
                    case "CUBE":
                        world.Shapes.Add(ParseShape(node));
                        break;

                    default:
                        throw new Exception($"Add {type} not supported (line {node.Start.Line})");
                    }
                    break;

                case "DEFINE":
                    var name = type;
                    type = type.Substring(type.LastIndexOf('-') + 1);

                    switch (type)
                    {
                    case "MATERIAL":
                        Materials.Add(name, ParseMaterialDefine(node));
                        break;

                    case "TRANSFORM":
                        Transforms.Add(name, ParseTransform(node.AllNodes.ToArray()[4]));
                        break;

                    case "OBJECT":
                        Objects.Add(name, ParseTransform(node.AllNodes.ToArray()[4]));
                        break;

                    default:
                        throw new Exception($"Define {name} not supported (line {node.Start.Line})");
                    }
                    break;

                default:
                    throw new Exception($"Command {command} not supported (line {node.Start.Line})");
                }
            }

            return(world, camera);
        }
Ejemplo n.º 38
0
        public void AllAliasesMustBeResolved()
        {
            var original = new YamlStream();

            Assert.Throws <AnchorNotFoundException>(() => original.Load(Yaml.StreamFrom("invalid-reference.yaml")));
        }
Ejemplo n.º 39
0
 protected override void Visit(YamlStream stream)
 {
     WriteIndent();
     Console.WriteLine("Visit(YamlStream)");
     ++indent;
 }
        public async Task Test()
        {
            var(client, server) = await StartConnectedServerDummyTickerClientPair();

            await server.WaitIdleAsync();

            var sResourceManager = server.ResolveDependency <IResourceManager>();
            var prototypePath    = new ResourcePath("/Prototypes/");
            var paths            = sResourceManager.ContentFindFiles(prototypePath)
                                   .ToList()
                                   .AsParallel()
                                   .Where(filePath => filePath.Extension == "yml" &&
                                          !filePath.Filename.StartsWith("."))
                                   .ToArray();

            var cComponentFactory = client.ResolveDependency <IComponentFactory>();
            var sComponentFactory = server.ResolveDependency <IComponentFactory>();

            var unknownComponentsClient = new List <(string entityId, string component)>();
            var unknownComponentsServer = new List <(string entityId, string component)>();
            var entitiesValidated       = 0;
            var componentsValidated     = 0;

            foreach (var path in paths)
            {
                var file   = sResourceManager.ContentFileRead(path);
                var reader = new StreamReader(file, Encoding.UTF8);

                var yamlStream = new YamlStream();

                Assert.DoesNotThrow(() => yamlStream.Load(reader), "Error while parsing yaml file {0}", path);

                foreach (var document in yamlStream.Documents)
                {
                    var root = (YamlSequenceNode)document.RootNode;

                    foreach (var node in root.Cast <YamlMappingNode>())
                    {
                        var prototypeType = node.GetNode("type").AsString();

                        if (prototypeType != "entity")
                        {
                            continue;
                        }

                        if (!node.TryGetNode <YamlSequenceNode>("components", out var components))
                        {
                            continue;
                        }

                        entitiesValidated++;

                        foreach (var component in components.Cast <YamlMappingNode>())
                        {
                            componentsValidated++;

                            var componentType      = component.GetNode("type").AsString();
                            var clientAvailability = cComponentFactory.GetComponentAvailability(componentType);

                            if (clientAvailability == ComponentAvailability.Unknown)
                            {
                                var entityId = node.GetNode("id").AsString();
                                unknownComponentsClient.Add((entityId, componentType));
                            }

                            var serverAvailability = sComponentFactory.GetComponentAvailability(componentType);

                            if (serverAvailability == ComponentAvailability.Unknown)
                            {
                                var entityId = node.GetNode("id").AsString();
                                unknownComponentsServer.Add((entityId, componentType));
                            }
                        }
                    }
                }
            }

            if (unknownComponentsClient.Count + unknownComponentsServer.Count == 0)
            {
                Assert.Pass($"Validated {entitiesValidated} entities with {componentsValidated} components in {paths.Length} files.");
                return;
            }

            var message = new StringBuilder();

            foreach (var unknownComponent in unknownComponentsClient)
            {
                message.Append(
                    $"CLIENT: Unknown component {unknownComponent.component} in prototype {unknownComponent.entityId}\n");
            }

            foreach (var unknownComponent in unknownComponentsServer)
            {
                message.Append(
                    $"SERVER: Unknown component {unknownComponent.component} in prototype {unknownComponent.entityId}\n");
            }

            Assert.Fail(message.ToString());
        }
Ejemplo n.º 41
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);
        }
    }
Ejemplo n.º 42
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);
             * }*/
        }
        public NintendoContentFileSystemInfo GetFileSystemInfo()
        {
            NintendoContentFileSystemInfo fileSystemInfo1 = new NintendoContentFileSystemInfo();

            using (StreamReader streamReader = new StreamReader(this.m_adfPath, Encoding.UTF8))
            {
                YamlStream yamlStream = new YamlStream();
                yamlStream.Load((TextReader)streamReader);
                YamlMappingNode  rootNode;
                YamlSequenceNode child1;
                try
                {
                    rootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;
                    if (((YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("formatType")]).Value != "NintendoContent")
                    {
                        throw new ArgumentException();
                    }
                    YamlScalarNode child2 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("contentType")];
                    YamlScalarNode child3 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("keyGeneration")];
                    YamlScalarNode child4 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("programId")];
                    YamlScalarNode child5 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("contentIndex")];
                    child1 = (YamlSequenceNode)rootNode.Children[(YamlNode) new YamlScalarNode("entries")];
                    fileSystemInfo1.contentType   = this.ConvertToContentTypeByte(child2.Value);
                    fileSystemInfo1.keyGeneration = Convert.ToByte(child3.Value);
                    fileSystemInfo1.programId     = Convert.ToUInt64(child4.Value, 16);
                    fileSystemInfo1.contentIndex  = Convert.ToUInt32(child5.Value);
                }
                catch
                {
                    throw new ArgumentException("invalid format .adf file.");
                }
                try
                {
                    YamlScalarNode child2 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("keyAreaEncryptionKeyIndex")];
                    fileSystemInfo1.keyAreaEncryptionKeyIndex = Convert.ToByte(child2.Value);
                }
                catch
                {
                    fileSystemInfo1.keyAreaEncryptionKeyIndex = (byte)0;
                }
                string descFilePath;
                if (fileSystemInfo1.contentType == (byte)0)
                {
                    try
                    {
                        descFilePath = ((YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("descFilePath")]).Value;
                    }
                    catch
                    {
                        throw new ArgumentException(".desc file is not specified for program content.");
                    }
                }
                else
                {
                    descFilePath = (string)null;
                }
                byte[] numArray = (byte[])null;
                if (descFilePath != null)
                {
                    numArray = NintendoContentAdfReader.RetrieveInfoFromDesc(ref fileSystemInfo1, descFilePath);
                }
                foreach (YamlMappingNode yamlMappingNode in child1)
                {
                    NintendoContentFileSystemInfo.EntryInfo entryInfo1 = new NintendoContentFileSystemInfo.EntryInfo();
                    string adfPath = (string)null;
                    foreach (KeyValuePair <YamlNode, YamlNode> keyValuePair in yamlMappingNode)
                    {
                        switch (((YamlScalarNode)keyValuePair.Key).Value)
                        {
                        case "encryptionType":
                            entryInfo1.encryptionType = Convert.ToByte(((YamlScalarNode)keyValuePair.Value).Value);
                            continue;

                        case "formatType":
                            entryInfo1.formatType = ((YamlScalarNode)keyValuePair.Value).Value;
                            continue;

                        case "hashType":
                            entryInfo1.hashType = Convert.ToByte(((YamlScalarNode)keyValuePair.Value).Value);
                            continue;

                        case "partitionType":
                            entryInfo1.partitionType  = ((YamlScalarNode)keyValuePair.Value).Value;
                            entryInfo1.partitionIndex = this.GetPartitionIndex(entryInfo1.partitionType);
                            continue;

                        case "path":
                            adfPath = ((YamlScalarNode)keyValuePair.Value).Value;
                            continue;

                        case "type":
                            entryInfo1.type = ((YamlScalarNode)keyValuePair.Value).Value;
                            continue;

                        case "version":
                            entryInfo1.version = Convert.ToUInt16(((YamlScalarNode)keyValuePair.Value).Value);
                            continue;

                        default:
                            throw new ArgumentException("invalid format .adf file. invalid key is specified\n" + yamlMappingNode.ToString());
                        }
                    }
                    if (entryInfo1.type == null || entryInfo1.formatType == null || adfPath == null)
                    {
                        throw new ArgumentException("invalid format .adf file. \"type\" or \"formatType\" is not specified\n" + yamlMappingNode.ToString());
                    }
                    entryInfo1.version        = (ushort)2;
                    entryInfo1.hashType       = NintendoContentArchiveSource.VerifyHashType(fileSystemInfo1, entryInfo1);
                    entryInfo1.encryptionType = NintendoContentArchiveSource.VerifyEncryptionType(fileSystemInfo1, entryInfo1);
                    string formatType = entryInfo1.formatType;
                    if (!(formatType == "PartitionFs"))
                    {
                        if (!(formatType == "RomFs"))
                        {
                            throw new NotImplementedException("invalid format .adf file. invalid formatType." + yamlMappingNode.ToString());
                        }
                        RomFsAdfReader romFsAdfReader = new RomFsAdfReader(adfPath);
                        entryInfo1.fileSystemInfo = (Nintendo.Authoring.FileSystemMetaLibrary.FileSystemInfo)romFsAdfReader.GetFileSystemInfo();
                    }
                    else
                    {
                        PartitionFileSystemInfo fileSystemInfo2 = new PartitionFsAdfReader(adfPath).GetFileSystemInfo();
                        if (numArray != null && entryInfo1.partitionType == "code")
                        {
                            IEnumerable <PartitionFileSystemInfo.EntryInfo> source = fileSystemInfo2.entries.Where <PartitionFileSystemInfo.EntryInfo>((Func <PartitionFileSystemInfo.EntryInfo, bool>)(p => p.name == "main.npdm"));
                            if (fileSystemInfo1.contentType == (byte)0 && source.Count <PartitionFileSystemInfo.EntryInfo>() != 1)
                            {
                                throw new ArgumentException("\"main.npdm\" must be included in the code region.");
                            }
                            foreach (PartitionFileSystemInfo.EntryInfo entryInfo2 in source)
                            {
                                if (!((IEnumerable <byte>) this.ReadAcid(entryInfo2.path)).SequenceEqual <byte>((IEnumerable <byte>)numArray))
                                {
                                    throw new ArgumentException(".desc file specified differ from the one used to build code.");
                                }
                            }
                        }
                        entryInfo1.fileSystemInfo = (Nintendo.Authoring.FileSystemMetaLibrary.FileSystemInfo)fileSystemInfo2;
                    }
                    fileSystemInfo1.fsEntries.Add(entryInfo1);
                }
            }
            fileSystemInfo1.numFsEntries     = fileSystemInfo1.fsEntries.Count;
            fileSystemInfo1.isProdEncryption = false;
            return(fileSystemInfo1);
        }
Ejemplo n.º 44
0
 public void ReadYamlStream(YamlStream yaml, FileInfo fileInfo)
 {
     ReadYamlStream(yaml,
                    fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read)
                    );
 }
Ejemplo n.º 45
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()));
            }
        }
Ejemplo n.º 46
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;
                }
                }
            }
        }
Ejemplo n.º 47
0
        public static async Task <PackageVersion> GetPackageVersion(string fullPath)
        {
            try
            {
                // Solution file: extract projects
                var solutionDirectory = Path.GetDirectoryName(fullPath) ?? "";
                var solution          = Xenko.Core.VisualStudio.Solution.FromFile(fullPath);

                foreach (var project in solution.Projects)
                {
                    // Xenko up to 3.0
                    try
                    {
                        string packagePath;
                        if (IsPackage(project, out packagePath))
                        {
                            var packageFullPath = Path.Combine(solutionDirectory, packagePath);

                            // 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);

                            if (yamlRootNode.Meta.Dependencies is DynamicYamlArray)
                            {
                                foreach (var dependency in yamlRootNode.Meta.Dependencies)
                                {
                                    if ((string)dependency.Name == "Xenko")
                                    {
                                        return(new PackageVersion((string)dependency.Version));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        e.Ignore();
                    }

                    // Xenko 3.1+
                    if (project.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharp || project.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharpNewSystem)
                    {
                        var projectPath = project.FullPath;
                        var packagePath = Path.ChangeExtension(projectPath, Package.PackageFileExtension);
                        if (File.Exists(packagePath))
                        {
                            var projectAssetsJsonPath = Path.Combine(Path.GetDirectoryName(projectPath), @"obj", LockFileFormat.AssetsFileName);
#if !XENKO_LAUNCHER
                            if (!File.Exists(projectAssetsJsonPath))
                            {
                                var log = new LoggerResult();
                                await VSProjectHelper.RestoreNugetPackages(log, projectPath);
                            }
#endif
                            if (File.Exists(projectAssetsJsonPath))
                            {
                                if (File.Exists(projectAssetsJsonPath))
                                {
                                    var format        = new LockFileFormat();
                                    var projectAssets = format.Read(projectAssetsJsonPath);
                                    foreach (var library in projectAssets.Libraries)
                                    {
                                        if (library.Type == "package" && library.Name == "Xenko.Engine")
                                        {
                                            return(new PackageVersion((string)library.Version.ToString()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.Ignore();
            }

            return(null);
        }
Ejemplo n.º 48
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.");
            }
        }
Ejemplo n.º 49
0
        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());
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Executes the framework using the given command line options.
        /// </summary>
        /// <param name="commandLineOptions">Command line options.</param>
        private 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 (var yamlNode in moduleListSequenceNode)
                        {
                            var moduleEntryNode = (YamlMappingNode)yamlNode;

                            // 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 != null && !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(FormatException(t.Exception));
                        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(FormatException(ex));

                    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 occurred:");

                    await Logger.LogErrorAsync(FormatException(ex));
                }
                else
                {
                    Console.WriteLine("A general error occured:");
                    Console.WriteLine(FormatException(ex));
                }
            }
            finally
            {
                // Make sure logger is disposed properly
                if (Logger.IsInitialized())
                {
                    Logger.Deinitialize();
                }
            }
        }
Ejemplo n.º 51
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
                }
                }
            }
        }
Ejemplo n.º 52
0
 public void ReadYamlStream(YamlStream yaml, Stream stream)
 {
     using var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, leaveOpen: true);
     yaml.Load(reader);
 }
Ejemplo n.º 53
0
        public RomFsFileSystemInfo GetFileSystemInfo()
        {
            RomFsFileSystemInfo fsFileSystemInfo = new RomFsFileSystemInfo();

            using (StreamReader streamReader = new StreamReader(this.m_adfPath, Encoding.UTF8))
            {
                YamlStream yamlStream = new YamlStream();
                yamlStream.Load((TextReader)streamReader);
                YamlMappingNode rootNode;
                try
                {
                    rootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;
                    if (((YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("formatType")]).Value != "RomFs")
                    {
                        throw new ArgumentException();
                    }
                }
                catch
                {
                    throw new ArgumentException("invalid format .adf file.");
                }
                YamlSequenceNode child;
                try
                {
                    child = (YamlSequenceNode)rootNode.Children[(YamlNode) new YamlScalarNode("entries")];
                }
                catch
                {
                    throw new ArgumentException("invalid format .adf file. At least one file must be included in the data region.");
                }
                DirectoryList directoryList = new DirectoryList();
                foreach (YamlMappingNode yamlMappingNode in child)
                {
                    RomFsFileSystemInfo.EntryInfo entryInfo = new RomFsFileSystemInfo.EntryInfo();
                    foreach (KeyValuePair <YamlNode, YamlNode> keyValuePair in yamlMappingNode)
                    {
                        string str = ((YamlScalarNode)keyValuePair.Key).Value;
                        if (!(str == "type"))
                        {
                            if (!(str == "name"))
                            {
                                if (!(str == "offset"))
                                {
                                    if (!(str == "path"))
                                    {
                                        throw new ArgumentException("invalid format .adf file. invalid key is specified\n" + yamlMappingNode.ToString());
                                    }
                                    entryInfo.path = ((YamlScalarNode)keyValuePair.Value).Value;
                                }
                                else
                                {
                                    entryInfo.offset = Convert.ToUInt64(((YamlScalarNode)keyValuePair.Value).Value);
                                }
                            }
                            else
                            {
                                entryInfo.name = "/" + ((YamlScalarNode)keyValuePair.Value).Value;
                            }
                        }
                        else
                        {
                            entryInfo.type = ((YamlScalarNode)keyValuePair.Value).Value;
                        }
                    }
                    if (entryInfo.type == null)
                    {
                        throw new ArgumentException("invalid format .adf file. invalid \"type\"\n" + yamlMappingNode.ToString());
                    }
                    if (entryInfo.type == "file" && (entryInfo.name == null || entryInfo.path == null))
                    {
                        throw new ArgumentException("invalid format .adf file. \"type == file\" but \"name\" or \"path\" is not specified.\n" + yamlMappingNode.ToString());
                    }
                    if (entryInfo.type == "directory" && entryInfo.name == null)
                    {
                        throw new ArgumentException("invalid format .adf file. \"type == directory\" but \"name\" is not specified.\n" + yamlMappingNode.ToString());
                    }
                    if (entryInfo.type == "file")
                    {
                        FileInfo fileInfo = new FileInfo(entryInfo.path);
                        entryInfo.size = (ulong)fileInfo.Length;
                        fsFileSystemInfo.entries.Add(entryInfo);
                        ++fsFileSystemInfo.fileEntryCount;
                        directoryList.AddAncestors(Path.GetDirectoryName(entryInfo.name));
                    }
                    else
                    {
                        if (!(entryInfo.type == "directory"))
                        {
                            throw new ArgumentException("invalid format .adf file. \"type\" should be \"directory\" or \"file\".\n" + yamlMappingNode.ToString());
                        }
                        fsFileSystemInfo.entries.Add(entryInfo);
                        directoryList.AddAncestors(entryInfo.name);
                    }
                }
                fsFileSystemInfo.directoryEntryCount = directoryList.Count;
            }
            return(fsFileSystemInfo);
        }
Ejemplo n.º 54
0
 public void WriteYamlStream(YamlStream yaml, string file)
 {
     using var stream = File.Open(file, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
     WriteYamlStream(yaml, stream);
 }
Ejemplo n.º 55
0
        public override async Task ExecuteAsync(OutputContext output, Application application, ServiceEntry service)
        {
            var bindings = service.Outputs.OfType <ComputedBindings>().FirstOrDefault();

            if (bindings is null)
            {
                return;
            }

            foreach (var binding in bindings.Bindings)
            {
                if (binding is SecretInputBinding secretInputBinding)
                {
                    if (!Secrets.Add(secretInputBinding.Name))
                    {
                        output.WriteDebugLine($"Already validated secret '{secretInputBinding.Name}'.");
                        continue;
                    }

                    output.WriteDebugLine($"Validating secret '{secretInputBinding.Name}'.");

                    var config = KubernetesClientConfiguration.BuildDefaultConfig();

                    // Workaround for https://github.com/kubernetes-client/csharp/issues/372
                    var store   = KubernetesClientConfiguration.LoadKubeConfig();
                    var context = store.Contexts.Where(c => c.Name == config.CurrentContext).FirstOrDefault();
                    config.Namespace ??= context?.ContextDetails?.Namespace;

                    var kubernetes = new Kubernetes(config);

                    try
                    {
                        var result = await kubernetes.ReadNamespacedSecretWithHttpMessagesAsync(secretInputBinding.Name, config.Namespace ?? "default");

                        output.WriteInfoLine($"Found existing secret '{secretInputBinding.Name}'.");
                        continue;
                    }
                    catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        // The kubernetes client uses exceptions for 404s.
                    }
                    catch (Exception ex)
                    {
                        output.WriteDebugLine("Failed to query secret.");
                        output.WriteDebugLine(ex.ToString());
                        throw new CommandException("Unable connect to kubernetes.", ex);
                    }

                    if (Force)
                    {
                        output.WriteDebugLine("Skipping because force was specified.");
                        continue;
                    }

                    if (!Interactive)
                    {
                        throw new CommandException(
                                  $"The secret '{secretInputBinding.Name}' used for service '{secretInputBinding.Service.Service.Name}' is missing from the deployment environment. " +
                                  $"Rerun the command with --interactive to specify the value interactively, or with --force to skip validation. Alternatively " +
                                  $"use the following command to manually create the secret." + System.Environment.NewLine +
                                  $"kubectl create secret generic {secretInputBinding.Name} --from-literal=connectionstring=<value>");
                    }

                    // If we get here then we should create the sceret.
                    var text = output.Prompt($"Enter the connection string to use for service '{secretInputBinding.Service.Service.Name}'", allowEmpty: true);
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        output.WriteAlways($"Skipping creation of secret for '{secretInputBinding.Service.Service.Name}'. This may prevent creation of pods until secrets are created.");
                        output.WriteAlways($"Manually create a secret with:");
                        output.WriteAlways($"kubectl create secret generic {secretInputBinding.Name} --from-literal=connectionstring=<value>");
                        continue;
                    }

                    var secret = new V1Secret(type: "Opaque", stringData: new Dictionary <string, string>()
                    {
                        { "connectionstring", text },
                    });
                    secret.Metadata      = new V1ObjectMeta();
                    secret.Metadata.Name = secretInputBinding.Name;

                    output.WriteDebugLine($"Creating secret '{secret.Metadata.Name}'.");

                    try
                    {
                        await kubernetes.CreateNamespacedSecretWithHttpMessagesAsync(secret, config.Namespace ?? "default");

                        output.WriteInfoLine($"Created secret '{secret.Metadata.Name}'.");
                    }
                    catch (Exception ex)
                    {
                        output.WriteDebugLine("Failed to create secret.");
                        output.WriteDebugLine(ex.ToString());
                        throw new CommandException("Failed to create secret.", ex);
                    }
                }
            }

            var yaml = service.Outputs.OfType <IYamlManifestOutput>().ToArray();

            if (yaml.Length == 0)
            {
                output.WriteDebugLine($"No yaml manifests found for service '{service.FriendlyName}'. Skipping.");
                return;
            }

            using var tempFile = TempFile.Create();
            output.WriteDebugLine($"Writing output to '{tempFile.FilePath}'.");

            {
                using var stream = File.OpenWrite(tempFile.FilePath);
                using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: -1, leaveOpen: true);
                var yamlStream = new YamlStream(yaml.Select(y => y.Yaml));
                yamlStream.Save(writer, assignAnchors: false);
            }

            // kubectl apply logic is implemented in the client in older versions of k8s. The capability
            // to get the same behavior in the server isn't present in every version that's relevant.
            //
            // https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply
            //
            output.WriteDebugLine("Running 'kubectl apply'.");
            output.WriteCommandLine("kubectl", $"apply -f \"{tempFile.FilePath}\"");
            var capture  = output.Capture();
            var exitCode = await Process.ExecuteAsync(
                $"kubectl",
                $"apply -f \"{tempFile.FilePath}\"",
                System.Environment.CurrentDirectory,
                stdOut : capture.StdOut,
                stdErr : capture.StdErr);

            output.WriteDebugLine($"Done running 'kubectl apply' exit code: {exitCode}");
            if (exitCode != 0)
            {
                throw new CommandException("'kubectl apply' failed.");
            }

            output.WriteInfoLine($"Deployed service '{service.FriendlyName}'.");
        }
Ejemplo n.º 56
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")]
                        );
                }
            }
        }
Ejemplo n.º 57
0
        public static bool TryDeserialize(YamlStream yamlStream, out DeserializedInfo deserializedInfo)
        {
            if (yamlStream == null)
            {
                deserializedInfo = null;
                return(false);
            }

            var mapping      = (YamlMappingNode)yamlStream.Documents[0].RootNode;
            var tool         = new Tool();
            var publications = new List <Publication>();

            foreach (var entry in mapping.Children)
            {
                switch (entry.Key.ToString())
                {
                case "package":
                    foreach (var child in ((YamlMappingNode)entry.Value).Children)
                    {
                        if (child.Key.ToString() == "name")
                        {
                            tool.Name = child.Value.ToString();
                            break;
                        }
                    }
                    break;

                case "source":
                    if (entry.Value.GetType() == typeof(YamlMappingNode))
                    {
                        foreach (var child in ((YamlMappingNode)entry.Value).Children)
                        {
                            if (child.Key.ToString() == "url")
                            {
                                tool.CodeRepo = child.Value.ToString();
                                break;
                            }
                        }
                    }
                    else if (entry.Value.GetType() == typeof(YamlSequenceNode))
                    {
                        foreach (YamlMappingNode child in ((YamlSequenceNode)entry.Value).Children)
                        {
                            foreach (var c in child.Children)
                            {
                                if (c.Key.ToString() == "url")
                                {
                                    tool.CodeRepo = c.Value.ToString();
                                    break;
                                }
                            }
                        }
                    }
                    break;

                case "extra":
                    foreach (var child in ((YamlMappingNode)entry.Value).Children)
                    {
                        if (child.Key.ToString() == "identifiers")
                        {
                            foreach (var x in ((YamlSequenceNode)child.Value).Children)
                            {
                                if (x.ToString().StartsWith("doi:", StringComparison.OrdinalIgnoreCase))
                                {
                                    publications.Add(new Publication()
                                    {
                                        DOI = x.ToString().Split(':')[1]
                                    });
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
            }

            deserializedInfo = new DeserializedInfo
            {
                ToolRepoAssociation = new ToolRepoAssociation()
                {
                    Tool = tool
                }
            };
            deserializedInfo.PopulateToolPublicationAssociations(publications);
            return(true);
        }
Ejemplo n.º 58
0
 /// <summary>
 /// Called when this object is visiting a <see cref="YamlStream"/>.
 /// </summary>
 /// <param name="stream">
 /// The <see cref="YamlStream"/> that is being visited.
 /// </param>
 public virtual void Visit(YamlStream stream)
 {
     VisitChildren(stream);
 }
Ejemplo n.º 59
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);
            }
        }
Ejemplo n.º 60
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);
    }