Пример #1
0
        private static void HandleServiceEnvFile(YamlScalarNode yamlScalarNode, string[] envLines, List <ConfigConfigurationSource> configuration)
        {
            foreach (var line in envLines)
            {
                var lineTrim = line?.Trim();
                if (string.IsNullOrEmpty(lineTrim) || lineTrim[0] == '#')
                {
                    continue;
                }

                var keyValueSeparator = lineTrim.IndexOf('=');

                if (keyValueSeparator == -1)
                {
                    throw new TyeYamlException(yamlScalarNode.Start, CoreStrings.FormatExpectedEnvironmentVariableValue(lineTrim));
                }

                configuration.Add(new ConfigConfigurationSource
                {
                    Name  = lineTrim.Substring(0, keyValueSeparator).Trim(),
                    Value = lineTrim.Substring(keyValueSeparator + 1)?.Trim(new[] { ' ', '"' }) ?? string.Empty
                });
            }
        }
Пример #2
0
        /// <summary>
        /// Gets a scalar value identified by its key
        /// </summary>
        /// <param name="parent">Parent node</param>
        /// <param name="key">Key of the value</param>
        /// <param name="errorMessage">Error message if the key does not exists</param>
        /// <returns>Returns the scalar value</returns>
        public string GetScalarValue(YamlNode parent, string key, string errorMessage = null)
        {
            Contract.Requires(parent != null);
            Contract.Requires(key != null);
            Contract.Ensures(Contract.Result <string>() != null);

            try
            {
                var mapping = (YamlMappingNode)parent;
                var pairs   = EnumerateNodesOf(mapping);
                var keyNode = new YamlScalarNode(key);

                foreach (var pair in pairs)
                {
                    if (keyNode.Equals(pair.Key))
                    {
                        if (pair.Value is YamlScalarNode)
                        {
                            var v = ((YamlScalarNode)pair.Value).Value;
                            if (v != null)
                            {
                                return(v);
                            }
                        }

                        throw new InvalidSpecificationException(errorMessage ?? String.Format("No value for key {0}", key));
                    }
                }

                throw new InvalidSpecificationException(String.Format("Parent has no child with key {0}", key));
            }
            catch (Exception ex)
            {
                throw new InvalidSpecificationException(errorMessage ?? ex.Message, ex);
            }
        }
Пример #3
0
        private static bool IsNull(YamlScalarNode scalar)
        {
            if (string.IsNullOrEmpty(scalar.Value))
            {
                return(true);
            }

            if (string.Equals(scalar.Tag, "tag:yaml.org,2002:null", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            if (string.Equals(scalar.Value, "null", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            if (string.Equals(scalar.Value, "~", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            return(false);
        }
Пример #4
0
        // --------- Loaders --------

        private void ApplyConversationIDs()
        {
            string mainFile = directory + @"\main.yml";

            YamlStream      mainStream;
            YamlMappingNode mainRoot;

            using (StringReader mainReader = new StringReader(File.ReadAllText(mainFile)))
            {
                mainStream = new YamlStream();
                mainStream.Load(mainReader);

                if (mainStream.Documents.Count != 0)
                {
                    mainRoot = (YamlMappingNode)mainStream.Documents[0].RootNode;

                    foreach (var mainOption in mainRoot.Children)
                    {
                        YamlScalarNode option = mainOption.Key as YamlScalarNode;
                        if (option.Value.Equals("npcs", StringComparison.InvariantCultureIgnoreCase))
                        {
                            YamlMappingNode npcs = mainOption.Value as YamlMappingNode;
                            foreach (var npc in npcs.Children)
                            {
                                YamlScalarNode npcIDNode   = npc.Key as YamlScalarNode;
                                YamlScalarNode npcFileName = npc.Value as YamlScalarNode;
                                int            npcID       = int.Parse(npcIDNode.Value);

                                Conversation conversation = conversationsFiles[npcFileName.Value];
                                conversation.NPCID = npcID;
                            }
                        }
                    }
                }
            }
        }
Пример #5
0
        public void TestSerializeYaml()
        {
            //string fr = File.ReadAllText(fullpath);

            //StreamReader reader = new StreamReader("f:/generated/UnitTest/APITitle.raml");
            //YamlStream stream = new YamlStream();
            //stream.Load(reader);

            YamlScalarNode node = new YamlScalarNode("!include foo.raml");

            node.Style = ScalarStyle.Raw;
            //node.Tag = "tag:yaml.org,2002:null";

            //node.Value = "!includ2 foo2.raml";
            //node.Anchor = "!include";

            YamlMappingNode map = new YamlMappingNode();
            ////map.Style = YamlDotNet.Core.Events.MappingStyle.Flow;

            YamlSequenceNode seq = new YamlSequenceNode();

            //seq.Add(node);

            map.Add("api", node);

            YamlStream   stream = new YamlStream();
            YamlDocument doc    = new YamlDocument(map);

            stream.Documents.Add(doc);

            StringWriter writer = new StringWriter();

            stream.Save(writer);

            string yaml = writer.ToString();
        }
Пример #6
0
        private static object ToExpandoImpl(YamlNode node, StringComparer comparer, ExpandoObject exp = null)
        {
            YamlScalarNode   scalar   = node as YamlScalarNode;
            YamlMappingNode  mapping  = node as YamlMappingNode;
            YamlSequenceNode sequence = node as YamlSequenceNode;

            if (scalar != null)
            {
                return(scalar.Value);
            }
            else if (mapping != null)
            {
                exp = new ExpandoObject();
                foreach (KeyValuePair <YamlNode, YamlNode> child in mapping.Children)
                {
                    YamlScalarNode keyNode = (YamlScalarNode)child.Key;
                    string         keyName = keyNode.Value;
                    object         val     = ToExpandoImpl(child.Value, comparer);
                    exp.SetProperty(keyName, val);
                }
                return(exp);
            }
            else if (sequence != null)
            {
                var childNodes = new List <object>();
                foreach (YamlNode child in sequence.Children)
                {
                    var    childExp = new ExpandoObject();
                    object childVal = ToExpandoImpl(child, comparer, childExp);
                    childNodes.Add(childVal);
                }
                return(childNodes);
            }

            return(exp);
        }
Пример #7
0
        private static Config AddToConfig(YamlNode yamlNode, Config parent)
        {
            Config node = new Config();
            if (yamlNode is YamlMappingNode)
            {
                YamlMappingNode mapping = yamlNode as YamlMappingNode;
                node.Children = new List<Config>();
                foreach (var child in mapping.Children)
            #if DEBUG
                    if (child.Key is YamlScalarNode)
            #endif
                        AddToConfig(child.Value, node).Name = (child.Key as YamlScalarNode).Value;
            #if DEBUG
                    else // going on the assumption that a Key is *always* a string. Can't wrap my head around how it wouldn't be.
                        throw new InvalidCastException("YamlMappingNode's key is NOT a YamlScalarNode: " + child.Key.GetType().FullName);
            #endif
            }
            else if (yamlNode is YamlSequenceNode)
            {
                YamlSequenceNode sequence = yamlNode as YamlSequenceNode;
                node.Children = new List<Config>();
                foreach( var child in sequence.Children )
                    AddToConfig(child, node);
            }
            else if (yamlNode is YamlScalarNode)
            {
                YamlScalarNode scalar = yamlNode as YamlScalarNode;
                node.Value = scalar.Value;
            }
            else
                throw new InvalidCastException("Unrecognised YamlNode type: " + yamlNode.GetType().FullName);

            if ( parent != null )
                parent.Children.Add(node);
            return node;
        }
Пример #8
0
 void IYamlVisitor.Visit(YamlScalarNode scalar)
 {
     Visit(scalar);
     Visited(scalar);
 }
Пример #9
0
 protected override void Visit(YamlScalarNode scalar)
 {
     WriteIndent();
     Console.WriteLine("Visit(YamlScalarNode, {0}, {1}) - {2}", scalar.Anchor, scalar.Tag, scalar.Value);
     ++indent;
 }
Пример #10
0
 public ValueNode(ParsingContext context, OpenApiDiagnostic diagnostic, YamlScalarNode scalarNode) : base(
         context,
         diagnostic)
 {
     _node = scalarNode;
 }
Пример #11
0
 public override void Visit(YamlScalarNode scalar)
 {
     LineClass.OutputLine = bool.Parse(scalar.Value);
 }
Пример #12
0
        internal void MergeNamespaceIntoToc(YamlSequenceNode toc)
        {
            bool MatchByUid(YamlNode n, string key)
            {
                var uid = new YamlScalarNode(this.uid);

                if (n is YamlMappingNode map)
                {
                    if (map.Children != null && map.Children.TryGetValue(new YamlScalarNode(Utils.UidKey), out YamlNode node))
                    {
                        if (node is YamlScalarNode valueNode)
                        {
                            return(valueNode.Equals(uid));
                        }
                    }
                }
                return(false);
            }

            string?TryGetUid(YamlNode node)
            {
                if (node is YamlMappingNode mappingNode)
                {
                    mappingNode.Children.TryGetValue(Utils.UidKey, out var uidNode);
                    return((uidNode as YamlScalarNode)?.Value);
                }
                else
                {
                    return(null);
                }
            }

            int CompareUids(YamlNode node1, YamlNode node2) =>
            String.Compare(
                TryGetUid(node1),
                TryGetUid(node2)
                );

            var namespaceNode             = toc.Children?.SingleOrDefault(c => MatchByUid(c, this.uid)) as YamlMappingNode;
            YamlSequenceNode?itemListNode = null;

            if (namespaceNode == null)
            {
                namespaceNode = new YamlMappingNode();
                namespaceNode.AddStringMapping(Utils.UidKey, this.uid);
                namespaceNode.AddStringMapping(Utils.NameKey, this.name);
                toc.Add(namespaceNode);
                toc.Children.Sort((node1, node2) => CompareUids(node1, node2));
            }
            else
            {
                YamlNode itemsNode;
                if (namespaceNode.Children.TryGetValue(new YamlScalarNode(Utils.ItemsKey), out itemsNode))
                {
                    itemListNode = itemsNode as YamlSequenceNode;
                }
            }
            if (itemListNode == null)
            {
                itemListNode = new YamlSequenceNode();
                namespaceNode.Add(Utils.ItemsKey, itemListNode);
            }

            foreach (var item in items)
            {
                if (!itemListNode.Children.Any(c => MatchByUid(c, item.Uid)))
                {
                    itemListNode.Add(Utils.BuildMappingNode(Utils.NameKey, item.Name, Utils.UidKey, item.Uid));
                }
            }

            itemListNode.Children.Sort((node1, node2) => CompareUids(node1, node2));
        }
Пример #13
0
 private void VisitYamlSequenceNode(YamlScalarNode yamlNodeKey, YamlSequenceNode yamlNodeValue)
 {
     EnterContext(yamlNodeKey.Value);
     VisitYamlSequenceNode(yamlNodeValue);
     ExitContext();
 }
Пример #14
0
        static YamlMappingNode reifyMethod(EA.Repository Repository, EA.Element e, EA.Connector con, EA.Element client)
        {
            logger.log("Reify Method:" + e.Name);
            YamlMappingNode methodProps = new YamlMappingNode();

            String description = "";

            if (e.Notes != null && e.Notes.Length > 0)
            {
                description = e.Notes;
            }


            YamlSequenceNode pms = new YamlSequenceNode();

            visitOutboundConnectedElements(Repository, e, pms, MetaDataManager.filterPermission, namePermission, reifyPermission);
            foreach (YamlNode node in pms.Children)
            {
                YamlScalarNode pn         = (YamlScalarNode)node;
                String         permission = pn.ToString();
                if (REIFY_VERSION == APIAddinClass.RAML_0_8)
                {
                    description += APIAddinClass.MARKDOWN_PARAGRAPH_BREAK + "The permission[" + permission + "] is required to invoke this method.";
                }
                else
                {
                    methodProps.Add("(extensions.permission)", permission);
                }
            }

            methodProps.Add("description", description);

            Dictionary <string, RunState> rs = ObjectManager.parseRunState(e.RunState);

            foreach (string key in rs.Keys)
            {
                try
                {
                    methodProps.Add(key, rs[key].value);
                }
                catch (Exception)
                {
                    //ignore on purpose
                }
            }


            //YamlMappingNode responses = new YamlMappingNode();
            //visitOutboundConnectedElements(Repository, e, responses, MetaDataManager.filterResponse, nameOfTargetElement, reifyResponse);
            //if (responses.Children.Count > 0)
            //{
            //    methodProps.Add("responses", responses);
            //}

            YamlMappingNode queryParameters = new YamlMappingNode();

            visitOutboundConnectedElements(Repository, e, queryParameters, MetaDataManager.filterQueryParameter, nameOfTargetElement, reifyQueryParameter);
            if (queryParameters.Children.Count > 0)
            {
                methodProps.Add("queryParameters", queryParameters);
            }

            //YamlMappingNode contentTypes = new YamlMappingNode();
            //visitOutboundConnectedElements(Repository, e, contentTypes, MetaDataManager.filterContentType, nameOfTargetElement, reifyContentType);
            //if (contentTypes.Children.Count > 0)
            //{
            //    methodProps.Add("body", contentTypes);
            //}

            if (REIFY_VERSION > APIAddinClass.RAML_0_8)
            {
                logger.log("Reify Examples");
                YamlMappingNode responseExamples = new YamlMappingNode();
                visitOutboundConnectedElements(Repository, e, responseExamples, MetaDataManager.filterResponseExample, nameOfTargetElement, reifyExamples);
                logger.log("Reify Response Examples:" + responseExamples.Children.Count);
                if (responseExamples.Children.Count > 0)
                {
                    YamlMappingNode responses = new YamlMappingNode();
                    methodProps.Add("responses", responses);

                    YamlMappingNode status = new YamlMappingNode();
                    responses.Add("200", status);

                    YamlMappingNode body = new YamlMappingNode();
                    status.Add("body", body);

                    YamlMappingNode contenttype = new YamlMappingNode();
                    body.Add("application/json", contenttype);


                    YamlMappingNode exampleMap = new YamlMappingNode();
                    contenttype.Add("examples", exampleMap);
                    foreach (KeyValuePair <YamlNode, YamlNode> kp in responseExamples)
                    {
                        exampleMap.Add(kp.Key, kp.Value);
                    }
                }

                YamlMappingNode requestExamples = new YamlMappingNode();
                visitOutboundConnectedElements(Repository, e, requestExamples, MetaDataManager.filterRequestExample, nameOfTargetElement, reifyExamples);
                if (requestExamples.Children.Count > 0)
                {
                    YamlMappingNode body = new YamlMappingNode();
                    methodProps.Add("body", body);

                    YamlMappingNode contenttype = new YamlMappingNode();
                    body.Add("application/json", contenttype);

                    YamlMappingNode exampleMap = new YamlMappingNode();
                    contenttype.Add("examples", exampleMap);
                    foreach (KeyValuePair <YamlNode, YamlNode> kp in requestExamples)
                    {
                        exampleMap.Add(kp.Key, kp.Value);
                    }
                }
            }

            String           traits    = "[";
            YamlSequenceNode traitsMap = new YamlSequenceNode();

            visitOutboundConnectedElements(Repository, e, traitsMap, MetaDataManager.filterTrait, nameTrait, reifyTrait);
            if (traitsMap.Children.Count > 0)
            {
                foreach (YamlNode node in traitsMap.Children)
                {
                    YamlScalarNode sn    = (YamlScalarNode)node;
                    String         trait = sn.ToString();
                    traits += trait + ",";
                }
                traits  = traits.Substring(0, traits.Length - 1);
                traits += "]";
                YamlScalarNode traitNode = new YamlScalarNode(traits);
                traitNode.Style = ScalarStyle.Raw;
                methodProps.Add("is", traitNode);
            }
            return(methodProps);
        }
Пример #15
0
 /// <summary>
 /// Called when this object is visiting a <see cref="YamlScalarNode"/>.
 /// </summary>
 /// <param name="scalar">
 /// The <see cref="YamlScalarNode"/> that is being visited.
 /// </param>
 public virtual void Visit(YamlScalarNode scalar)
 {
     // Do nothing.
 }
Пример #16
0
        static YamlNode reifySecurity(EA.Repository Repository, EA.Element e, EA.Connector con, EA.Element client)
        {
            logger.log("Reify Security:" + e.Name + "-" + e.Version);

            Dictionary <string, RunState> rs = ObjectManager.parseRunState(e.RunState);

            // If security element is defined with no run state then include security definition from version value
            if (rs.Count == 0)
            {
                YamlScalarNode security = null;
                if (REIFY_VERSION == APIAddinClass.RAML_0_8)
                {
                    security = new YamlScalarNode("!include " + e.Version + ".raml");
                }
                else
                {
                    security = new YamlScalarNode("!include " + e.Version + ".1_0.raml");
                }
                security.Style = ScalarStyle.Raw;
                return(security);
            }
            else
            {
                // Security schemes is a sequence in RAML
                YamlSequenceNode security = new YamlSequenceNode();

                // Security scheme attributes as a map
                YamlMappingNode securityObject = new YamlMappingNode();
                security.Add(securityObject);
                YamlMappingNode securityAttributes = new YamlMappingNode();
                securityObject.Add(e.Name, securityAttributes);

                // Add security scheme attributes
                // The element classifier type must match securedBy in traits
                foreach (string key in rs.Keys)
                {
                    YamlScalarNode securityAttribute = new YamlScalarNode(rs[key].value);
                    securityAttribute.Style = ScalarStyle.Raw;
                    securityAttributes.Add(key, securityAttribute);
                }

                // Get any settings or other attributes from connectors and add as a map from run state
                foreach (EA.Connector connector in e.Connectors)
                {
                    EA.Element element = Repository.GetElementByID(connector.SupplierID);
                    logger.log("Reify Security Attrib:" + element.Name);
                    if (element.Name != e.Name) //Not sure why there is a self reference here but avoiding it.
                    {
                        YamlMappingNode connectorNode = new YamlMappingNode();
                        securityAttributes.Add(element.Name, connectorNode);
                        Dictionary <string, RunState> elementRS = ObjectManager.parseRunState(element.RunState);
                        foreach (string key in elementRS.Keys)
                        {
                            YamlScalarNode securityObjectAttribute = new YamlScalarNode(elementRS[key].value);
                            securityObjectAttribute.Style = ScalarStyle.Raw;
                            connectorNode.Add(key, securityObjectAttribute);
                        }
                    }
                }
                return(security);
            }
        }
Пример #17
0
        public static object?ToObject(this YamlScalarNode node, Type valueType, object?parent)
        {
            _ = valueType ??
                throw new NetDaemonArgumentNullException(nameof(valueType));
            _ = node ??
                throw new NetDaemonArgumentNullException(nameof(node));

            Type?underlyingNullableType = Nullable.GetUnderlyingType(valueType);

            if (underlyingNullableType != null)
            {
                // It is nullable type
                valueType = underlyingNullableType;
            }

            switch (valueType.Name)
            {
            case "String":
                return(node.Value);

            case "Int32":
                if (int.TryParse(node.Value, NumberStyles.Number,
                                 CultureInfo.InvariantCulture, out int i32Value))
                {
                    return(i32Value);
                }

                break;

            case "Int64":
                if (long.TryParse(node.Value, NumberStyles.Number,
                                  CultureInfo.InvariantCulture, out long i64Value))
                {
                    return(i64Value);
                }

                break;

            case "Decimal":
                if (decimal.TryParse(node.Value, NumberStyles.Number,
                                     CultureInfo.InvariantCulture, out decimal decimalValue))
                {
                    return(decimalValue);
                }

                break;

            case "Single":
                if (float.TryParse(node.Value, NumberStyles.Number,
                                   CultureInfo.InvariantCulture, out float floatValue))
                {
                    return(floatValue);
                }

                break;

            case "Double":
                if (double.TryParse(node.Value, NumberStyles.Number,
                                    CultureInfo.InvariantCulture, out double doubleValue))
                {
                    return(doubleValue);
                }

                break;

            case "Boolean":
                if (bool.TryParse(node.Value, out bool boolValue))
                {
                    return(boolValue);
                }

                break;
            }

            if (valueType.IsAssignableTo(typeof(RxEntityBase)))
            {
                var instance = Activator.CreateInstance(valueType, parent, new[] { node.Value });
                return(instance);
            }
            return(null);
        }
Пример #18
0
        static YamlNode reifyTypeForResource(EA.Repository Repository, EA.Element e, EA.Connector con, EA.Element client)
        {
            YamlMappingNode specificType = new YamlMappingNode();


            {
                YamlScalarNode node = new YamlScalarNode("infoSchema");
                node.Style = ScalarStyle.Raw;
                specificType.Add("infoSchema", node);
            }

            if (e.Name.Equals(APIAddinClass.RESOURCETYPE_ITEMPOST) || e.Name.Equals(APIAddinClass.RESOURCETYPE_ITEMPOST_ONEWAY) || e.Name.Equals(APIAddinClass.RESOURCETYPE_COLLECTIONGETPOST))
            {
                YamlScalarNode node = new YamlScalarNode("infoSchema");
                node.Style = ScalarStyle.Raw;
                specificType.Add("postInfoSchema", node);
            }

            logger.log("Reify Type for Resource:" + e.Name);
            visitOutboundConnectedElements(Repository, e, specificType, MetaDataManager.filterClass, nameSupplierRole, reifyTypeReference);

            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample400BadRequest-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample400Resp", node);
            }
            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample401-Unauthorized-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample401Resp", node);
            }
            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample403-Forbidden-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample403Resp", node);
            }


            if (!e.Name.Equals(APIAddinClass.RESOURCETYPE_ITEMPOST_SYNC) && !e.Name.Equals(APIAddinClass.RESOURCETYPE_ITEMPOST_ONEWAY))
            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample404Resp-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample404Resp", node);
            }
            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample405-MethodNotAllowed-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample405Resp", node);
            }
            {
                YamlScalarNode node = new YamlScalarNode("!include samples/sample406-NotAcceptable-sample.json");
                node.Style = ScalarStyle.Raw;
                specificType.Add("sample406Resp", node);
            }


            visitOutboundConnectedElements(Repository, e, specificType, MetaDataManager.filterObject, nameSupplierRole, reifyTypeSample);

            logger.log("End Reify Type for Resource:" + e.Name);
            return(specificType);
        }
        static YamlNode SaveNode(string name, dynamic node)
        {
            if (node == null)
            {
                return(new YamlScalarNode("null"));
            }
            else if (IsReferenceNode(node))
            {
                if (NodePaths[node].Tag == null)
                {
                    NodePaths[node].Tag = $"!ref{refNodeId++}";
                }
                return(new YamlScalarNode($"!refTag={NodePaths[node].Tag}"));
            }
            else if ((node is IList <dynamic>))
            {
                var yamlNode = new YamlSequenceNode();
                //  NodePaths.Add(node, yamlNode);

                if (!HasEnumerables((IList <dynamic>)node) &&
                    ((IList <dynamic>)node).Count < 6)
                {
                    yamlNode.Style = SharpYaml.YamlStyle.Flow;
                }

                foreach (var item in (IList <dynamic>)node)
                {
                    yamlNode.Add(SaveNode(null, item));
                }

                return(yamlNode);
            }
            else if (node is IDictionary <string, dynamic> )
            {
                var yamlNode = new YamlMappingNode();
                //  NodePaths.Add(node, yamlNode);

                if (!HasEnumerables((IDictionary <string, dynamic>)node) &&
                    ((IDictionary <string, dynamic>)node).Count < 6)
                {
                    yamlNode.Style = SharpYaml.YamlStyle.Flow;
                }

                foreach (var item in (IDictionary <string, dynamic>)node)
                {
                    string   key     = item.Key;
                    YamlNode keyNode = new YamlScalarNode(key);
                    if (BYAML.IsHash(key))
                    {
                        uint hash = Convert.ToUInt32(key, 16);
                        if (BYAML.Hashes.ContainsKey(hash))
                        {
                            key = $"{BYAML.Hashes[hash]}";
                        }

                        keyNode     = new YamlScalarNode(key);
                        keyNode.Tag = "!h";
                    }
                    yamlNode.Add(keyNode, SaveNode(item.Key, item.Value));
                }
                return(yamlNode);
            }
            else if (node is ByamlPathPoint)
            {
                return(ConvertPathPoint((ByamlPathPoint)node));
            }
            else if (node is List <ByamlPathPoint> )
            {
                var yamlNode = new YamlSequenceNode();
                foreach (var pt in (List <ByamlPathPoint>)node)
                {
                    yamlNode.Add(ConvertPathPoint(pt));
                }
                return(yamlNode);
            }
            else
            {
                string tag = null;
                if (node is int)
                {
                    tag = "!l";
                }
                else if (node is uint)
                {
                    tag = "!u";
                }
                else if (node is Int64)
                {
                    tag = "!ul";
                }
                else if (node is double)
                {
                    tag = "!d";
                }
                else if (node is ByamlPathIndex)
                {
                    tag = "!p";
                }

                var yamlNode = new YamlScalarNode(ConvertValue(node));
                if (tag != null)
                {
                    yamlNode.Tag = tag;
                }
                return(yamlNode);
            }
        }
Пример #20
0
        /// <summary>
        /// cTor.
        /// </summary>
        /// <param name="fullpath">path+file+extension of MapTilesets.yml</param>
        public TilesetManager(string fullpath)
        {
            //LogFile.WriteLine("");
            //LogFile.WriteLine("TilesetManager cTor");

            // TODO: if exists(fullpath)
            // else error out.

            var progress = ProgressBarForm.Instance;

            progress.SetInfo("Parsing MapTilesets ...");

            var typeCount = 0;             // TODO: optimize the reading (here & below) into a buffer.

            using (var reader = File.OpenText(fullpath))
            {
                string line = String.Empty;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains("- type"))
                    {
                        ++typeCount;
                    }
                }
            }
            progress.SetTotal(typeCount);


            bool isUfoConfigured  = !String.IsNullOrEmpty(SharedSpace.Instance.GetShare(SharedSpace.ResourceDirectoryUfo));
            bool isTftdConfigured = !String.IsNullOrEmpty(SharedSpace.Instance.GetShare(SharedSpace.ResourceDirectoryTftd));

            using (var sr = new StreamReader(File.OpenRead(fullpath)))
            {
                var str = new YamlStream();
                str.Load(sr);

                var nodeRoot = str.Documents[0].RootNode as YamlMappingNode;
//				foreach (var node in nodeRoot.Children) // parses YAML document divisions, ie "---"
//				{
                //LogFile.WriteLine(". node.Key(ScalarNode)= " + (YamlScalarNode)node.Key); // "tilesets"

                var nodeTilesets = nodeRoot.Children[new YamlScalarNode("tilesets")] as YamlSequenceNode;
                foreach (YamlMappingNode nodeTileset in nodeTilesets)                 // iterate over all the tilesets
                {
                    //LogFile.WriteLine(". . tileset= " + tileset); // lists all data in the tileset

                    // IMPORTANT: ensure that tileset-labels (ie, type) and terrain-labels
                    // (ie, terrains) are stored and used only as UpperCASE strings.


                    string nodeGroup = nodeTileset.Children[new YamlScalarNode("group")].ToString();
                    //LogFile.WriteLine(". . group= " + nodeGroup); // eg. "ufoShips"

                    if ((!isUfoConfigured && nodeGroup.StartsWith("ufo", StringComparison.OrdinalIgnoreCase)) ||
                        (!isTftdConfigured && nodeGroup.StartsWith("tftd", StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    if (!Groups.Contains(nodeGroup))
                    {
                        Groups.Add(nodeGroup);
                    }


                    string nodeCategory = nodeTileset.Children[new YamlScalarNode("category")].ToString();
                    //LogFile.WriteLine(". . category= " + nodeCategory); // eg. "Ufo"

                    string nodeLabel = nodeTileset.Children[new YamlScalarNode("type")].ToString();
                    nodeLabel = nodeLabel.ToUpperInvariant();
                    //LogFile.WriteLine(". . type= " + nodeLabel); // eg. "UFO_110"

                    var terrainList = new List <string>();

                    var nodeTerrains = nodeTileset.Children[new YamlScalarNode("terrains")] as YamlSequenceNode;
                    foreach (YamlScalarNode nodeTerrain in nodeTerrains)
                    {
                        //LogFile.WriteLine(". . . terrain= " + nodeTerrain); // eg. "U_EXT02" etc.

                        string terrain = nodeTerrain.ToString();
                        terrain = terrain.ToUpperInvariant();

                        terrainList.Add(terrain);
                    }


                    string nodeBasepath = String.Empty;
                    var    basepath     = new YamlScalarNode("basepath");
                    if (nodeTileset.Children.ContainsKey(basepath))
                    {
                        nodeBasepath = nodeTileset.Children[basepath].ToString();
                        //LogFile.WriteLine(". . basepath= " + nodeBasepath);
                    }
                    //else LogFile.WriteLine(". . basepath not found.");


                    var tileset = new Tileset(
                        nodeLabel,
                        nodeGroup,
                        nodeCategory,
                        terrainList,
                        nodeBasepath);
                    Tilesets.Add(tileset);

                    progress.UpdateProgress();
                }
            }
            progress.Hide();
        }
Пример #21
0
        void YdnItemImport(string fileLocation)
        {
            //get input file
            StreamReader file = new StreamReader(fileLocation);
            YamlStream   yaml = new YamlStream();

            yaml.Load(file);

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

            foreach (var entry in map.Children)
            {
                //create all the values that an item needs
                int blueprintID         = 0,
                         copyTime       = -1,
                         METime         = -1,
                         TETime         = -1,
                         prodLmt        = -1,
                         itemID         = 0,
                         productionQty  = 1,
                         productionTime = 0,
                         invID          = 0,
                         invQty         = 1,
                         invTime        = 0;
                int[,] prodMats = new int[20, 2],
                invMats         = new int[6, 2],
                copyMats        = new int[5, 2],
                prodskills      = new int[8, 2],
                MEskills        = new int[8, 2],
                TEskills        = new int[8, 2],
                copyskills      = new int[5, 2];
                float invProb = 0f;

                blueprintID = Int32.Parse(((YamlScalarNode)entry.Key).Value);
                var currentEntry = (YamlMappingNode)map.Children[entry.Key];

                foreach (var item in currentEntry)
                {
                    if ((item.Key).ToString() == "activities")
                    {
                        YamlMappingNode activities = (YamlMappingNode)currentEntry.Children[(new YamlScalarNode("activities"))];

                        //skip current item if it is empty
                        if (activities == null)
                        {
                            continue;
                        }

                        //start grabbing data from the item
                        YamlMappingNode currentActivity;
                        foreach (var activity in activities)
                        {
                            //var currentActivity = activity.Value as YamlMappingNode;
                            currentActivity = (YamlMappingNode)activities.Children[(new YamlScalarNode((activity.Key).ToString()))];
                            if ((activity.Key).ToString() == "copying")
                            {
                                if (currentActivity.Children.Count > 1)
                                {
                                    YamlMappingNode subSearch;
                                    foreach (var search in currentActivity)
                                    {
                                        subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search.Key).ToString()))];
                                        //subSearch2 = search;
                                        //get copy data
                                        if ((search.Key).ToString() == mats)
                                        {
                                            //contains mats... extract them
                                            YdnExtract(subSearch, mats, ref copyMats);
                                        }
                                        else if ((search.Key).ToString() == prod)
                                        {
                                            //contains products... extract them
                                            Console.WriteLine("production does have a line");
                                        }
                                        else if ((search.Key).ToString() == skill)
                                        {
                                            //contains skills... extract them
                                            YdnExtract(subSearch, skill, ref copyskills);
                                        }
                                        else if ((search.Key).ToString() == skill)
                                        {
                                            //contains time... extract it
                                            YdnExtract(subSearch, time, ref copyTime);
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (var search in currentActivity)
                                    {
                                        if ((search.Key).ToString() == mats)
                                        {
                                            //contains mats... extract them
                                            YdnExtract(currentActivity, mats, ref copyMats);
                                        }
                                        else if ((search.Key).ToString() == prod)
                                        {
                                            //contains products... extract them
                                            Console.WriteLine("production does have a line");
                                        }
                                        else if ((search.Key).ToString() == skill)
                                        {
                                            //contains skills... extract them
                                            YdnExtract(currentActivity, skill, ref copyskills);
                                        }
                                        else if ((search.Key).ToString() == time)
                                        {
                                            //contains time... extract it
                                            YdnExtract(currentActivity, time, ref copyTime);
                                        }
                                    }
                                }
                            }
                            else if ((activity.Key).ToString() == "manufacturing")
                            {
                                //YamlMappingNode subSearch;
                                foreach (var search in currentActivity)
                                {
                                    //get copy data
                                    if ((search.Key).ToString() == mats)
                                    {
                                        Console.WriteLine("item, key: " + search.Key + ", value: " + search.Value);

                                        //contains mats... extract them
                                        YamlScalarNode  searchTerm = new YamlScalarNode("materials");
                                        YamlMappingNode subSearch  = (YamlMappingNode)currentActivity.Children[searchTerm];
                                        YdnExtract(subSearch, mats, ref prodMats);
                                    }
                                    else if ((search.Key).ToString() == prod)
                                    {
                                        //contains products... extract them
                                        var subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search.Key).ToString()))];
                                        YdnExtract(subSearch, prod, ref productionQty, ref itemID);
                                    }
                                    else if ((search.Key).ToString() == skill)
                                    {
                                        //contains skills... extract them
                                        var subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search.Key).ToString()))];
                                        YdnExtract(subSearch, skill, ref prodskills);
                                    }
                                    else if ((search.Key).ToString() == time)
                                    {
                                        //contains time... extract it

                                        //YdnExtract(search, time, ref productionTime);
                                    }
                                }

                                //YamlMappingNode subSearch;
                                //for (int i = 0; i <= Int32.Parse((currentActivity.Children).ToString()); ++i )
                                //{
                                //    YamlMappingNode test = (YamlMappingNode)currentActivity.Children[i] as YamlMappingNode;
                                //    //get copy data
                                //    //if (( .Key).ToString() == mats)
                                //    if (false)
                                //    {
                                //        //contains mats... extract them
                                //        //(search.Value).ToString();
                                //        subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search).ToString()))];
                                //        YdnExtract(subSearch, mats, ref prodMats);
                                //    }
                                //    //else if ((search.Key).ToString() == prod)
                                //    else if (false)
                                //    {
                                //        //contains products... extract them
                                //        subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search.Key).ToString()))];
                                //        YdnExtract(subSearch, prod, ref productionQty, ref itemID);
                                //    }
                                //    //else if ((search.Key).ToString() == skill)
                                //    else if (false)
                                //    {
                                //        //contains skills... extract them
                                //        subSearch = (YamlMappingNode)currentActivity.Children[(new YamlScalarNode((search.Key).ToString()))];
                                //        YdnExtract(subSearch, skill, ref prodskills);
                                //    }
                                //    //else if ((search.Key).ToString() == time)
                                //    else if (false)
                                //    {
                                //        //contains time... extract it

                                //        //YdnExtract(search, time, ref productionTime);
                                //    }
                                //}
                            }
                        }
                    }
                    else if ((item.Key).ToString() == "maxProductionLimit")
                    {
                        prodLmt = Int32.Parse((item.Value).ToString());
                    }
                }

                //pass in all the values that have been collected
                items[itemCount] = new Item(blueprintID, itemID);
                items[itemCount].setProdskills(prodskills);
                items[itemCount].setProdMats(prodMats);
                items[itemCount].setProdTime(productionTime);
                items[itemCount].setProdQty(productionQty);
                items[itemCount].setProdLimit(prodLmt);
                items[itemCount].setCopyTime(copyTime);
                items[itemCount].setCopySkills(copyskills);
                items[itemCount].setCopyMats(copyMats);
                ++itemCount;
            }
            itemCount = 0;
            file.Close();
        }
Пример #22
0
    private void ReadMockData()
    {
        //Read mock data from yaml and json files
        mockObjectDic.Clear();
        mockObjectDic.Add("GET", new List <MockServerObject> ());
        mockObjectDic.Add("POST", new List <MockServerObject> ());
        mockObjectDic.Add("PUT", new List <MockServerObject> ());
        mockObjectDic.Add("DELETE", new List <MockServerObject> ());
        //Get yaml string
        string yamlString = LoadFileData(pathFileLoad, false, null);
        // Setup the input
        var input = new StringReader(yamlString);
        // Load the stream
        var yaml = new YamlStream();

        yaml.Load(input);
        int docCount = yaml.Documents.Count;

        for (int i = 0; i < docCount; i++)
        {
            var mapping = (YamlMappingNode)yaml.Documents [i].RootNode;

            MockServerObject mock   = new MockServerObject();
            var            request  = (YamlMappingNode)mapping.Children [new YamlScalarNode("request")];
            var            response = (YamlMappingNode)mapping.Children [new YamlScalarNode("response")];
            YamlScalarNode method   = (YamlScalarNode)request.Children [new YamlScalarNode("method")];
            mock.method = method.Value;

            if (request.Children.Keys.Contains(new YamlScalarNode("body")))
            {
                var body = request.Children [new YamlScalarNode("body")];
                mock.body = body.ToJson().Replace("\"[", "[").Replace("]\"", "]");
            }

            if (request.Children.Keys.Contains(new YamlScalarNode("query")))
            {
                var    query       = request.Children [new YamlScalarNode("query")];
                String queryString = "";

                if (query is YamlMappingNode)
                {
                    YamlMappingNode queryMapNode = (YamlMappingNode)query;
                    foreach (var item in queryMapNode.Children)
                    {
                        if (queryString.Length > 0)
                        {
                            queryString += "&";
                        }
                        queryString += item.Key + "=" + (item.Value is YamlMappingNode ? item.Value.ToJson() : item.Value);
                    }
                }
                mock.query = queryString;
            }

            if (request.Children.Keys.Contains(new YamlScalarNode("header")))
            {
                var header = request.Children [new YamlScalarNode("header")];
                mock.header = header.ToJson();
            }

            YamlScalarNode url = (YamlScalarNode)request.Children [new YamlScalarNode("url")];
            if (mock.query != null && mock.query.Length > 0)
            {
                mock.url = MockServer.SERVER + url.Value + "?" + mock.query;
            }
            else
            {
                mock.url = MockServer.SERVER + url.Value;
            }


            if (response.Children.Keys.Contains(new YamlScalarNode("X-NCMB-Response-Signature")))
            {
                mock.responseSignature = true;
            }

            YamlScalarNode status = (YamlScalarNode)response.Children [new YamlScalarNode("status")];
            mock.status = Convert.ToInt32(status.Value);

            YamlScalarNode file = (YamlScalarNode)response.Children [new YamlScalarNode("file")];
            mock.responseJson = LoadFileData("PlayModeTest" + file.Value, true, "");
            mockObjectDic [mock.method].Add(mock);
        }
    }
        public NintendoSubmissionPackageFileSystemInfo GetFileSystemInfo()
        {
            NintendoSubmissionPackageFileSystemInfo packageFileSystemInfo = new NintendoSubmissionPackageFileSystemInfo();

            using (StreamReader streamReader = new StreamReader(this.m_adfPath, Encoding.UTF8))
            {
                YamlStream yamlStream = new YamlStream();
                yamlStream.Load((TextReader)streamReader);
                YamlSequenceNode child1;
                try
                {
                    YamlMappingNode rootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;
                    if (((YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("formatType")]).Value != "NintendoSubmissionPackage")
                    {
                        throw new ArgumentException();
                    }
                    YamlScalarNode child2 = (YamlScalarNode)rootNode.Children[(YamlNode) new YamlScalarNode("version")];
                    child1 = (YamlSequenceNode)rootNode.Children[(YamlNode) new YamlScalarNode("entries")];
                    packageFileSystemInfo.Version = Convert.ToByte(child2.Value);
                }
                catch
                {
                    throw new ArgumentException("invalid format .adf file.");
                }
                foreach (YamlMappingNode yamlMappingNode1 in child1)
                {
                    NintendoSubmissionPackageFileSystemInfo.EntryInfo entryInfo = new NintendoSubmissionPackageFileSystemInfo.EntryInfo();
                    entryInfo.Contents = new List <NintendoSubmissionPackageFileSystemInfo.ContentInfo>();
                    YamlNode child2 = yamlMappingNode1.Children[(YamlNode) new YamlScalarNode("contents")];
                    if (child2 is YamlSequenceNode)
                    {
                        foreach (YamlMappingNode yamlMappingNode2 in (YamlSequenceNode)child2)
                        {
                            NintendoSubmissionPackageFileSystemInfo.ContentInfo contentInfo = new NintendoSubmissionPackageFileSystemInfo.ContentInfo();
                            string empty1 = string.Empty;
                            string empty2 = string.Empty;
                            foreach (KeyValuePair <YamlNode, YamlNode> keyValuePair in yamlMappingNode2)
                            {
                                string str = ((YamlScalarNode)keyValuePair.Key).Value;
                                if (!(str == "type"))
                                {
                                    if (!(str == "contentType"))
                                    {
                                        if (!(str == "path"))
                                        {
                                            throw new ArgumentException("invalid format .adf file. invalid key is specified\n" + yamlMappingNode2.ToString());
                                        }
                                        empty2 = ((YamlScalarNode)keyValuePair.Value).Value;
                                    }
                                    else
                                    {
                                        contentInfo.ContentType = ((YamlScalarNode)keyValuePair.Value).Value;
                                    }
                                }
                                else
                                {
                                    empty1 = ((YamlScalarNode)keyValuePair.Value).Value;
                                }
                            }
                            if (empty2 == null)
                            {
                                throw new ArgumentException("invalid format .adf file. \"path\" is not specified\n" + yamlMappingNode2.ToString());
                            }
                            if (empty1 == "format")
                            {
                                NintendoContentAdfReader contentAdfReader = new NintendoContentAdfReader(empty2);
                                contentInfo.FsInfo = (Nintendo.Authoring.FileSystemMetaLibrary.FileSystemInfo)contentAdfReader.GetFileSystemInfo();
                            }
                            else
                            {
                                if (!(empty1 == "file"))
                                {
                                    throw new ArgumentException("invalid format .adf file. unknown \"type\" is specified\n" + yamlMappingNode2.ToString());
                                }
                                FileInfo fileInfo = new FileInfo(empty2);
                                contentInfo.Source = (ISource) new FileSource(empty2, 0L, fileInfo.Length);
                            }
                            entryInfo.Contents.Add(contentInfo);
                        }
                    }
                    List <Tuple <string, string> > iconList   = new List <Tuple <string, string> >();
                    List <Tuple <string, string> > nxIconList = new List <Tuple <string, string> >();
                    uint maxNxIconSize = 102400;
                    foreach (KeyValuePair <YamlNode, YamlNode> keyValuePair in yamlMappingNode1)
                    {
                        switch (((YamlScalarNode)keyValuePair.Key).Value)
                        {
                        case "contents":
                            continue;

                        case "icon":
                            using (IEnumerator <YamlNode> enumerator = ((YamlSequenceNode)keyValuePair.Value).GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    YamlMappingNode current = (YamlMappingNode)enumerator.Current;
                                    string          str1    = ((YamlScalarNode)current.Children[(YamlNode) new YamlScalarNode("language")]).Value;
                                    string          str2    = ((YamlScalarNode)current.Children[(YamlNode) new YamlScalarNode("path")]).Value;
                                    iconList.Add(new Tuple <string, string>(str1, str2));
                                }
                                continue;
                            }

                        case "keyIndex":
                            entryInfo.KeyIndex = int.Parse(((YamlScalarNode)keyValuePair.Value).Value);
                            continue;

                        case "metaFilePath":
                            entryInfo.MetaFilePath = ((YamlScalarNode)keyValuePair.Value).Value;
                            continue;

                        case "metaType":
                            entryInfo.MetaType = ((YamlScalarNode)keyValuePair.Value).Value;
                            continue;

                        case "nxIcon":
                            using (IEnumerator <YamlNode> enumerator = ((YamlSequenceNode)keyValuePair.Value).GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    YamlMappingNode current = (YamlMappingNode)enumerator.Current;
                                    string          str1    = ((YamlScalarNode)current.Children[(YamlNode) new YamlScalarNode("language")]).Value;
                                    string          str2    = ((YamlScalarNode)current.Children[(YamlNode) new YamlScalarNode("path")]).Value;
                                    nxIconList.Add(new Tuple <string, string>(str1, str2));
                                }
                                continue;
                            }

                        case "nxIconMaxSize":
                            maxNxIconSize = uint.Parse(((YamlScalarNode)keyValuePair.Value).Value);
                            continue;

                        default:
                            throw new ArgumentException("invalid format .adf file. invalid key is specified\n" + yamlMappingNode1.ToString());
                        }
                    }
                    if (entryInfo.MetaFilePath == null)
                    {
                        throw new ArgumentException();
                    }
                    Tuple <int, int> cardSpec = new DotMetaReader(entryInfo.MetaFilePath).GetCardSpec();
                    if (cardSpec != null)
                    {
                        packageFileSystemInfo.CardSize      = cardSpec.Item1;
                        packageFileSystemInfo.CardClockRate = cardSpec.Item2;
                    }
                    else
                    {
                        Log.Info("\"CardSpec\" is not specified by .meta file. Size and ClockRate will be calculated automatically.");
                    }
                    entryInfo.ExtraData = this.CreateExtraSource(iconList, nxIconList, maxNxIconSize);
                    packageFileSystemInfo.Entries.Add(entryInfo);
                }
            }
            return(packageFileSystemInfo);
        }
 private static IEnumerable <ParsingEvent> ConvertToEventStream(YamlScalarNode scalar)
 {
     yield return(new Scalar(scalar.Anchor, scalar.Tag, scalar.Value, scalar.Style, false, false));
 }
        /// <summary>
        /// Creates a target resource for the template.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="templateKey">The key of the template.</param>
        /// <param name="templateNode">The template from configuration.</param>
        /// <returns></returns>
        private TargetResourceTemplate CreateTargetResourceTemplate(AzureIntegrationServicesModel model, YamlScalarNode templateKey, YamlMappingNode templateNode)
        {
            // Mandatory fields
            var targetResource = new TargetResourceTemplate()
            {
                TemplateKey  = ((YamlScalarNode)templateNode.Children["template"]).Value,
                TemplateType = ((YamlScalarNode)templateNode.Children["templateType"]).Value,
                ResourceName = ((YamlScalarNode)templateNode.Children["resourceName"]).Value,
                ResourceType = ((YamlScalarNode)templateNode.Children["resourceType"]).Value
            };

            // Optional fields
            if (templateNode.Children.ContainsKey("outputPath"))
            {
                targetResource.OutputPath = ((YamlScalarNode)templateNode.Children["outputPath"]).Value;
            }

            // Tags
            if (templateNode.Children.ContainsKey("tags"))
            {
                var templateTags = templateNode.Children["tags"] as YamlSequenceNode;
                if (templateTags != null)
                {
                    foreach (var tag in templateTags)
                    {
                        var tagNode = ((YamlMappingNode)tag).Children.SingleOrDefault();
                        targetResource.Tags.Add(((YamlScalarNode)tagNode.Key).Value, ((YamlScalarNode)tagNode.Value).Value);
                    }
                }
            }

            // Parameters
            if (templateNode.Children.ContainsKey("parameters"))
            {
                var templateParams = templateNode.Children["parameters"] as YamlSequenceNode;
                if (templateParams != null)
                {
                    foreach (var param in templateParams)
                    {
                        var paramNode = ((YamlMappingNode)param).Children.SingleOrDefault();
                        targetResource.Parameters.Add(((YamlScalarNode)paramNode.Key).Value, ((YamlScalarNode)paramNode.Value).Value);
                    }
                }
            }

            // Files
            if (templateNode.Children.ContainsKey("files"))
            {
                var templateFiles = templateNode.Children["files"] as YamlSequenceNode;
                if (templateFiles != null)
                {
                    _logger.LogTrace(TraceMessages.FilteringTemplatesByEnvironment, model.MigrationTarget.DeploymentEnvironment, templateKey.Value);

                    foreach (var templateFileNode in templateFiles)
                    {
                        var templateFile = (YamlMappingNode)templateFileNode;

                        // Filter by deployment environment
                        var envNameNode = templateFile.Children["env"] as YamlSequenceNode;
                        if (envNameNode != null)
                        {
                            var envNames = envNameNode.Select(t => ((YamlScalarNode)t).Value.ToUpperInvariant());
                            if (envNames.Contains(model.MigrationTarget.DeploymentEnvironment.ToUpperInvariant()))
                            {
                                _logger.LogTrace(TraceMessages.FoundFilesForEnvironment, model.MigrationTarget.DeploymentEnvironment, templateKey.Value);

                                // Get paths - note that if there are no paths defined, then this node is a YamlScalarNode.
                                var pathsList = templateFile.Children["paths"] as YamlSequenceNode;
                                if (pathsList != null)
                                {
                                    foreach (var path in pathsList)
                                    {
                                        targetResource.ResourceTemplateFiles.Add(((YamlScalarNode)path).Value);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(targetResource);
        }
Пример #26
0
 protected override void Visited(YamlScalarNode scalar)
 {
     --indent;
     WriteIndent();
     Console.WriteLine("Visited(YamlScalarNode)");
 }
        /// <summary>
        /// Creates a target resource for the snippet.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="snippetKey">The key of the snippet.</param>
        /// <param name="snippetNode">The snippet from configuration.</param>
        /// <returns></returns>
        private TargetResourceSnippet CreateTargetResourceSnippet(AzureIntegrationServicesModel model, YamlScalarNode snippetKey, YamlMappingNode snippetNode)
        {
            // Mandatory fields
            var targetResource = new TargetResourceSnippet()
            {
                SnippetKey   = ((YamlScalarNode)snippetNode.Children["snippet"]).Value,
                SnippetType  = ((YamlScalarNode)snippetNode.Children["snippetType"]).Value,
                ResourceName = ((YamlScalarNode)snippetNode.Children["resourceName"]).Value,
                ResourceType = ((YamlScalarNode)snippetNode.Children["resourceType"]).Value
            };

            // Optional fields
            if (snippetNode.Children.ContainsKey("outputPath"))
            {
                targetResource.OutputPath = ((YamlScalarNode)snippetNode.Children["outputPath"]).Value;
            }

            // Parameters
            if (snippetNode.Children.ContainsKey("parameters"))
            {
                var templateParams = (YamlSequenceNode)snippetNode.Children["parameters"];
                if (templateParams != null)
                {
                    foreach (var param in templateParams)
                    {
                        var paramNode = ((YamlMappingNode)param).Children.SingleOrDefault();
                        targetResource.Parameters.Add(((YamlScalarNode)paramNode.Key).Value, ((YamlScalarNode)paramNode.Value).Value);
                    }
                }
            }

            // Files
            if (snippetNode.Children.ContainsKey("files"))
            {
                var snippetFiles = (YamlSequenceNode)snippetNode.Children["files"];
                if (snippetFiles != null)
                {
                    _logger.LogTrace(TraceMessages.FilteringSnippetsByEnvironment, model.MigrationTarget.DeploymentEnvironment, snippetKey.Value);

                    foreach (var snippetFileNode in snippetFiles)
                    {
                        var snippetFile = (YamlMappingNode)snippetFileNode;

                        // Filter by deployment environment
                        var envNameNode = (YamlSequenceNode)snippetFile.Children["env"];
                        var envNames    = envNameNode.Select(t => ((YamlScalarNode)t).Value.ToUpperInvariant());
                        if (envNames.Contains(model.MigrationTarget.DeploymentEnvironment.ToUpperInvariant()))
                        {
                            _logger.LogTrace(TraceMessages.FoundSnippetFileForEnvironment, model.MigrationTarget.DeploymentEnvironment, snippetKey.Value);

                            // Get path
                            targetResource.ResourceSnippetFile = ((YamlScalarNode)snippetFile.Children["path"]).Value;
                        }
                    }
                }
            }

            return(targetResource);
        }
Пример #28
0
 public override void Visit(YamlScalarNode scalar)
 {
     events.Add(new YamlNodeEvent(YamlNodeEventType.Scalar, scalar.Anchor, scalar.Tag, scalar.Value));
 }
        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());
        }
Пример #30
0
 /// <summary>
 /// Called after this object finishes visiting a <see cref="YamlScalarNode"/>.
 /// </summary>
 /// <param name="scalar">
 /// The <see cref="YamlScalarNode"/> that has been visited.
 /// </param>
 protected virtual void Visited(YamlScalarNode scalar)
 {
     // Do nothing.
 }
Пример #31
0
        public void WriteConfig(Options options)
        {
            const string initialContent = "---\nversion: 1\n"; // needed to start writing yaml file

            var sr     = new StringReader(initialContent);
            var stream = new YamlStream();

            stream.Load(sr);

            var rootMappingNode = (YamlMappingNode)stream.Documents[0].RootNode;

            var sras            = options.SraAccession.Split(',');
            var fqs             = options.Fastq1.Split(',') ?? new string[0];
            var analysisStrings = new List <string>();

            if (options.AnalyzeVariants)
            {
                analysisStrings.Add("variant");
            }
            if (options.AnalyzeIsoforms)
            {
                analysisStrings.Add("isoform");
            }

            // write user input sras
            var accession = new YamlSequenceNode();

            rootMappingNode.Add("sra", AddParam(sras, accession));

            // write user defined analysis directory (input and output folder)
            var analysisDirectory = new YamlSequenceNode();

            analysisDirectory.Style = SequenceStyle.Flow;
            analysisDirectory.Add("analysis");
            rootMappingNode.Add("analysisDirectory", analysisDirectory);

            // write user input fastqs
            var fq = new YamlSequenceNode();

            rootMappingNode.Add("fq", AddParam(fqs, fq));

            // write ensembl release
            var release = new YamlScalarNode(options.Release.Substring(8));

            release.Style = ScalarStyle.DoubleQuoted;
            rootMappingNode.Add("release", release);

            // write species
            var species = new YamlScalarNode(options.Species.First().ToString().ToUpper() + options.Species.Substring(1));

            species.Style = ScalarStyle.DoubleQuoted;
            rootMappingNode.Add("species", species);

            // write species
            var organism = new YamlScalarNode(options.Organism);

            organism.Style = ScalarStyle.DoubleQuoted;
            rootMappingNode.Add("organism", organism);

            // write genome [e.g. GRCm38]
            var genome = new YamlScalarNode(options.Reference);

            genome.Style = ScalarStyle.DoubleQuoted;
            rootMappingNode.Add("genome", genome);

            // list the analyses to perform
            var analyses = new YamlSequenceNode();

            rootMappingNode.Add("analyses", AddParam(analysisStrings.ToArray(), analyses));

            // record the version of spritz
            var version = new YamlScalarNode(options.SpritzVersion);

            version.Style = ScalarStyle.DoubleQuoted;
            rootMappingNode.Add("spritzversion", version);

            using (TextWriter writer = File.CreateText(Path.Combine(ConfigDirectory, "config.yaml")))
            {
                stream.Save(writer, false);
            }
            File.WriteAllLines(Path.Combine(ConfigDirectory, "threads.txt"), new[] { options.Threads.ToString() });
        }