Exemple #1
0
        public void TestSuperclassedArray()
        {
            var x = new CSuperArray
            {
                Arr = new int[] { 1, 3, 5 }
            };

            var s   = new CSerializer();
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(typeof(CSuperArray).AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(elem, s.Context.TypeAttributeName),
                            "Type of the root node is wrong");

            var e = (XmlElement)elem.SelectSingleNode("Arr");

            Assert.IsNotNull(e, "Missing Arr element");
            Assert.AreEqual(x.Arr.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(e, s.Context.TypeAttributeName),
                            "Type Attribute Error");
            Assert.AreEqual(x.Arr.Length.ToString(),
                            XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName),
                            "Length of Array Attribute is wrong");
            Assert.AreEqual("1,3,5", elem.InnerText, "Inner Text for the array");
        }
        public static void LoadRepositoryXml(string filePath, ContentManager content)
        {
            XmlDocument document = new XmlDocument();

            document.Load(filePath);

            foreach (XmlNode itemNode in document.SelectNodes("ItemRepository/Item"))
            {
                Item item = new Item();
                item.Name = XmlExtensions.GetAttributeValue(itemNode, "Name", null, true);

                item.FriendlyName = itemNode.SelectSingleNode("FriendlyName").InnerText;
                item.Description  = itemNode.SelectSingleNode("Description").InnerText;
                item.Weight       = XmlExtensions.GetAttributeValue <float>(itemNode, "Weight", 0);
                item.ItemType     = (ItemType)Enum.Parse(typeof(ItemType), XmlExtensions.GetAttributeValue(itemNode, "ItemType", null, true));

                foreach (XmlNode drawableSetNode in itemNode.SelectNodes("Drawables/Drawable"))
                {
                    string src = XmlExtensions.GetAttributeValue(drawableSetNode, "src");
                    DrawableSet.LoadDrawableSetXml(item.Drawables, src, content);
                }

                GameItems.Add(item.Name, item);
            }
        }
Exemple #3
0
        public void TestExternalBaseSurrogate()
        {
            var x = new CMySuperStd
            {
                Name = "Alyssa",
                Age  = 21,
                Sex  = "Yes"
            };

            var c = new CSerializationContext();

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(3, elem.ChildNodes.Count, "Child Node Count is wrong");
            Assert.AreEqual(x.Name, XmlExtensions.GetElementValue(elem, "Name"), "Name");
            Assert.AreEqual(x.Age.ToString(), XmlExtensions.GetElementValue(elem, "Age"), "Age");
            Assert.AreEqual(x.Sex, XmlExtensions.GetElementValue(elem, "Sex"), "Sex");

            PrintLine();

            c.RegisterExternalSurrogate(typeof(CStdBaseObject), new CStdExternalSurrogate());

            doc = s.Serialize(x);
            Print(doc);
            elem = doc.DocumentElement;

            Assert.AreEqual(1, elem.ChildNodes.Count, "Child Node Count is wrong");
            Assert.AreEqual(x.Name, XmlExtensions.GetAttributeValue(elem, "NAME"), "Name");
            Assert.AreEqual(x.Age.ToString(), XmlExtensions.GetAttributeValue(elem, "AGE"), "Age");
            Assert.AreEqual(x.Sex, XmlExtensions.GetElementValue(elem, "Sex"), "Sex");
        }
Exemple #4
0
        public void TestNullableType()
        {
            int?x = null;
            var s = new CSerializer();

            CSerializationContext.Global.SetVerbose();

            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(CSerializationContext.Global.NullAttributeValue,
                            XmlExtensions.GetAttributeValue(elem, CSerializationContext.Global.NullAttributeName),
                            "Should be null");
            Assert.AreEqual("", elem.InnerText, "Should be no innerText");

            PrintLine();

            x   = 69;
            doc = s.Serialize(x);
            Print(doc);
            elem = doc.DocumentElement;
            Assert.AreEqual(x.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(elem, CSerializationContext.Global.TypeAttributeName),
                            "The Type is wrong");
        }
Exemple #5
0
        public void TestExternalSurrogate()
        {
            var x = new CStdBaseObject
            {
                Name = "Alyssa",
                Age  = 21
            };
            var c = new CSerializationContext();

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(2, elem.ChildNodes.Count, "Child Node Count is wrong");
            Assert.AreEqual(x.Name, XmlExtensions.GetElementValue(elem, "Name"), "Name");
            Assert.AreEqual(x.Age.ToString(), XmlExtensions.GetElementValue(elem, "Age"), "Age");

            Console.WriteLine(
                "\r\n\r\n-----------------------------------------------------------------------------\r\n\r\n");
            c.RegisterExternalSurrogate(typeof(CStdBaseObject), new CStdExternalSurrogate());

            doc = s.Serialize(x);
            Print(doc);
            elem = doc.DocumentElement;

            Assert.AreEqual(0, elem.ChildNodes.Count, "Child Node Count is wrong");
            Assert.AreEqual(x.Name, XmlExtensions.GetAttributeValue(elem, "NAME"), "Name");
            Assert.AreEqual(x.Age.ToString(), XmlExtensions.GetAttributeValue(elem, "AGE"), "Age");
        }
Exemple #6
0
        public void TestMultidimStringArray()
        {
            string[,] x;
            x = (string[, ])Array.CreateInstance(typeof(string), new int[] { 2, 2 }, new int[] { 5, 9 });

            x[5, 9]  = "first";
            x[5, 10] = "second";
            x[6, 9]  = "third";
            x[6, 10] = "fourth";

            var c = new CSerializationContext();

            c.SetConcise();

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(1, elem.ChildNodes.Count, "Should be one child (an XmlText node)");
            Assert.AreEqual("2,2",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayAttributeName),
                            "Array Lengths are wrong");
            Assert.AreEqual("5,9",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayLowerBoundAttribute),
                            "Array Lowerbounds are wrong");
            Assert.AreEqual("first,second,third,fourth", elem.InnerText, "The text for the multidim array is wrong");
        }
Exemple #7
0
        private static void AssureCorrectReference(XmlElement elem, int a1, int a2)
        {
            var n  = elem.SelectSingleNode("//_[@_I=" + a1 + "]");
            var id = XmlExtensions.GetAttributeValue(n, "_ID");

            var n2  = elem.SelectSingleNode("//_[@_I=" + a2 + "]");
            var rid = XmlExtensions.GetAttributeValue(n2, "_RID");

            Assert.AreEqual(id, rid, "ID of referenced element didn't match");
        }
Exemple #8
0
        private static bool CreateFromXml(XmlElement _node, CWorkingObject _object, CDeserializer _framework)
        {
            var x = _object.GetExistingOrCreateNew <CStdImplicitSurrogate>();

            x.Name = XmlExtensions.GetAttributeValue(_node, "NAME");
            x.Age  = int.Parse(XmlExtensions.GetAttributeValue(_node, "AGE"));

            STATUS = ETestStatus.IMPLICIT_DESERIALIZER;
            return(true);
        }
Exemple #9
0
        private static void CreateFromXml(XmlElement _node, CWorkingObject _object, CDeserializer _framework)
        {
            var x = new CVoidImplicitSurrogate();

            _object.Set(x);

            x.Name = XmlExtensions.GetAttributeValue(_node, "NAME");
            x.Age  = int.Parse(XmlExtensions.GetAttributeValue(_node, "AGE"));

            STATUS = ETestStatus.IMPLICIT_DESERIALIZER_VOID;
        }
Exemple #10
0
            public bool Deserialize(CWorkingObject _workingObject,
                                    XmlElement _parentNode,
                                    CDeserializer _deserializer)
            {
                var sLen = XmlExtensions.GetAttributeValue(_parentNode, "MYLEN");
                var len  = int.Parse(sLen);

                _workingObject.Set(Array.CreateInstance(typeof(int), len + 1));
                // This actually is a no-no, but i'm testing to make sure
                // that this is really the array that's being returned.
                return(false);
            }
Exemple #11
0
        public void TestCPersonExplicitArrays()
        {
            var x = new CPerson();
            var c = new CSerializationContext
            {
                FixM_ = true,
                AllArraysHaveExplicitElements = true,
                ArrayElementsIncludeIndicies  = true
            };

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(x.m_name, XmlExtensions.GetElementValue(elem, "Name"), "Name");
            Assert.AreEqual(x.m_age.ToString(), XmlExtensions.GetElementValue(elem, "Age"), "Age");

            var e = (XmlElement)elem.SelectSingleNode("KidsNames");

            Assert.IsNotNull(e, "Missing KidsNames element");
            Assert.AreEqual("3", XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName), "Kids Array Count");
            for (var i = 0; i < x.m_kidsNames.Length; i++)
            {
                Assert.AreEqual(x.m_kidsNames[i], e.ChildNodes[i].InnerText, "Kid " + i);
                Assert.AreEqual(i.ToString(),
                                XmlExtensions.GetAttributeValue(e.ChildNodes[i], s.Context.ArrayIndexAttributeName),
                                "Array Index " + i);
            }

            e = (XmlElement)elem.SelectSingleNode("ANullValue");
            Assert.IsNotNull(e, "Missing ANullValue element");
            Assert.AreEqual(s.Context.NullAttributeValue,
                            XmlExtensions.GetAttributeValue(e, s.Context.NullAttributeName),
                            "Null Attribute Error");

            e = (XmlElement)elem.SelectSingleNode("Address");
            Assert.IsNotNull(e, "Missing Address element");
            Assert.AreEqual(x.m_address.m_city, XmlExtensions.GetElementValue(e, "City"), "Address-City");
            Assert.AreEqual(x.m_address.m_street, XmlExtensions.GetElementValue(e, "Street"), "Address-Street");
            Assert.AreEqual(x.m_address.m_zip.ToString(), XmlExtensions.GetElementValue(e, "Zip"), "Address-Zip");

            e = (XmlElement)elem.SelectSingleNode("OtherAddress");
            Assert.IsNotNull(e, "Other Address Missing");
            var sa = x.m_otherAddress as CSuperAddress;

            Assert.AreEqual(sa.m_country, XmlExtensions.GetElementValue(e, "Country"), "OtherAddress-Country");
            Assert.AreEqual(sa.m_city, XmlExtensions.GetElementValue(e, "City"), "Address-City");
            Assert.AreEqual(sa.m_street, XmlExtensions.GetElementValue(e, "Street"), "Address-Street");
            Assert.AreEqual(sa.m_zip.ToString(), XmlExtensions.GetElementValue(e, "Zip"), "Address-Zip");
        }
Exemple #12
0
        public void TestNullSerialize()
        {
            var s   = new CSerializer();
            var doc = s.Serialize(null);

            Print(doc);
            var e = doc.DocumentElement;

            Assert.AreEqual(s.Context.RootElementName, e.Name, "Root name is incorrect");
            Assert.AreEqual(s.Context.NullAttributeValue,
                            XmlExtensions.GetAttributeValue(e, s.Context.NullAttributeName),
                            "Null attribute was not there");
        }
Exemple #13
0
        public void TestNonstandardArray()
        {
            var x = Array.CreateInstance(typeof(int), new int[] { 10 }, new int[] { 5 });
            var s = new CSerializer();

            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(x.GetLowerBound(0).ToString(),
                            XmlExtensions.GetAttributeValue(elem, s.Context.ArrayLowerBoundAttribute),
                            "Lower Bound not set right");
        }
Exemple #14
0
        public void TestCPerson()
        {
            var x = new CPerson();

            CSerializationContext.Global.FixM_ = true;

            var s   = new CSerializer();
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(x.m_name, XmlExtensions.GetElementValue(elem, "Name"), "Name");
            Assert.AreEqual(x.m_age.ToString(), XmlExtensions.GetElementValue(elem, "Age"), "Age");

            var e = (XmlElement)elem.SelectSingleNode("KidsNames");

            Assert.IsNotNull(e, "Missing KidsNames element");
            Assert.AreEqual("3", XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName), "Kids Array Count");
            Assert.AreEqual("Maggie,Lisa,Bart", e.InnerText, "Kids Names");

            e = (XmlElement)elem.SelectSingleNode("KidsAges");
            Assert.IsNotNull(e, "Missing KidsNames element");
            Assert.AreEqual("3",
                            XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName),
                            "KidsAges Array Count");
            Assert.AreEqual("1,7,9", e.InnerText, "Kids Names");

            e = (XmlElement)elem.SelectSingleNode("ANullValue");
            Assert.IsNotNull(e, "Missing ANullValue element");
            Assert.AreEqual(s.Context.NullAttributeValue,
                            XmlExtensions.GetAttributeValue(e, s.Context.NullAttributeName),
                            "Null Attribute Error");

            e = (XmlElement)elem.SelectSingleNode("Address");
            Assert.IsNotNull(e, "Missing Address element");
            Assert.AreEqual(x.m_address.m_city, XmlExtensions.GetElementValue(e, "City"), "Address-City");
            Assert.AreEqual(x.m_address.m_street, XmlExtensions.GetElementValue(e, "Street"), "Address-Street");
            Assert.AreEqual(x.m_address.m_zip.ToString(), XmlExtensions.GetElementValue(e, "Zip"), "Address-Zip");

            e = (XmlElement)elem.SelectSingleNode("OtherAddress");
            Assert.IsNotNull(e, "Other Address Missing");
            var sa = x.m_otherAddress as CSuperAddress;

            Assert.AreEqual(sa.m_country, XmlExtensions.GetElementValue(e, "Country"), "OtherAddress-Country");
            Assert.AreEqual(sa.m_city, XmlExtensions.GetElementValue(e, "City"), "Address-City");
            Assert.AreEqual(sa.m_street, XmlExtensions.GetElementValue(e, "Street"), "Address-Street");
            Assert.AreEqual(sa.m_zip.ToString(), XmlExtensions.GetElementValue(e, "Zip"), "Address-Zip");
        }
        public bool Deserialize(CWorkingObject _object, XmlElement _node, CDeserializer _framework)
        {
            if (_object.WorkingObject == null)
            {
                _object.Set(new CStdBaseObject());
            }

            var x = _object.WorkingObject as CStdBaseObject;

            x.Name = XmlExtensions.GetAttributeValue(_node, "NAME");
            x.Age  = int.Parse(XmlExtensions.GetAttributeValue(_node, "AGE"));

            CStdBaseObject.STATUS = ETestStatus.EXTERNAL_DESERIALIZER;
            return(true);
        }
Exemple #16
0
        private static bool CreateFromXml(CWorkingObject _object, XmlElement _node, CDeserializer _framework)
        {
            if (_object.WorkingObject == null)
            {
                _object.Set(new CIncompleteImplicitSurrogate());
            }

            if ("Yes" != XmlExtensions.GetAttributeValue(_node, "Incomplete"))
            {
                throw new InvalidOperationException(
                          "Expected an attribute named 'Incomplete' and that attrribute to have the value 'Yes'.");
            }

            STATUS = ETestStatus.IMPLICIT_DESERIALIZER_INCOMPLETE;
            return(false);
        }
Exemple #17
0
        public void TestInvalidType()
        {
            object x = new IntPtr();

            var s    = new CSerializer();
            var doc  = s.Serialize(x);
            var elem = doc.DocumentElement;

            Print(doc);

            Assert.AreEqual(0, elem.ChildNodes.Count, "Should be no children");
            Assert.AreEqual(1, elem.Attributes.Count, "Should be only 1 attribute (the Type)");
            Assert.AreEqual(x.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(elem, s.Context.TypeAttributeName),
                            "The Type attribute is wrong");
        }
Exemple #18
0
        public void TestSerializePrimitive()
        {
            var x = 69;

            var s   = new CSerializer();
            var doc = s.Serialize(x);

            Print(doc);
            var e = doc.DocumentElement;

            Assert.AreEqual(s.Context.RootElementName, e.Name, "Root name is incorrect");
            Assert.AreEqual(x.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(e, s.Context.TypeAttributeName),
                            "Type attribute is incorrect");
            Assert.AreEqual(x.ToString(), e.InnerText, "The value itself was wrong");
        }
Exemple #19
0
        public void TestArray_Primitive()
        {
            var a = new int[] { 1, 2, 3 };

            var s   = new CSerializer();
            var doc = s.Serialize(a);

            Print(doc);
            var e = doc.DocumentElement;

            Assert.AreEqual(a.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(e, s.Context.TypeAttributeName),
                            "The Type attribute is wrong");
            Assert.AreEqual(int.Parse(XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName)),
                            a.Length,
                            "Array Attribute has wrong length value");
            Assert.AreEqual("1,2,3", e.InnerText, "Comma-Separated List is wrong.");
        }
Exemple #20
0
        public void TestImplicitSerializer()
        {
            var x = new CStdImplicitSurrogate
            {
                Name = "Homer",
                Age  = 40
            };

            var s   = new CSerializer();
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(0, elem.ChildNodes.Count, "Node Count");
            Assert.AreEqual(x.Name, XmlExtensions.GetAttributeValue(elem, "NAME"), "Name");
            Assert.AreEqual(x.Age.ToString(), XmlExtensions.GetAttributeValue(elem, "AGE"), "Age");
        }
Exemple #21
0
        public void TestMultidimArray()
        {
            var x = new int[3, 3, 5];

            for (var j = 0; j < 3; j++)
            {
                for (var k = 0; k < 3; k++)
                {
                    for (var l = 0; l < 5; l++)
                    {
                        x[j, k, l] = j * 100 + k * 10 + l;
                    }
                }
            }

            var c = new CSerializationContext();

            c.SetVerbose();

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(3 * 3 * 5, elem.ChildNodes.Count, "Child node count is wrong");
            Assert.AreEqual("3,3,5",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayAttributeName),
                            "Array Lengths are wrong");
            Assert.AreEqual("0,0,0",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayLowerBoundAttribute),
                            "Array lower-bounds are wrong");

            PrintLine();

            c.SetConcise();
            doc = s.Serialize(x);
            Print(doc);
            elem = doc.DocumentElement;

            Assert.AreEqual(1, elem.ChildNodes.Count, "Child node count is wrong");
            Assert.IsTrue(elem.InnerText.StartsWith("0,1,2,3,4,10,11,12"), "The inner text doesn't look right");
        }
Exemple #22
0
        public void TestSparseArray()
        {
            var x = new string[100];

            x[5]  = "Something";
            x[49] = "Else";
            x[50] = "?";
            x[75] = "";

            var c = new CSerializationContext
            {
                AllArraysHaveExplicitElements = true,
                RemoveNullValuesFromXml       = true
            };
            var s = new CSerializer(c);

            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(4, elem.ChildNodes.Count, "Child node count is wrong");
            Assert.AreEqual(x.Length.ToString(),
                            XmlExtensions.GetAttributeValue(elem, c.ArrayAttributeName),
                            "Array Length value is wrong");

            Assert.AreEqual("5",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[0], c.ArrayIndexAttributeName),
                            "Index for element 0 is wrong");
            Assert.AreEqual("49",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[1], c.ArrayIndexAttributeName),
                            "Index for element 1 is wrong");
            Assert.IsNull(XmlExtensions.GetAttributeValue(elem.ChildNodes[2], c.ArrayIndexAttributeName),
                          "Should have no index attribute on consecutive elements");
            Assert.AreEqual("75",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[3], c.ArrayIndexAttributeName),
                            "Index for element 3 is wrong");

            Assert.AreEqual(x[5], elem.ChildNodes[0].InnerText, "Value of child 0 incorrect");
            Assert.AreEqual(x[49], elem.ChildNodes[1].InnerText, "Value of child 1 incorrect");
            Assert.AreEqual(x[50], elem.ChildNodes[2].InnerText, "Value of child 2 incorrect");
            Assert.AreEqual(x[75], elem.ChildNodes[3].InnerText, "Value of child 3 incorrect");
        }
Exemple #23
0
        public void TestSparseMultidimArray()
        {
            object[,,] x;
            x          = (object[, , ])Array.CreateInstance(typeof(object), new int[] { 3, 4, 5 }, new int[] { 3, 2, 1 });
            x[3, 5, 3] = Guid.NewGuid();
            x[4, 4, 1] = "hello";
            x[4, 4, 2] = "Good Bye";
            x[4, 4, 3] = "he" + "llo"; // interns to "hello", and shared with the "hello" at [4,4,1]
            x[5, 2, 5] = 678;

            var c = new CSerializationContext();

            c.SetConcise();

            var s   = new CSerializer(c);
            var doc = s.Serialize(x);

            Print(doc);
            var elem = doc.DocumentElement;

            Assert.AreEqual(5, elem.ChildNodes.Count, "Number of elements is wrong");
            Assert.AreEqual("3,4,5",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayAttributeName),
                            "Array Lengths are wrong");
            Assert.AreEqual("3,2,1",
                            XmlExtensions.GetAttributeValue(elem, c.ArrayLowerBoundAttribute),
                            "Array Lowerbounds are wrong");

            Assert.AreEqual("3,5,3",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[0], c.ArrayIndexAttributeName),
                            "Index value is wrong");
            Assert.AreEqual("4,4,1",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[1], c.ArrayIndexAttributeName),
                            "Index value is wrong");
            Assert.AreEqual("5,2,5",
                            XmlExtensions.GetAttributeValue(elem.ChildNodes[4], c.ArrayIndexAttributeName),
                            "Index value is wrong");
            Assert.IsNull(XmlExtensions.GetAttributeValue(elem.ChildNodes[2], c.ArrayIndexAttributeName),
                          "Should be no index attribute for sequential element");
            Assert.IsNull(XmlExtensions.GetAttributeValue(elem.ChildNodes[3], c.ArrayIndexAttributeName),
                          "Should be no index attribute for sequential element");
        }
Exemple #24
0
        public void TestArray_String()
        {
            var a = new string[] { "hello,", "homer", "", "!", null, "what?" };

            var context = new CSerializationContext();

            var s   = new CSerializer(context);
            var doc = s.Serialize(a);

            Print(doc);
            var e = doc.DocumentElement;

            Assert.AreEqual(a.GetType().AssemblyQualifiedName,
                            XmlExtensions.GetAttributeValue(e, s.Context.TypeAttributeName),
                            "The Type attribute is wrong");
            Assert.AreEqual(int.Parse(XmlExtensions.GetAttributeValue(e, s.Context.ArrayAttributeName)),
                            a.Length,
                            "Array Attribute has wrong length value");
            Assert.AreEqual(@"hello\`,homer,\_,!,,what?", e.InnerText, "Comma-Separated List is wrong.");
        }
Exemple #25
0
        public void TestCircularReference()
        {
            var a = new CLinkedList
            {
                Data = 69
            };

            var b = new CLinkedList
            {
                Data = 70
            };

            a.Next = b;
            b.Next = a;

            var c = new CSerializationContext();

            c.SetVerbose();
            var s   = new CSerializer(c);
            var doc = s.Serialize(a);

            Print(doc);
            var elem = doc.DocumentElement;

            var id = XmlExtensions.GetAttributeValue(elem, c.ReferenceIdAttributeName);

            Assert.AreEqual("69", XmlExtensions.GetElementValue(elem, "Data"), "The first node's data is wrong");
            var e2 = (XmlElement)elem.SelectSingleNode("Next");

            Assert.AreEqual("70", XmlExtensions.GetElementValue(e2, "Data"), "The second node's data is wrong");

            var e3  = (XmlElement)e2.SelectSingleNode("Next");
            var rid = XmlExtensions.GetAttributeValue(e3, c.ReferToAttributeName);

            Assert.AreEqual(id, rid, "The reference to the first node is wrong");
        }
        public void TestBothInterfaceAndFullSerialization()
        {
            var ca = new CClassWithBothTypesOfCollections();

            for (var i = 0; i < 8; i++)
            {
                var name = "Address:" + i;
                ca.ByName[name] = CAddress.Get();
            }
            for (var i = 0; i < 6; i++)
            {
                ca.AsStack.Push(CAddress.Get());
            }


            var ctx = new CSerializationContext();

            ctx.SetConcise();
            ctx.RemoveNullValuesFromXml = false; // required for one test that checks the # of child elements where some of them are null

            var s   = new CSerializer(ctx);
            var doc = s.Serialize(ca);

            Print(doc);

            var dict = doc.DocumentElement["ByName"];

            Assert.AreEqual(ca.ByName.Count,
                            dict.ChildNodes.Count,
                            "Child Node Count should match Dictionary Count when using an Interface surrogate");

            var stak = doc.DocumentElement["AsStack"];
            //var stakArr = stak.ChildNodes[0];
            //Assert.AreEqual( ca.AsStack.Count, stakArr.ChildNodes.Count, $"The Stack size is incorrect" );

            var stakCount = stak["_size"];

            Assert.AreEqual(int.Parse(stakCount.InnerText), ca.AsStack.Count, "The number of stack elements is wrong");

            var stakElems = stak["_array"];
            var c         = int.Parse(XmlExtensions.GetAttributeValue(stakElems, ctx.ArrayAttributeName));

            Assert.IsTrue(c >= ca.AsStack.Count, "Not enough child elements for Stack");

            var d  = new CDeserializer(ctx);
            var cb = (CClassWithBothTypesOfCollections)d.Deserialize(doc);

            foreach (var key in ca.ByName.Keys)
            {
                Assert.AreEqual(ca.ByName[key].m_street, cb.ByName[key].m_street, "Incorrect Address for key: " + key);
                Assert.AreEqual(ca.ByName[key].m_city, cb.ByName[key].m_city, "Incorrect Address for key: " + key);
                Assert.AreEqual(ca.ByName[key].m_zip, cb.ByName[key].m_zip, "Incorrect Address for key: " + key);
            }

            var s_a = ca.AsStack.ToArray();
            var s_b = cb.AsStack.ToArray();

            Assert.AreEqual(s_a.Length, s_b.Length, "Lengths of Stacks are wrong");

            for (var i = 0; i < s_a.Length; i++)
            {
                var aa = s_a[i] as CAddress;
                var ab = s_b[i] as CAddress;

                CompareCAddresses(aa, ab);
            }
        }
Exemple #27
0
        /// <summary>
        /// Loads a DrawableSet file into a specified DrawableSet object.
        /// The method requires the string path to the xml file containing the drawable data and a reference to the
        /// ContentManager. An optional Layer value can be specified for the ordering of the drawables in the
        /// DrawableSet. Currently only supports loading of Animation objects.
        /// </summary>
        /// <param name="drawableSet">DrawableSet object to load the animations into.</param>
        /// <param name="path">String path to the XML formatted .anim file</param>
        /// <param name="content">Reference to the ContentManager instance being used in the application</param>
        public static void LoadDrawableSetXml(DrawableSet drawableSet, string path, ContentManager content, double startTimeMS = 0)
        {
            XmlDocument document = new XmlDocument();

            document.Load(path);

            foreach (XmlNode animNode in document.SelectNodes("Animations/Animation"))
            {
                int  frameDelay = XmlExtensions.GetAttributeValue <int>(animNode, "FrameDelay", 90);
                bool loop       = XmlExtensions.GetAttributeValue <bool>(animNode, "Loop", true);
                int  layer      = XmlExtensions.GetAttributeValue <int>(animNode, "Layer", 0);

                string   state       = XmlExtensions.GetAttributeValue(animNode, "State");
                string   group       = XmlExtensions.GetAttributeValue(animNode, "Group", "");
                string   spriteSheet = XmlExtensions.GetAttributeValue(animNode, "SpriteSheet");
                string[] offset      = XmlExtensions.GetAttributeValue(animNode, "Offset", "0, 0").Split(',');
                string[] origin      = XmlExtensions.GetAttributeValue(animNode, "Origin", "0.5, 1.0").Split(',');

                Vector2 offsetVector = new Vector2((float)Convert.ToDouble(offset[0]), (float)Convert.ToDouble(offset[1]));
                Vector2 originVector = new Vector2((float)Convert.ToDouble(origin[0]), (float)Convert.ToDouble(origin[1]));

                XmlNodeList frameNodes = animNode.SelectNodes("Frames/Frame");
                Rectangle[] frames     = new Rectangle[frameNodes.Count];

                for (int i = 0; i < frameNodes.Count; i++)
                {
                    string[] tokens = frameNodes[i].InnerText.Split(',');
                    if (tokens.Length != 4)
                    {
                        throw new FormatException("Expected 4 Values for Frame Definition: X, Y, Width, Height");
                    }

                    int x      = Convert.ToInt32(tokens[0]);
                    int y      = Convert.ToInt32(tokens[1]);
                    int width  = Convert.ToInt32(tokens[2]);
                    int height = Convert.ToInt32(tokens[3]);

                    frames[i] = new Rectangle(x, y, width, height);
                }

                Animation animation = new Animation(content.Load <Texture2D>(spriteSheet), frames, frameDelay, loop);
                animation.Origin = originVector;

                // TODO: Requires possible revision of code.
                // Allow support for specifying glob patterns in the case of state names.
                if (state.Contains("*"))
                {
                    // Use Glob patterns in favour of regular expressions.
                    state = Regex.Escape(state).Replace(@"\*", ".*").Replace(@"\?", ".");
                    Regex regexMatcher = new Regex(state);

                    foreach (string drawableSetState in drawableSet.GetStates())
                    {
                        if (regexMatcher.IsMatch(drawableSetState))
                        {
                            GameDrawableInstance instance = drawableSet.Add(drawableSetState, animation, group);
                            instance.StartTimeMS = startTimeMS;
                            instance.Layer       = layer;
                            instance.Offset      = offsetVector;
                        }
                    }
                }
                else
                {
                    GameDrawableInstance instance = drawableSet.Add(state, animation, group);
                    instance.StartTimeMS = startTimeMS;
                    instance.Layer       = layer;
                    instance.Offset      = offsetVector;
                }
            }
        }
        public void AddAttributeTest()
        {
            var e = m_xml.DocumentElement;

            e = e["b"];
            const string v1 = "furry";

            e.AddAttribute(v1, true);

            var node = m_xml.DocumentElement.SelectSingleNode(@"/a/b[@furry]/attribute::furry");

            Assert.AreEqual <string>("True", node.Value, "Getting the 'Furry' attribute");

            var lookHere = m_xml.DocumentElement.SelectSingleNode(@"//e");

            lookHere.AddAttribute("trunk", "yes");
            node = m_xml.DocumentElement.SelectSingleNode(@"/a/d/e/attribute::trunk");
            Assert.AreEqual <string>("yes", node.Value, "Elephant's Trunk");

            var actual = lookHere.GetAttributeValue("trunk");

            Assert.AreEqual <string>("yes", actual, "its wrong from the GetAttributeValue method");
            actual = lookHere.GetAttributeValue("hoser");
            Assert.IsNull(actual, "The 'horse' shouldn't exist.");

            actual = lookHere.GetRequiredAttribute("trunk");
            Assert.AreEqual <string>("yes", actual, "The Trunk was there");

            try
            {
                XmlExtensions.GetAttributeValue(null, "homer");
                Assert.Fail("Expected exception of type '" + typeof(ArgumentNullException).Name + "' but none was thrown.");
            }
            catch (ArgumentNullException) { }
            catch (Exception __e)
            {
                Assert.Fail("Expected exception of type ArgumentNullException, but " + __e.GetType().ToString() + " was generated instead.");
            }

            try
            {
                XmlExtensions.GetRequiredAttribute(null, "homer");
                Assert.Fail("Expected exception of type '" + typeof(ArgumentNullException).Name + "' but none was thrown.");
            }
            catch (ArgumentNullException) { }
            catch (Exception __e)
            {
                Assert.Fail("Expected exception of type ArgumentNullException, but " + __e.GetType().ToString() + " was generated instead.");
            }

            try
            {
                lookHere.GetRequiredAttribute("homer");
                Assert.Fail("Expected exception of type '" + typeof(ArgumentException).Name + "' but none was thrown.");
            }
            catch (ArgumentException) { }
            catch (Exception __e)
            {
                Assert.Fail("Expected exception of type ArithmeticException, but " + __e.GetType().ToString() + " was generated instead.");
            }
        }
Exemple #29
0
        // TODO: Support for zlib compression of tile data  (Zlib.NET)
        // http://stackoverflow.com/questions/6620655/compression-and-decompression-problem-with-zlib-net
        // Reads and converts and .tmx file to a TiledMap object. Doing so does NOT load appropriate tile textures into memory.
        // In order for textures to be loaded, the LoadContent(ContentManager) method must be called. This is usually automatically
        // performed by the TeeEngine when calling its LoadMap(TiledMap) method. However, it may be called independently if needs be.
        public static TiledMap LoadTmxFile(string file)
        {
            if (File.Exists(file))
            {
                // Find the working directory of this file so that any external files may use the same path.
                int    dirIndex         = file.LastIndexOfAny(new char[] { '/', '\\' });
                string workingDirectory = (dirIndex > 0) ? file.Substring(0, dirIndex) : "";

                XmlDocument document = new XmlDocument();
                document.Load(file);

                XmlNode mapNode = document.SelectSingleNode("map");

                TiledMap map = new TiledMap();
                map.txWidth    = XmlExtensions.GetAttributeValue <int>(mapNode, "width", -1, true);
                map.txHeight   = XmlExtensions.GetAttributeValue <int>(mapNode, "height", -1, true);
                map.TileWidth  = XmlExtensions.GetAttributeValue <int>(mapNode, "tilewidth", -1, true);
                map.TileHeight = XmlExtensions.GetAttributeValue <int>(mapNode, "tileheight", -1, true);
                map.Background = ColorExtensions.ToColor(
                    XmlExtensions.GetAttributeValue(
                        mapNode, "backgroundcolor", "#000000"
                        )
                    );
                map.LoadProperties(mapNode);

                // OBJECT LAYERS
                foreach (XmlNode objectLayerNode in mapNode.SelectNodes("objectgroup"))
                {
                    TiledObjectLayer mapObjectLayer = new TiledObjectLayer();
                    mapObjectLayer.Width  = XmlExtensions.GetAttributeValue <int>(objectLayerNode, "width", 1);
                    mapObjectLayer.Height = XmlExtensions.GetAttributeValue <int>(objectLayerNode, "height", 1);
                    mapObjectLayer.Name   = XmlExtensions.GetAttributeValue(objectLayerNode, "name");

                    foreach (XmlNode objectNode in objectLayerNode.SelectNodes("object"))
                    {
                        TiledObject mapObject = new TiledObject();
                        mapObject.Name   = XmlExtensions.GetAttributeValue(objectNode, "name");
                        mapObject.Type   = XmlExtensions.GetAttributeValue(objectNode, "type");
                        mapObject.X      = XmlExtensions.GetAttributeValue <int>(objectNode, "x", 0);
                        mapObject.Y      = XmlExtensions.GetAttributeValue <int>(objectNode, "y", 0);
                        mapObject.Width  = XmlExtensions.GetAttributeValue <int>(objectNode, "width", 0);
                        mapObject.Height = XmlExtensions.GetAttributeValue <int>(objectNode, "height", 0);
                        mapObject.Gid    = XmlExtensions.GetAttributeValue <int>(objectNode, "gid", -1);

                        XmlNode polygonNode = objectNode.SelectSingleNode("polygon");
                        if (polygonNode != null)
                        {
                            mapObject.Points = ConvertToPointsList(XmlExtensions.GetAttributeValue(polygonNode, "points"));
                        }

                        mapObject.LoadProperties(objectNode);

                        mapObjectLayer.TiledObjects.Add(mapObject);
                    }

                    map.TiledObjectLayers.Add(mapObjectLayer);
                }

                // TILESETS
                foreach (XmlNode tilesetNode in mapNode.SelectNodes("tileset"))
                {
                    XmlNode actualTilesetNode;
                    int     firstGID = XmlExtensions.GetAttributeValue <int>(tilesetNode, "firstgid", -1, true);

                    // If the tileset comes from an external .tsx file, load the node from that file.
                    if (XmlExtensions.HasAttribute(tilesetNode, "source"))
                    {
                        XmlDocument tilesetDocument = new XmlDocument();
                        tilesetDocument.Load(
                            string.Format("{0}/{1}",
                                          workingDirectory, XmlExtensions.GetAttributeValue(tilesetNode, "source")));

                        actualTilesetNode = tilesetDocument.SelectSingleNode("tileset");
                    }
                    else
                    {
                        actualTilesetNode = tilesetNode;
                    }

                    string tilesetName = XmlExtensions.GetAttributeValue(actualTilesetNode, "name");
                    int    tileHeight  = XmlExtensions.GetAttributeValue <int>(actualTilesetNode, "tileheight", -1, true);
                    int    tileWidth   = XmlExtensions.GetAttributeValue <int>(actualTilesetNode, "tilewidth", -1, true);

                    TileSet tileset = new TileSet();
                    tileset.LoadProperties(actualTilesetNode);

                    tileset.Name               = tilesetName;
                    tileset.TileWidth          = tileWidth;
                    tileset.TileHeight         = tileHeight;
                    tileset.ContentTexturePath = tileset.GetProperty("Content");    // Content Texture Path for XNA. REQUIRED.

                    map.TileSets.Add(tileset);

                    XmlNode imageNode         = actualTilesetNode.SelectSingleNode("image");
                    int     imageWidth        = XmlExtensions.GetAttributeValue <int>(imageNode, "width", -1, true);
                    int     imageHeight       = XmlExtensions.GetAttributeValue <int>(imageNode, "height", -1, true);
                    string  sourceTexturePath = XmlExtensions.GetAttributeValue <string>(imageNode, "source", "", true);

                    // PreBuild the tiles from the tileset information.
                    int i = 0;
                    while (true)
                    {
                        int tx = (i * tileWidth) % imageWidth;
                        int ty = tileHeight * ((i * tileWidth) / imageWidth);

                        // This check is performed in the case where image width is not
                        // an exact multiple of the tile width specified.
                        if (tx + tileWidth > imageWidth)
                        {
                            tx  = 0;
                            ty += tileHeight;
                        }

                        // If we have exceeded the image height, we are done.
                        if (ty + tileHeight > imageHeight)
                        {
                            break;
                        }

                        Tile tile = new Tile();
                        tile.SourceTexturePath = sourceTexturePath;                             // Path to the actual file being referred.
                        tile.SourceRectangle   = new Rectangle(tx, ty, tileWidth, tileHeight);
                        tile.TileGid           = i + firstGID;
                        tile.TileId            = i;
                        tile.TileSet           = tileset;

                        map.Tiles.Add(tile.TileGid, tile);
                        tileset.Tiles.Add(i, tile);
                        i++;
                    }

                    // Add any individual properties to the tiles we have created
                    foreach (XmlNode tileNode in actualTilesetNode.SelectNodes("tile"))
                    {
                        int  tileGid = firstGID + XmlExtensions.GetAttributeValue <int>(tileNode, "id", -1, true);
                        Tile tile    = map.Tiles[tileGid];
                        tile.LoadProperties(tileNode);

                        // BUILT INS
                        // Adjust the draw origin based on the tile property 'DrawOrigin'
                        string[] drawOrigin = tile.GetProperty("DrawOrigin", "0, 1").Split(',');
                        tile.Origin = new Vector2(
                            (float)Convert.ToDouble(drawOrigin[0]),
                            (float)Convert.ToDouble(drawOrigin[1])
                            );
                    }
                }

                // TILE LAYERS
                foreach (XmlNode layerNode in mapNode.SelectNodes("layer"))
                {
                    int width  = XmlExtensions.GetAttributeValue <int>(layerNode, "width", 0);
                    int height = XmlExtensions.GetAttributeValue <int>(layerNode, "height", 0);

                    TileLayer tileLayer = new TileLayer(width, height);
                    tileLayer.Name = XmlExtensions.GetAttributeValue(layerNode, "name");
                    tileLayer.LoadProperties(layerNode);

                    // SET BUILTIN PROPERTIES
                    tileLayer.Color = ColorExtensions.ToColor(
                        tileLayer.GetProperty <string>("Color", "#ffffff")
                        );
                    tileLayer.Opacity = tileLayer.GetProperty <float>("Opacity", 1.0f);

                    XmlNode  dataNode = layerNode.SelectSingleNode("data");
                    string[] tokens   = dataNode.InnerText.Split(
                        new char[] { '\n', ',', '\r' },
                        StringSplitOptions.RemoveEmptyEntries
                        );

                    for (int index = 0; index < tokens.Length; index++)
                    {
                        tileLayer[index] = Convert.ToInt32(tokens[index]);
                    }

                    map.TileLayers.Add(tileLayer);
                }

                return(map);
            }
            else
            {
                throw new IOException(string.Format("The Map File '{0}' does not exist.", file));
            }
        }