bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
		{
			if (!typeof(IList).IsAssignableFrom(expectedType))
			{
				value = false;
				return false;
			}

			reader.Expect<SequenceStart>();

			var list = (IList)_objectFactory.Create(expectedType);
			while (!reader.Accept<SequenceEnd>())
			{
				var item = nestedObjectDeserializer(reader, typeof(object));
				var promise = item as IValuePromise;
				if (promise == null)
				{
					list.Add(item);
				}
				else
				{
					var index = list.Count;
					list.Add(null);
					promise.ValueAvailable += v => list[index] = v;
				}
			}
			value = list;

			reader.Expect<SequenceEnd>();

			return true;
		}
Example #2
0
        public object Deserialize(EventReader reader, Type type)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            bool   flag  = reader.Allow <StreamStart>() != null;
            bool   flag2 = reader.Allow <DocumentStart>() != null;
            object obj2  = null;

            if (!reader.Accept <DocumentEnd>() && !reader.Accept <StreamEnd>())
            {
                using (SerializerState state = new SerializerState())
                {
                    obj2 = this.valueDeserializer.DeserializeValue(reader, type, state, this.valueDeserializer);
                    state.OnDeserialization();
                }
            }
            if (flag2)
            {
                reader.Expect <DocumentEnd>();
            }
            if (flag)
            {
                reader.Expect <StreamEnd>();
            }
            return(obj2);
        }
Example #3
0
        internal static void DeserializeHelper(Type tItem, EventReader reader, Type expectedType, Func <EventReader, Type, object> nestedObjectDeserializer, IList result, bool canUpdate)
        {
            reader.Expect <SequenceStart>();
            while (!reader.Accept <SequenceEnd>())
            {
                var current = reader.Parser.Current;

                var value   = nestedObjectDeserializer(reader, tItem);
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType(value, tItem));
                }
                else if (canUpdate)
                {
                    var index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null);
                    promise.ValueAvailable += v => result[index] = TypeConverter.ChangeType(v, tItem);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                              current.Start,
                              current.End,
                              "Forward alias references are not allowed because this type does not implement IList<>"
                              );
                }
            }
            reader.Expect <SequenceEnd>();
        }
        internal static void DeserializeHelper <TItem>(EventReader reader, Type expectedType, Func <EventReader, Type, object> nestedObjectDeserializer, ICollection <TItem> result)
        {
            var list = result as IList <TItem>;

            reader.Expect <SequenceStart>();
            while (!reader.Accept <SequenceEnd>())
            {
                var current = reader.Parser.Current;

                var value   = nestedObjectDeserializer(reader, typeof(TItem));
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType <TItem>(value));
                }
                else if (list != null)
                {
                    var index = list.Count;
                    result.Add(default(TItem));
                    promise.ValueAvailable += v => list[index] = TypeConverter.ChangeType <TItem>(v);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                              current.Start,
                              current.End,
                              "Forward alias references are not allowed because this type does not implement IList<>"
                              );
                }
            }
            reader.Expect <SequenceEnd>();
        }
Example #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlDocument"/> class.
        /// </summary>
        /// <param name="events">The events.</param>
        internal YamlDocument(EventReader events)
        {
            DocumentLoadingState state = new DocumentLoadingState();

            events.Expect <DocumentStart>();

            while (!events.Accept <DocumentEnd>())
            {
                Debug.Assert(RootNode == null);
                RootNode = YamlNode.ParseNode(events, state);

                if (RootNode is YamlAliasNode)
                {
                    throw new YamlException();
                }
            }

            state.ResolveAliases();

#if DEBUG
            foreach (var node in AllNodes)
            {
                if (node is YamlAliasNode)
                {
                    throw new InvalidOperationException("Error in alias resolution.");
                }
            }
#endif

            events.Expect <DocumentEnd>();
        }
        bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func <EventReader, Type, object> nestedObjectDeserializer, out object value)
        {
            if (!typeof(IList).IsAssignableFrom(expectedType))
            {
                value = false;
                return(false);
            }

            reader.Expect <SequenceStart>();

            var list = (IList)_objectFactory.Create(expectedType);

            while (!reader.Accept <SequenceEnd>())
            {
                var current = reader.Parser.Current;

                var item    = nestedObjectDeserializer(reader, typeof(object));
                var promise = item as IValuePromise;
                if (promise == null)
                {
                    list.Add(item);
                }
                else
                {
                    var index = list.Count;
                    list.Add(null);
                    promise.ValueAvailable += v => list[index] = v;
                }
            }
            value = list;

            reader.Expect <SequenceEnd>();

            return(true);
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlDocument"/> class.
        /// </summary>
        /// <param name="events">The events.</param>
        internal YamlDocument(EventReader events)
        {
            DocumentLoadingState state = new DocumentLoadingState();

            events.Expect<DocumentStart>();

            while (!events.Accept<DocumentEnd>())
            {
                Debug.Assert(RootNode == null);
                RootNode = YamlNode.ParseNode(events, state);

                if (RootNode is YamlAliasNode)
                {
                    throw new YamlException();
                }
            }

            state.ResolveAliases();

            #if DEBUG
            foreach (var node in AllNodes)
            {
                if (node is YamlAliasNode)
                {
                    throw new InvalidOperationException("Error in alias resolution.");
                }
            }
            #endif

            events.Expect<DocumentEnd>();
        }
Example #8
0
        private MapNode DeserializeIsolatedNode(EventReader r)
        {
            string text = null; NodePosition pos = NodePosition.Undefined; string id = null;

            string prop = r.Peek<Scalar>().Value;

            if (prop != null && prop.Equals(Text))
            {
                r.Expect<Scalar>();
                text = r.Expect<Scalar>().Value;
                prop = r.Peek<Scalar>().Value;
            }

            if (prop != null && prop.Equals(Pos))
            {
                r.Expect<Scalar>();
                pos = (NodePosition)Enum.Parse(typeof(NodePosition), r.Expect<Scalar>().Value);
                //prop = r.Peek<Scalar>().Value;
            }

            // Isolated nodes donot have Id
            //if (prop != null && prop.Equals(Id))
            //{
            //    r.Expect<Scalar>();
            //    id = r.Expect<Scalar>().Value;
            //    //prop = r.Peek<Scalar>().Value;
            //}

            MapNode node = MapNode.CreateIsolatedNode(pos);
            node.Text = text;
            return node;
        }
Example #9
0
        /// <summary>
        /// Deserializes an object of the specified type.
        /// </summary>
        /// <param name="reader">The <see cref="EventReader" /> where to deserialize the object.</param>
        /// <param name="type">The static type of the object to deserialize.</param>
        /// <param name="options">Options that control how the deserialization is to be performed.</param>
        /// <returns>Returns the deserialized object.</returns>
        public object Deserialize(EventReader reader, Type type, DeserializationFlags options = DeserializationFlags.None)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var hasStreamStart = reader.Allow <StreamStart>() != null;

            var hasDocumentStart = reader.Allow <DocumentStart>() != null;

            object result = DeserializeValue(reader, type, null);

            if (hasDocumentStart)
            {
                reader.Expect <DocumentEnd>();
            }

            if (hasStreamStart)
            {
                reader.Expect <StreamEnd>();
            }

            return(result);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="state">The state.</param>
        internal YamlSequenceNode(EventReader events, DocumentLoadingState state)
        {
            SequenceStart sequence = events.Expect <SequenceStart>();

            Load(sequence, state);
            Style = sequence.Style;

            bool hasUnresolvedAliases = false;

            while (!events.Accept <SequenceEnd>())
            {
                YamlNode child = ParseNode(events, state);
                children.Add(child);
                hasUnresolvedAliases |= child is YamlAliasNode;
            }

            if (hasUnresolvedAliases)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }
#if DEBUG
            else
            {
                foreach (var child in children)
                {
                    if (child is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                }
            }
#endif

            events.Expect <SequenceEnd>();
        }
Example #11
0
        /// <summary>
        /// Deserializes an object from the specified <see cref="EventReader" /> with an expected specific type.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="expectedType">The expected type, maybe null.</param>
        /// <param name="existingObject">An existing object, may be null.</param>
        /// <param name="contextSettings">The context settings.</param>
        /// <param name="context">The context used to deserialize the object.</param>
        /// <returns>A deserialized object.</returns>
        /// <exception cref="System.ArgumentNullException">reader</exception>
        public object Deserialize(EventReader reader, Type expectedType, object existingObject, SerializerContextSettings contextSettings, out SerializerContext context)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            var hasStreamStart   = reader.Allow <StreamStart>() != null;
            var hasDocumentStart = reader.Allow <DocumentStart>() != null;

            context = null;

            object result = null;

            if (!reader.Accept <DocumentEnd>() && !reader.Accept <StreamEnd>())
            {
                context = new SerializerContext(this, contextSettings)
                {
                    Reader = reader
                };
                result = context.ReadYaml(existingObject, expectedType);
            }

            if (hasDocumentStart)
            {
                reader.Expect <DocumentEnd>();
            }

            if (hasStreamStart)
            {
                reader.Expect <StreamEnd>();
            }

            return(result);
        }
Example #12
0
        /// <summary>
        /// Deserializes an object of the specified type.
        /// </summary>
        /// <param name="reader">The <see cref="EventReader" /> where to deserialize the object.</param>
        /// <param name="type">The static type of the object to deserialize.</param>
        /// <param name="options">Options that control how the deserialization is to be performed.</param>
        /// <returns>Returns the deserialized object.</returns>
        public object Deserialize(EventReader reader, Type type)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var hasStreamStart = reader.Allow <StreamStart>() != null;

            var hasDocumentStart = reader.Allow <DocumentStart>() != null;

            object result = null;

            if (!reader.Accept <DocumentEnd>() && !reader.Accept <StreamEnd>())
            {
                result = valueDeserializer.DeserializeValue(reader, type, new SerializerState(), valueDeserializer);
            }

            if (hasDocumentStart)
            {
                reader.Expect <DocumentEnd>();
            }

            if (hasStreamStart)
            {
                reader.Expect <StreamEnd>();
            }

            return(result);
        }
Example #13
0
        private MapNode DeserializeIsolatedNode(EventReader r)
        {
            string text = null; NodePosition pos = NodePosition.Undefined; string id = null;

            string prop = r.Peek <Scalar>().Value;

            if (prop != null && prop.Equals(Text))
            {
                r.Expect <Scalar>();
                text = r.Expect <Scalar>().Value;
                prop = r.Peek <Scalar>().Value;
            }

            if (prop != null && prop.Equals(Pos))
            {
                r.Expect <Scalar>();
                pos = (NodePosition)Enum.Parse(typeof(NodePosition), r.Expect <Scalar>().Value);
                //prop = r.Peek<Scalar>().Value;
            }

            // Isolated nodes donot have Id
            //if (prop != null && prop.Equals(Id))
            //{
            //    r.Expect<Scalar>();
            //    id = r.Expect<Scalar>().Value;
            //    //prop = r.Peek<Scalar>().Value;
            //}

            MapNode node = MapNode.CreateIsolatedNode(pos);

            node.Text = text;
            return(node);
        }
Example #14
0
        private object DeserializeList(EventReader reader, Type type, DeserializationContext context)
        {
            SequenceStart sequence = reader.Expect <SequenceStart>();

            type = GetType(sequence.Tag, type, context.Options.Mappings);

            // Choose a default list type in case there was no specific type specified.
            if (type == typeof(object))
            {
                type = typeof(ArrayList);
            }

            object result;

            Type iCollection = ReflectionUtility.GetImplementedGenericInterface(type, typeof(ICollection <>));

            if (iCollection != null)                // Generic list
            {
                Type[] iCollectionArguments = iCollection.GetGenericArguments();
                Debug.Assert(iCollectionArguments.Length == 1, "ICollection<> must have one generic argument.");
                var itemType = iCollectionArguments[0];

                //result = type.IsArray ? typeof(List<>).MakeGenericType(iCollectionArguments) : Activator.CreateInstance(type);
                //MethodInfo addAdapter = addAdapterGeneric.MakeGenericMethod(iCollectionArguments);
                //Action<object, object> addAdapterDelegate = (Action<object, object>)Delegate.CreateDelegate(typeof(Action<object, object>), addAdapter);
                if (type.IsArray)
                {
                    var tempListType = typeof(List <>).MakeGenericType(iCollectionArguments);
                    var tempList     = Activator.CreateInstance(tempListType);
                    DeserializeGenericListInternal(reader, tempList, itemType, context);
                    result = tempListType.GetMethod("ToArray", Type.EmptyTypes).Invoke(tempList, null);
                }
                else
                {
                    result = Activator.CreateInstance(type);
                    DeserializeGenericListInternal(reader, result, itemType, context);
                }
            }
            else               // Non-generic list
            {
                result = Activator.CreateInstance(type);
                var list = result as IList;
                if (list != null)
                {
                    while (!reader.Accept <SequenceEnd>())
                    {
                        list.Add(DeserializeValue(reader, typeof(object), context));
                    }
                }
                reader.Expect <SequenceEnd>();
            }

            AddAnchoredObject(sequence, result, context.Anchors);

            return(result);
        }
Example #15
0
 internal static void DeserializeHelper <TItem>(EventReader reader, Type expectedType, Func <EventReader, Type, object> nestedObjectDeserializer, ICollection <TItem> result)
 {
     reader.Expect <SequenceStart>();
     while (!reader.Accept <SequenceEnd>())
     {
         var value = (TItem)nestedObjectDeserializer(reader, typeof(TItem));
         result.Add(value);
     }
     reader.Expect <SequenceEnd>();
 }
Example #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="state">The state.</param>
        internal YamlMappingNode(EventReader events, DocumentLoadingState state, bool overrideKeys)
        {
            MappingStart mapping = events.Expect <MappingStart>();

            Load(mapping, state);

            bool hasUnresolvedAliases = false;

            while (!events.Accept <MappingEnd>())
            {
                YamlNode key   = ParseNode(events, state, overrideKeys);
                YamlNode value = ParseNode(events, state, overrideKeys);

                try
                {
                    if (children.ContainsKey(key) && overrideKeys)
                    {
                        children[key] = value;
                    }
                    else
                    {
                        children.Add(key, value);
                    }
                }
                catch (ArgumentException err)
                {
                    throw new YamlException(key.Start, key.End, "Duplicate key", err);
                }

                hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode;
            }

            if (hasUnresolvedAliases)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }
#if DEBUG
            else
            {
                foreach (var child in children)
                {
                    if (child.Key is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                    if (child.Value is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                }
            }
#endif

            events.Expect <MappingEnd>();
        }
Example #17
0
 public void Load(EventReader reader)
 {
     this.documents.Clear();
     reader.Expect <StreamStart>();
     while (!reader.Accept <StreamEnd>())
     {
         YamlDocument item = new YamlDocument(reader);
         this.documents.Add(item);
     }
     reader.Expect <StreamEnd>();
 }
        private void DeserializeNodeStyles(MetaModel.MetaModel metaModel, EventReader r)
        {
            r.Expect <SequenceStart>();

            while (r.Accept <MappingStart>())
            {
                DeserializeNodeStyle(metaModel, r);
            }

            r.Expect <SequenceEnd>();
        }
        private void DeserializeRecentFiles(MetaModel.MetaModel metaModel, EventReader r)
        {
            r.Expect <SequenceStart>();

            while (r.Accept <Scalar>())
            {
                metaModel.RecentFiles.Add(r.Expect <Scalar>().Value);
            }

            r.Expect <SequenceEnd>();
        }
Example #20
0
        /// <summary>
        /// Deserializes an isolated node
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public MapNode Deserialize(EventReader r)
        {
            r.Expect<MappingStart>();

            MapNode n = DeserializeIsolatedNode(r);
            DeserializeScalarProperties(n, r);

            r.Expect<MappingEnd>();

            return n;
        }
Example #21
0
 /// <summary>
 /// Loads the stream from the specified <see cref="EventReader"/>.
 /// </summary>
 public void Load(EventReader reader)
 {
     documents.Clear();
     reader.Expect <StreamStart>();
     while (!reader.Accept <StreamEnd>())
     {
         YamlDocument document = new YamlDocument(reader);
         documents.Add(document);
     }
     reader.Expect <StreamEnd>();
 }
        public object ReadYaml(IParser parser, Type type)
        {
            EventReader eventReader = new EventReader(parser);

            eventReader.Expect <MappingStart>();
            Vector3 v = new Vector3();

            v = ReadField(eventReader, ReadField(eventReader, ReadField(eventReader, v)));
            eventReader.Expect <MappingEnd>();
            return(v);
        }
Example #23
0
        /// <summary>
        /// Deserializes an isolated node
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public MapNode Deserialize(EventReader r)
        {
            r.Expect <MappingStart>();

            MapNode n = DeserializeIsolatedNode(r);

            DeserializeScalarProperties(n, r);

            r.Expect <MappingEnd>();

            return(n);
        }
        public void Deserialize_AllProperties()
        {
            var sut  = new MapYamlSerializer();
            var node = MapNode.CreateIsolatedNode(NodePosition.Left);

            node.Text          = "Text";
            node.Folded        = true;
            node.BackColor     = Color.Aqua;
            node.Bold          = true;
            node.FontName      = "Arial";
            node.FontSize      = 15;
            node.TextAlignment = TextAlignment.AboveStart;
            node.Italic        = true;
            node.Label         = "label";
            node.LineColor     = Color.BlueViolet;
            node.LinePattern   = DashStyle.Dot;
            node.LineWidth     = 4;
            node.NoteText      = "Note";
            node.Shape         = NodeShape.Box;
            node.Strikeout     = true;
            node.Link          = "link";
            node.Color         = Color.Azure;

            var writer  = new StringWriter();
            var emitter = new Emitter(writer);

            emitter.Emit(new StreamStart());
            emitter.Emit(new DocumentStart());

            sut.Serialize(node, emitter);

            emitter.Emit(new DocumentEnd(true));
            emitter.Emit(new StreamEnd());

            string text = writer.ToString();

            var parser      = new Parser(new StringReader(text));
            var eventReader = new EventReader(parser);

            eventReader.Expect <StreamStart>();
            eventReader.Expect <DocumentStart>();
            var result = sut.Deserialize(eventReader);

            eventReader.Expect <DocumentEnd>();
            eventReader.Expect <StreamEnd>();

            Assert.AreEqual(Color.Azure, result.Color);
            Assert.IsNotNull(result.Label);
            Assert.IsNotNull(result.Text);
            Assert.AreEqual("link", result.Link);
        }
Example #25
0
        private static object ReadEvent(EventReader reader)
        {
            // Read a plain scalar and decode it to a C# value
            if (reader.Accept <Scalar>())
            {
                var scalar = reader.Expect <Scalar>();

                // We try to parse scalar with an extended YamlSchema
                // If we find a int,double... -> convert it to the proper C# type
                string defaultTag;
                object value;
                return(DefaultSchema.TryParse(scalar, true, out defaultTag, out value) ? value : scalar.Value);
            }

            // Read a YAML sequence to a ScriptArray
            if (reader.Accept <SequenceStart>())
            {
                var array = new ScriptArray();
                reader.Expect <SequenceStart>();
                while (!reader.Accept <SequenceEnd>())
                {
                    array.Add(ReadEvent(reader));
                }
                reader.Expect <SequenceEnd>();
                return(array);
            }

            // Read a YAML mapping to a ScriptObject
            if (reader.Accept <MappingStart>())
            {
                var obj = new ScriptObject();
                reader.Expect <MappingStart>();
                while (!reader.Accept <MappingEnd>())
                {
                    var key   = ReadEvent(reader).ToString();
                    var value = ReadEvent(reader);
                    try
                    {
                        obj.Add(key, value);
                    }
                    catch (ArgumentException err)
                    {
                        throw new YamlException(reader.Parser.Current.Start, reader.Parser.Current.End, "Duplicate key", err);
                    }
                }
                reader.Expect <MappingEnd>();
                return(obj);
            }

            throw new YamlException(reader.Parser.Current.Start, reader.Parser.Current.End, $"Unsupported Yaml Event {reader.Parser.Current}");
        }
Example #26
0
        /// <summary>
        /// Deserializes an object from the specified <see cref="EventReader" /> with an expected specific type.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="expectedType">The expected type, maybe null.</param>
        /// <param name="existingObject">An existing object, may be null.</param>
        /// <param name="contextSettings">The context settings.</param>
        /// <param name="context">The context used to deserialize the object.</param>
        /// <returns>A deserialized object.</returns>
        /// <exception cref="System.ArgumentNullException">reader</exception>
        public object Deserialize(EventReader reader, Type expectedType, object existingObject, SerializerContextSettings contextSettings, out SerializerContext context)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            var hasStreamStart   = reader.Allow <StreamStart>() != null;
            var hasDocumentStart = reader.Allow <DocumentStart>() != null;

            context = null;

            object result = null;

            if (!reader.Accept <DocumentEnd>() && !reader.Accept <StreamEnd>())
            {
                context = new SerializerContext(this, contextSettings)
                {
                    Reader = reader
                };
                var node = context.Reader.Parser.Current;
                try
                {
                    var objectContext = new ObjectContext(context, existingObject, context.FindTypeDescriptor(expectedType));
                    result = context.Serializer.ObjectSerializer.ReadYaml(ref objectContext);
                }
                catch (YamlException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    ex = ex.Unwrap();
                    throw new YamlException(node, ex);
                }
            }

            if (hasDocumentStart)
            {
                reader.Expect <DocumentEnd>();
            }

            if (hasStreamStart)
            {
                reader.Expect <StreamEnd>();
            }

            return(result);
        }
Example #27
0
        internal YamlDocument(EventReader events)
        {
            DocumentLoadingState state = new DocumentLoadingState();

            events.Expect <DocumentStart>();
            while (!events.Accept <DocumentEnd>())
            {
                this.RootNode = YamlNode.ParseNode(events, state);
                if (this.RootNode is YamlAliasNode)
                {
                    throw new YamlException();
                }
            }
            state.ResolveAliases();
            events.Expect <DocumentEnd>();
        }
        private void DeserializeNodeStyle(MetaModel.MetaModel metaModel, EventReader r)
        {
            var s = new NodeStyle();

            r.Expect <MappingStart>();

            r.Expect <Scalar>(); //Title
            s.Title = r.Expect <Scalar>().Value;

            r.Expect <Scalar>(); //RefNode
            s.RefNode = new MapYamlSerializer().Deserialize(r);

            r.Expect <MappingEnd>();

            metaModel.NodeStyles.Add(s);
        }
Example #29
0
    // Use this for initialization
    void Start()
    {
        var input = new StringReader(Document);

        var deserializer = new Deserializer();

        var reader = new EventReader(new Parser(input));

        // Consume the stream start event "manually"
        reader.Expect <StreamStart>();

        var output = new StringBuilder();

        while (reader.Accept <DocumentStart>())
        {
            // Deserialize the document
            var doc = deserializer.Deserialize <List <string> >(reader);

            output.AppendLine("## Document");
            foreach (var item in doc)
            {
                output.AppendLine(item);
            }
        }
        Debug.Log(output);
    }
Example #30
0
        /// <summary>
        /// Parses the node represented by the next event in <paramref name="events" />.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="state">The state.</param>
        /// <returns>Returns the node that has been parsed.</returns>
        static internal YamlNode ParseNode(EventReader events, DocumentLoadingState state)
        {
            if (events.Accept <Scalar>())
            {
                return(new YamlScalarNode(events, state));
            }

            if (events.Accept <SequenceStart>())
            {
                return(new YamlSequenceNode(events, state));
            }

            if (events.Accept <MappingStart>())
            {
                return(new YamlMappingNode(events, state));
            }

            if (events.Accept <AnchorAlias>())
            {
                AnchorAlias alias = events.Expect <AnchorAlias>();
                return(state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value));
            }

            throw new ArgumentException("The current event is of an unsupported type.", "events");
        }
Example #31
0
        /// <summary>
        /// Loads the stream from the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        public void Load(TextReader input)
        {
            documents.Clear();

            var parser = new Parser(input);

            EventReader events = new EventReader(parser);

            events.Expect <StreamStart>();
            while (!events.Accept <StreamEnd>())
            {
                YamlDocument document = new YamlDocument(events);
                documents.Add(document);
            }
            events.Expect <StreamEnd>();
        }
 // Use this for initialization
 void Start () {
     var input = new StringReader(Document);
     
     var deserializer = new Deserializer();
     
     var reader = new EventReader(new Parser(input));
     
     // Consume the stream start event "manually"
     reader.Expect<StreamStart>();
     
     var output = new StringBuilder();
     while(reader.Accept<DocumentStart>())
     {
         // Deserialize the document
         var doc = deserializer.Deserialize<List<string>>(reader);
     
         output.AppendLine("## Document");
         foreach(var item in doc)
         {
             output.AppendLine(item);
         }
     }    
     Debug.Log(output);
     
 }
Example #33
0
		/// <summary>
		/// Initializes a new instance of the <see cref="YamlScalarNode"/> class.
		/// </summary>
		/// <param name="events">The events.</param>
		/// <param name="state">The state.</param>
		internal YamlScalarNode(EventReader events, DocumentLoadingState state)
		{
			Scalar scalar = events.Expect<Scalar>();
			Load(scalar, state);
			Value = scalar.Value;
			Style = scalar.Style;
		}
Example #34
0
        private void Load(EventReader events, DocumentLoadingState state)
        {
            Scalar scalar = events.Expect <Scalar>();

            base.Load(scalar, state);
            Value = scalar.Value;
            Style = scalar.Style;
        }
Example #35
0
 private void DeserializeGenericListInternal(EventReader reader, Type itemType, object list, Action <object, object> addAdapterDelegate, DeserializationContext context)
 {
     while (!reader.Accept <SequenceEnd>())
     {
         addAdapterDelegate(list, DeserializeValue(reader, itemType, context));
     }
     reader.Expect <SequenceEnd>();
 }
Example #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlScalarNode"/> class.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="state">The state.</param>
        internal YamlScalarNode(EventReader events, DocumentLoadingState state)
        {
            Scalar scalar = events.Expect <Scalar>();

            Load(scalar, state);
            Value = scalar.Value;
            Style = scalar.Style;
        }
Example #37
0
    private static object GetData(EventReader r)
    {
        if(r.Accept<Scalar>())
        {
            return r.Expect<Scalar>().Value;
        }
        else if(r.Accept<SequenceStart>()) {
            var seq = new ArrayList();

            r.Expect<SequenceStart>();

            while(!r.Accept<SequenceEnd>())
            {
                seq.Add(GetData(r));
            }

            r.Expect<SequenceEnd>();

            // Arrays are IStructuralEquatable, ArrayLists are not.
            return seq.ToArray();
        }
        else if(r.Accept<MappingStart>())
        {
            // Since we use sequences as keys...
            var map = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);

            r.Expect<MappingStart>();

            while(!r.Accept<MappingEnd>())
            {
                object key = GetData(r);
                object value = GetData(r);
                map.Add(key, value);
            }

            r.Expect<MappingEnd>();

            return map;
        }
        else {
            throw new YamlException();
        }
    }
		bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
		{
			var mapping = reader.Allow<MappingStart>();
			if (mapping == null)
			{
				value = null;
				return false;
			}
			
			value = _objectFactory.Create(expectedType);
			while (!reader.Accept<MappingEnd>())
			{
				var propertyName = reader.Expect<Scalar>();
				var property = _typeDescriptor.GetProperty(expectedType, null, propertyName.Value, _ignoreUnmatched);
				if (property == null)
				{
					reader.SkipThisAndNestedEvents();
					continue;
				}

				var propertyValue = nestedObjectDeserializer(reader, property.Type);
				var propertyValuePromise = propertyValue as IValuePromise;
				if (propertyValuePromise == null)
				{
					var convertedValue = TypeConverter.ChangeType(propertyValue, property.Type);
					property.Write(value, convertedValue);
				}
				else
				{
					var valueRef = value;
					propertyValuePromise.ValueAvailable += v =>
					{
						var convertedValue = TypeConverter.ChangeType(v, property.Type);
						property.Write(valueRef, convertedValue);
					};
				}
			}

			reader.Expect<MappingEnd>();
			return true;
		}
        public static void ReadConfigYAML()
        {
            var input = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"/AME.yaml");

            var deserializer = new Deserializer();

            var reader = new EventReader(new Parser(input));

            // Deserialize the document
            reader.Expect<StreamStart>();
            reader.Accept<DocumentStart>();
            var settings = deserializer.Deserialize<AMESettings>(reader);

            reader.Accept<DocumentStart>();
            var behaviorManifests = deserializer.Deserialize<BehaviorManifests>(reader);

            foreach (var behavior in behaviorManifests.FRLGBehaviors)
            {
                if(behavior.Value[0] == '&')
                    behaviorManifests.FRLGBehaviors[behavior.Key] = InternalStrings.ResourceManager.GetString(behavior.Value);
                Console.WriteLine("[{0}] {1}", behavior.Key.ToString("X"), behavior.Value);
            }
        }
Example #40
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;
        }
Example #41
0
        /// <summary>
        /// Throws YamlException
        /// </summary>
        /// <param name="metaModel"></param>
        /// <param name="textReader"></param>
        public void Deserialize(MetaModel.MetaModel metaModel, TextReader textReader)
        {
            Parser p = new Parser(textReader);
            EventReader r = new EventReader(p);

            r.Expect<StreamStart>();
            r.Expect<DocumentStart>();
            r.Expect<MappingStart>();

            Scalar section = r.Peek<Scalar>();
            if (section.Value.Equals(Icons))
            {
                r.Expect<Scalar>();
                DeserializeIcons(metaModel, r);
                section = r.Peek<Scalar>();
            }

            if (section != null && section.Value.Equals(RecentFiles))
            {
                r.Expect<Scalar>();
                DeserializeRecentFiles(metaModel, r);
                section = r.Peek<Scalar>();
            }

            if (section != null && section.Value.Equals(LastOpenedFile))
            {
                r.Expect<Scalar>();
                metaModel.LastOpenedFile = r.Expect<Scalar>().Value;
                section = r.Peek<Scalar>();
            }

            if (section != null && section.Value.Equals(MapBackColor))
            {
                r.Expect<Scalar>();
                metaModel.MapEditorBackColor = (Color)(new ColorConverter().ConvertFromString(r.Expect<Scalar>().Value));
                section = r.Peek<Scalar>();
            }

            if (section != null && section.Value.Equals(NoteBackColor))
            {
                r.Expect<Scalar>();
                metaModel.NoteEditorBackColor = (Color)(new ColorConverter().ConvertFromString(r.Expect<Scalar>().Value));
                section = r.Peek<Scalar>();
            }

            if (section != null && section.Value.Equals(NodeStyles))
            {
                r.Expect<Scalar>();
                DeserializeNodeStyles(metaModel, r);
                //section = r.Peek<Scalar>(); //uncomment when adding another section
            }

            r.Expect<MappingEnd>();
            r.Expect<DocumentEnd>();
            r.Expect<StreamEnd>();
        }
        public static bool MigrateAssetIfNeeded(AssetMigrationContext context, PackageLoadingAssetFile loadAsset, string dependencyName, PackageVersion untilVersion = null)
        {
            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 = AssetFileSerializer.FindSerializer(assetFileExtension);
            if (!(serializer is YamlAssetSerializer))
                return false;

            // We've got a Yaml asset, let's get expected and serialized versions
            var serializedVersion = PackageVersion.Zero;
            PackageVersion 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 tagTypeRegistry = AssetYamlSerializer.Default.GetSerializerSettings().TagTypeRegistry;
                bool typeAliased;
                assetType = tagTypeRegistry.TypeFromTag(mappingStart.Tag, out typeAliased);

                var expectedVersions = AssetRegistry.GetCurrentFormatVersions(assetType);
                expectedVersion = expectedVersions?.FirstOrDefault(x => x.Key == dependencyName).Value ?? PackageVersion.Zero;

                Scalar assetKey;
                while ((assetKey = yamlEventReader.Allow<Scalar>()) != null)
                {
                    // Only allow Id before SerializedVersion
                    if (assetKey.Value == nameof(Asset.Id))
                    {
                        yamlEventReader.Skip();
                    }
                    else if (assetKey.Value == nameof(Asset.SerializedVersion))
                    {
                        // Check for old format: only a scalar
                        var scalarVersion = yamlEventReader.Allow<Scalar>();
                        if (scalarVersion != null)
                        {
                            serializedVersion = PackageVersion.Parse("0.0." + Convert.ToInt32(scalarVersion.Value, CultureInfo.InvariantCulture));

                            // Let's update to new format
                            using (var yamlAsset = loadAsset.AsYamlAsset())
                            {
                                yamlAsset.DynamicRootNode.RemoveChild(nameof(Asset.SerializedVersion));
                                AssetUpgraderBase.SetSerializableVersion(yamlAsset.DynamicRootNode, dependencyName, serializedVersion);

                                var baseBranch = yamlAsset.DynamicRootNode["~Base"];
                                if (baseBranch != null)
                                {
                                    var baseAsset = baseBranch["Asset"];
                                    if (baseAsset != null)
                                    {
                                        baseAsset.RemoveChild(nameof(Asset.SerializedVersion));
                                        AssetUpgraderBase.SetSerializableVersion(baseAsset, dependencyName, serializedVersion);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // New format: package => version mapping
                            yamlEventReader.Expect<MappingStart>();

                            while (!yamlEventReader.Accept<MappingEnd>())
                            {
                                var packageName = yamlEventReader.Expect<Scalar>().Value;
                                var packageVersion = PackageVersion.Parse(yamlEventReader.Expect<Scalar>().Value);

                                // For now, we handle only one dependency at a time
                                if (packageName == dependencyName)
                                {
                                    serializedVersion = packageVersion;
                                }
                            }

                            yamlEventReader.Expect<MappingEnd>();
                        }
                        break;
                    }
                    else
                    {
                        // If anything else than Id or SerializedVersion, let's stop
                        break;
                    }
                }
            }

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

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

                using (var yamlAsset = loadAsset.AsYamlAsset())
                {
                    var yamlRootNode = yamlAsset.RootNode;

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

                    // Instantiate asset updaters
                    var currentVersion = serializedVersion;
                    while (currentVersion != expectedVersion)
                    {
                        PackageVersion 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);

                        // Stop if the next version would be higher than what is expected
                        if (untilVersion != null && targetVersion > untilVersion)
                            break;

                        upgrader.Upgrade(context, dependencyName, currentVersion, targetVersion, yamlRootNode, loadAsset);
                        currentVersion = targetVersion;
                    }

                    // Make sure asset is updated to latest version
                    YamlNode serializedVersionNode;
                    PackageVersion newSerializedVersion = null;
                    if (yamlRootNode.Children.TryGetValue(new YamlScalarNode(nameof(Asset.SerializedVersion)), out serializedVersionNode))
                    {
                        var newSerializedVersionForDefaultPackage = ((YamlMappingNode)serializedVersionNode).Children[new YamlScalarNode(dependencyName)];
                        newSerializedVersion = PackageVersion.Parse(((YamlScalarNode)newSerializedVersionForDefaultPackage).Value);
                    }

                    if (untilVersion == null && newSerializedVersion != expectedVersion)
                    {
                        throw new InvalidOperationException($"Asset of type {assetType} was migrated, but still its new version {newSerializedVersion} doesn't match expected version {expectedVersion}.");
                    }

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

                return true;
            }

            return false;
        }
Example #43
0
        private void DeserializeScalarProperties(MapNode node, EventReader r)
        {
            Scalar prop = r.Peek<Scalar>();

            if (prop != null && prop.Value.Equals(Folded))
            {
                r.Expect<Scalar>();
                node.Folded = Boolean.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Link))
            {
                r.Expect<Scalar>();
                node.Link = r.Expect<Scalar>().Value;
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Created))
            {
                r.Expect<Scalar>();
                node.Created = DateHelper.ToDateTime(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Modified))
            {
                r.Expect<Scalar>();
                node.Modified = DateHelper.ToDateTime(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Bold))
            {
                r.Expect<Scalar>();
                node.Bold = Boolean.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Italic))
            {
                r.Expect<Scalar>();
                node.Italic = Boolean.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Strikeout))
            {
                r.Expect<Scalar>();
                node.Strikeout = Boolean.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(FontName))
            {
                r.Expect<Scalar>();
                node.FontName = r.Expect<Scalar>().Value;
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(FontSize))
            {
                r.Expect<Scalar>();
                node.FontSize = Single.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(BackColor))
            {
                r.Expect<Scalar>();
                node.BackColor = (Color)new ColorConverter().ConvertFromString(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Color))
            {
                r.Expect<Scalar>();
                node.Color = (Color)new ColorConverter().ConvertFromString(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Shape))
            {
                r.Expect<Scalar>();
                node.Shape = (NodeShape)Enum.Parse(typeof(NodeShape), r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(LineWidth))
            {
                r.Expect<Scalar>();
                node.LineWidth = Int32.Parse(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(LinePattern))
            {
                r.Expect<Scalar>();
                node.LinePattern = (DashStyle)Enum.Parse(typeof(DashStyle), r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(LineColor))
            {
                r.Expect<Scalar>();
                node.LineColor = (Color)new ColorConverter().ConvertFromString(r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(NoteText))
            {
                r.Expect<Scalar>();
                node.NoteText = r.Expect<Scalar>().Value;
                prop = r.Peek<Scalar>();
            }

            //if (prop != null && prop.Value.Equals(Image))
            //{
            //    r.Expect<Scalar>();
            //    node.Image = r.Expect<Scalar>().Value;
            //    prop = r.Peek<Scalar>();
            //}

            if (prop != null && prop.Value.Equals(ImageAlignment))
            {
                r.Expect<Scalar>();
                node.ImageAlignment = (ImageAlignment)Enum.Parse(typeof(ImageAlignment), r.Expect<Scalar>().Value);
                prop = r.Peek<Scalar>();
            }

            if (prop != null && prop.Value.Equals(Label))
            {
                r.Expect<Scalar>();
                node.Label = r.Expect<Scalar>().Value;
                //prop = r.Peek<Scalar>();
            }
        }
Example #44
0
        private void DeserializeRecentFiles(MetaModel.MetaModel metaModel, EventReader r)
        {
            r.Expect<SequenceStart>();

            while (r.Accept<Scalar>())
            {
                metaModel.RecentFiles.Add(r.Expect<Scalar>().Value);
            }

            r.Expect<SequenceEnd>();
        }
Example #45
0
        private void DeserializeNodeStyles(MetaModel.MetaModel metaModel, EventReader r)
        {
            r.Expect<SequenceStart>();

            while (r.Accept<MappingStart>())
            {
                DeserializeNodeStyle(metaModel, r);
            }

            r.Expect<SequenceEnd>();
        }
Example #46
0
        /// <summary>
        /// Parses the node represented by the next event in <paramref name="events" />.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="state">The state.</param>
        /// <returns>Returns the node that has been parsed.</returns>
        internal static YamlNode ParseNode(EventReader events, DocumentLoadingState state)
        {
            if (events.Accept<Scalar>())
            {
                return new YamlScalarNode(events, state);
            }

            if (events.Accept<SequenceStart>())
            {
                return new YamlSequenceNode(events, state);
            }

            if (events.Accept<MappingStart>())
            {
                return new YamlMappingNode(events, state);
            }

            if (events.Accept<AnchorAlias>())
            {
                AnchorAlias alias = events.Expect<AnchorAlias>();
                return state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value);
            }

            throw new ArgumentException("The current event is of an unsupported type.", "events");
        }
Example #47
0
        private void DeserializeNodeStyle(MetaModel.MetaModel metaModel, EventReader r)
        {
            var s = new NodeStyle();

            r.Expect<MappingStart>();

            r.Expect<Scalar>(); //Title
            s.Title = r.Expect<Scalar>().Value;

            r.Expect<Scalar>(); //RefNode
            s.RefNode = new MapYamlSerializer().Deserialize(r);

            r.Expect<MappingEnd>();

            metaModel.NodeStyles.Add(s);
        }
Example #48
0
        /// <summary>
        /// Name and Title are mandatory while shortcut is optional
        /// </summary>
        /// <param name="metaModel"></param>
        /// <param name="r"></param>
        private void DeserializeIcon(MetaModel.MetaModel metaModel, EventReader r)
        {
            string name = null, title = null, shortcut = null;
            r.Expect<MappingStart>();

            r.Expect<Scalar>(); //name
            name = r.Expect<Scalar>().Value;

            r.Expect<Scalar>();
            title = r.Expect<Scalar>().Value;

            if (r.Accept<Scalar>())
            {
                if(r.Expect<Scalar>().Value.Equals(Shortcut))
                {
                    shortcut = r.Expect<Scalar>().Value;
                }
            }
            r.Expect<MappingEnd>();

            metaModel.IconsList.Add(new ModelIcon(name, title, shortcut));
        }
        internal static void DeserializeHelper(Type tItem, EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, IList result, bool canUpdate)
        {
            reader.Expect<SequenceStart>();
            while (!reader.Accept<SequenceEnd>())
            {
                var current = reader.Parser.Current;

                var value = nestedObjectDeserializer(reader, tItem);
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType(value, tItem));
                }
                else if (canUpdate)
                {
                    var index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null);
                    promise.ValueAvailable += v => result[index] = TypeConverter.ChangeType(v, tItem);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                        current.Start,
                        current.End,
                        "Forward alias references are not allowed because this type does not implement IList<>"
                    );
                }
            }
            reader.Expect<SequenceEnd>();
        }
Example #50
0
    static void Main(string[] args)
    {
        OrderedDictionary zones;

        using (var sr = new StreamReader(args[0]))
        {
            var parser = new Parser(sr);
            var er = new EventReader(parser);

            er.Expect<StreamStart>();
            er.Expect<DocumentStart>();
            zones = (OrderedDictionary)GetData(er);
            er.Expect<DocumentEnd>();
            er.Expect<StreamEnd>();
        }

        // Remove modelsets key, not a real zone
        zones.Remove("modelsets");

        // Generate the C# structures
        //
        // We want a command dictionary that does not include the model data, which we
        // are not using.
        var commands = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
        foreach (DictionaryEntry zoneEntry in zones)
        {
            object zone = zoneEntry.Key;
            OrderedDictionary commandsInZone = (OrderedDictionary)zoneEntry.Value;
            OrderedDictionary newCommands = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);

            foreach (DictionaryEntry commandEntry in commandsInZone)
            {
                object command = commandEntry.Key;
                OrderedDictionary commandData = (OrderedDictionary)commandEntry.Value;

                OrderedDictionary values = (OrderedDictionary)commandData["values"];

                OrderedDictionary newValues = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
                foreach (DictionaryEntry valueEntry in values)
                {
                    object value = valueEntry.Key;
                    OrderedDictionary valueData = (OrderedDictionary)valueEntry.Value;

                    OrderedDictionary newValueData = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer)
                    {
                        { "name", valueData["name"] },
                        { "description", valueData["description"] }
                    };

                    newValues.Add(value, newValueData);
                }

                OrderedDictionary newCommandData = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer)
                {
                    { "name", commandData["name"] },
                    { "description", commandData["description"] },
                    { "values", newValues }
                };
                newCommands.Add(command, newCommandData);
            }
            commands.Add(zone, newCommands);
        }

        var zoneMappings = new OrderedDictionary()
        {
            // use main as default zone
            { "", "main" }
        };

        var commandMappings = Odict(
            from DictionaryEntry zoneEntry in zones
            select new DictionaryEntry
            {
                Key = zoneEntry.Key,
                Value = Odict(FindCommandAliases((OrderedDictionary)zoneEntry.Value))
            }
        );

        var valueMappings = Odict(
            from DictionaryEntry zoneEntry in zones
            let zone = zoneEntry.Key
            let commands_ = zoneEntry.Value
            select new DictionaryEntry
            {
                Key = zone,
                Value = Odict(
                    from DictionaryEntry commandEntry in (IEnumerable)commands_
                    let command = commandEntry.Key
                    let commandData = commandEntry.Value
                    select new DictionaryEntry
                    {
                        Key = command,
                        Value = Odict( FindValueAliases((OrderedDictionary)(commandData as IDictionary)["values"]) )
                    }
                )
            }
        );

        Console.OutputEncoding = Encoding.UTF8;

        Console.Write(
            "// Generated\n" +
            "// by {0}\n" +
            "// from {1}\n" +
            "// at {2}\n\n",
            Path.GetFileName(Environment.GetCommandLineArgs()[0]),
            Path.GetFileName(args[0]),
            DateTime.Now
        );

        Console.Write(
            "using System.Collections;\n" +
            "using System.Collections.Specialized;\n\n" +
            "namespace Eiscp.Core\n" +
            "{{\n" +
            "\tpublic static class EiscpCommands\n" +
            "\t{{\n" +
            "\t\tpublic static readonly OrderedDictionary Commands = {0};\n" +
            "\n" +
            "\t\tpublic static readonly OrderedDictionary ZoneMappings = {1};\n" +
            "\n" +
            "\t\tpublic static readonly OrderedDictionary CommandMappings = {2};\n" +
            "\n" +
            "\t\tpublic static readonly OrderedDictionary ValueMappings = {3};\n" +
            "\t}}\n" +
            "}}\n",
            PrintData(false, 2, commands),
            PrintData(false, 2, zoneMappings),
            PrintData(false, 2, commandMappings),
            PrintData(false, 2, valueMappings)
        );
    }
        bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
        {
            if(!typeof(IDictionary).IsAssignableFrom(expectedType))
            {
                value = false;
                return false;
            }

            reader.Expect<MappingStart>();

            var dictionary = (IDictionary)_objectFactory.Create(expectedType);
            while (!reader.Accept<MappingEnd>())
            {
                var key = nestedObjectDeserializer(reader, typeof(object));
                var keyPromise = key as IValuePromise;

                var keyValue = nestedObjectDeserializer(reader, typeof(object));
                var valuePromise = keyValue as IValuePromise;

                if (keyPromise == null)
                {
                    if (valuePromise == null)
                    {
                        // Happy path: both key and value are known
                        dictionary.Add(key, keyValue);
                    }
                    else
                    {
                        // Key is known, value is pending
                        valuePromise.ValueAvailable += v => dictionary.Add(key, v);
                    }
                }
                else
                {
                    if (valuePromise == null)
                    {
                        // Key is pending, value is known
                        keyPromise.ValueAvailable += v => dictionary.Add(v, keyValue);
                    }
                    else
                    {
                        // Both key and value are pending. We need to wait until both of them becom available.
                        var hasFirstPart = false;

                        keyPromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                dictionary.Add(v, keyValue);
                            }
                            else
                            {
                                key = v;
                                hasFirstPart = true;
                            }
                        };

                        valuePromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                dictionary.Add(key, v);
                            }
                            else
                            {
                                keyValue = v;
                                hasFirstPart = true;
                            }
                        };
                    }
                }
            }
            value = dictionary;

            reader.Expect<MappingEnd>();

            return true;
        }
Example #52
0
        /// <summary>
        /// Deserializes an object of the specified type.
        /// </summary>
        /// <param name="reader">The <see cref="EventReader" /> where to deserialize the object.</param>
        /// <param name="type">The static type of the object to deserialize.</param>
        /// <param name="options">Options that control how the deserialization is to be performed.</param>
        /// <returns>Returns the deserialized object.</returns>
        public object Deserialize(EventReader reader, Type type, DeserializationOptions options = DeserializationOptions.None)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var hasStreamStart = reader.Allow<StreamStart>() != null;

            var hasDocumentStart = reader.Allow<DocumentStart>() != null;

            if (hasDocumentStart)
            {
                reader.Expect<DocumentEnd>();
            }

            if (hasStreamStart)
            {
                reader.Expect<StreamEnd>();
            }
        }
        private static void DeserializeHelper(Type tKey, Type tValue, EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, IDictionary result)
        {
            reader.Expect<MappingStart>();
            while (!reader.Accept<MappingEnd>())
            {
                var key = nestedObjectDeserializer(reader, tKey);
                var keyPromise = key as IValuePromise;

                var value = nestedObjectDeserializer(reader, tValue);
                var valuePromise = value as IValuePromise;

                if (keyPromise == null)
                {
                    if (valuePromise == null)
                    {
                        // Happy path: both key and value are known
                        result[key] = value;
                    }
                    else
                    {
                        // Key is known, value is pending
                        valuePromise.ValueAvailable += v => result[key] = v;
                    }
                }
                else
                {
                    if (valuePromise == null)
                    {
                        // Key is pending, value is known
                        keyPromise.ValueAvailable += v => result[v] = value;
                    }
                    else
                    {
                        // Both key and value are pending. We need to wait until both of them becom available.
                        var hasFirstPart = false;

                        keyPromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                result[v] = value;
                            }
                            else
                            {
                                key = v;
                                hasFirstPart = true;
                            }
                        };

                        valuePromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                result[key] = v;
                            }
                            else
                            {
                                value = v;
                                hasFirstPart = true;
                            }
                        };
                    }
                }
            }
            reader.Expect<MappingEnd>();
        }
Example #54
0
        private object DeserializeValue(EventReader reader, Type expectedType, object context)
        {
            if (reader.Accept<AnchorAlias>())
            {
                throw new NotImplementedException();
                //return context.Anchors[reader.Expect<AnchorAlias>().Value];
            }

            var nodeEvent = (NodeEvent)reader.Parser.Current;

            if (IsNull(nodeEvent))
            {
                reader.Expect<NodeEvent>();
                AddAnchoredObject(nodeEvent, null, context.Anchors);
                return null;
            }

            object result = DeserializeValueNotNull(reader, context, nodeEvent, expectedType);
            return ObjectConverter.Convert(result, expectedType);
        }