Exemplo n.º 1
0
        private static void RunYaxLibXmlDeserialization()
        {
            YAXSerializer serializer = new YAXSerializer(typeof(Config));

            Console.WriteLine("YaxLib Xml Deserialization Test");

            object settings = serializer.Deserialize(File.ReadAllText(Environment.CurrentDirectory + "/output/yaxlib.xml"));

            Console.WriteLine(settings != null ? "Success" : "Failure");
            Console.WriteLine();
        }
Exemplo n.º 2
0
        public static object XMLDeserialize(this string content, Type type)
        {
            if (content == string.Empty)
            {
                return(Activator.CreateInstance(type));
            }

            YAXSerializer serializer = new YAXSerializer(type);

            return(Convert.ChangeType(serializer.Deserialize(content), type));
        }
Exemplo n.º 3
0
        static void VerifyClientCommandResult(ProcessResult processResult, string command)
        {
            var validStandardOuputText = RemoveUnsupportedCharacters(processResult.StandardOutput);

            var commandResult = (CommandLineClientResult)CommandResultSerializer.Deserialize(validStandardOuputText);

            if (!commandResult.Success)
            {
                throw new VaultException(string.Format("Command {0} failed because: {1}.", command, commandResult.Error));
            }
        }
Exemplo n.º 4
0
        public void MultiLevelMemberAndClassDifferentNamespacesDeserializationTest()
        {
            var serializer = new YAXSerializer(typeof(CellPhone_MultiLevelMemberAndClassDifferentNamespaces),
                                               YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Warning,
                                               YAXSerializationOptions.SerializeNullObjects);
            var got          = serializer.Serialize(CellPhone_MultiLevelMemberAndClassDifferentNamespaces.GetSampleInstance());
            var deserialized = serializer.Deserialize(got) as CellPhone_MultiLevelMemberAndClassDifferentNamespaces;

            Assert.That(deserialized, Is.Not.Null);
            Assert.That(serializer.ParsingErrors, Has.Count.EqualTo(0));
        }
Exemplo n.º 5
0
        public void AttributeNamespaceDeserializationTest()
        {
            var serializer = new YAXSerializer(typeof(AttributeNamespaceSample),
                                               YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Warning,
                                               YAXSerializationOptions.SerializeNullObjects);
            var got          = serializer.Serialize(AttributeNamespaceSample.GetSampleInstance());
            var deserialized = serializer.Deserialize(got) as AttributeNamespaceSample;

            Assert.That(deserialized, Is.Not.Null);
            Assert.That(serializer.ParsingErrors, Has.Count.EqualTo(0));
        }
Exemplo n.º 6
0
        public void DictionaryNamespaceDeserializationTest()
        {
            var serializer = new YAXSerializer(typeof(CellPhone_DictionaryNamespaceForAllItems),
                                               YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Warning,
                                               YAXSerializationOptions.SerializeNullObjects);
            var got          = serializer.Serialize(CellPhone_DictionaryNamespaceForAllItems.GetSampleInstance());
            var deserialized = serializer.Deserialize(got) as CellPhone_DictionaryNamespaceForAllItems;

            Assert.That(deserialized, Is.Not.Null);
            Assert.That(serializer.ParsingErrors, Has.Count.EqualTo(0));
        }
Exemplo n.º 7
0
        public void MaxRecursionPreventsInfiniteLoop()
        {
            var ser = new YAXSerializer(typeof(CalculatedPropertiesCanCauseInfiniteLoop));

            ser.MaxRecursion = 10;
            string result = ser.Serialize(CalculatedPropertiesCanCauseInfiniteLoop.GetSampleInstance());
            var    deserialzedInstance = ser.Deserialize(result) as CalculatedPropertiesCanCauseInfiniteLoop;

            Assert.IsNotNull(deserialzedInstance);
            Assert.AreEqual(2.0M, deserialzedInstance.Data);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Convierte un xml a un objeto
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="xml">xml</param>
 /// <returns>T</returns>
 public static T XMLToObject <T>(string xml)
 {
     try
     {
         var serializer = new YAXSerializer(typeof(T));
         return((T)serializer.Deserialize(xml));
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemplo n.º 9
0
        //These functions are primarily for use when creating a AcbFormatHelper.xml (done with external tool)

        private void LoadXml()
        {
            //Attempt to load from file if in debug mode
            bool loadedXml = false;

#if DEBUG
            loadedXml = DebugLoadXml();
#endif
            //Load it from embedded resources. For normal use.
            if (!loadedXml)
            {
                YAXSerializer serializer = new YAXSerializer(typeof(AcbFormatHelperMain), YAXSerializationOptions.DontSerializeNullObjects);

#if XenoKit
                //XenoKit uses linked code rather than Xv2CoreLib.dll currently, so it cannot access Xv2CoreLib.Properties
                AcbFormatHelperMain = (AcbFormatHelperMain)serializer.Deserialize(XenoKit.Properties.Resources.AcbFormatHelper);
#else
                AcbFormatHelperMain = (AcbFormatHelperMain)serializer.Deserialize(Properties.Resources.AcbFormatHelper);
#endif
            }
        }
Exemplo n.º 10
0
        public string Yaxlib_Deserialization_With_Initialization()
        {
            var serializer = new YAXSerializer(typeof(Dummy));

            foreach (var item in _testDataYaxLibXmls)
            {
                Dummy result = (Dummy)serializer.Deserialize(item);
                bool  a      = result.BoolProperty7;
            }

            return(serializer.Serialize(_testDataObjects[0]));
        }
Exemplo n.º 11
0
        public static LogEventInfo[] LoadLog(string logFilePath)
        {
            string content = File.ReadAllText(logFilePath);

            content = String.Format("<LogInfos>\r\n{0}\r\n</LogInfos>", content);

            var serializer = new YAXSerializer(typeof(LogInfos), YAXExceptionHandlingPolicies.ThrowWarningsAndErrors,
                                               YAXExceptionTypes.Error);

            var logInfos = (LogInfos)serializer.Deserialize(content);

            return(logInfos.LogEntries);
        }
Exemplo n.º 12
0
        public void MaxRecursionPreventsInfiniteLoop()
        {
            var ser = new YAXSerializer(typeof(CalculatedPropertiesCanCauseInfiniteLoop));

            ser.Options.MaxRecursion = 10;
            var result = ser.Serialize(CalculatedPropertiesCanCauseInfiniteLoop.GetSampleInstance());
            var deserializedInstance = ser.Deserialize(result) as CalculatedPropertiesCanCauseInfiniteLoop;

            Assert.IsNotNull(deserializedInstance);
            Assert.That(ser.Options.MaxRecursion, Is.EqualTo(10));
            Assert.That(deserializedInstance.Data, Is.EqualTo(2.0M));
            Assert.That(ser.RecursionCount, Is.EqualTo(0));
        }
Exemplo n.º 13
0
        private void Read()
        {
            var deserializer = new YAXSerializer(typeof(SceneInfo));
            var document     = XDocument.Load(filepath);

            scenes = new Dictionary <string, SceneInfo>();

            foreach (var sceneXml in document.Root.Elements())
            {
                var scene = (SceneInfo)deserializer.Deserialize(sceneXml);
                scenes.Add(scene.Name, scene);
            }
        }
Exemplo n.º 14
0
        public void TestDoubleMax()
        {
            try
            {
                var ser = new YAXSerializer(typeof(double), YAXExceptionHandlingPolicies.ThrowErrorsOnly,
                                            YAXExceptionTypes.Warning, YAXSerializationOptions.SerializeNullObjects);
                double d               = 0.55;
                var    xml             = ser.Serialize(d);
                var    deseredInstance = ser.Deserialize(xml);
                Assert.AreEqual(d, deseredInstance);

                d               = Double.MaxValue;
                xml             = ser.Serialize(d);
                deseredInstance = ser.Deserialize(xml);
                // Causes a System.OverflowException {"Value was either too large or too small for a Double."}
                Assert.AreEqual(d, deseredInstance);
            }
            catch (Exception ex)
            {
                Assert.Fail("No exception should have been throwned, but received:" + Environment.NewLine + ex);
            }
        }
Exemplo n.º 15
0
        public void DesEmptyNullableTest()
        {
            const string    xml        = @"<NullableSample2 />";
            YAXSerializer   serializer = new YAXSerializer(typeof(NullableSample2), YAXExceptionHandlingPolicies.DoNotThrow);
            NullableSample2 got        = (NullableSample2)serializer.Deserialize(xml);

            Assert.That(got, Is.Not.Null);
            Assert.That(got.Boolean, Is.Null);
            Assert.That(got.DateTime, Is.Null);
            Assert.That(got.Decimal, Is.Null);
            Assert.That(got.Enum, Is.Null);
            Assert.That(got.Number, Is.Null);
        }
Exemplo n.º 16
0
        public void DeserializeIndirectSelfReferringObjectWhenDontSerializeCyclingReferencesIsSet()
        {
            var inst = IndirectSelfReferringObject.GetSampleInstanceWithLoop();

            var ser = new YAXSerializer(typeof(IndirectSelfReferringObject),
                                        YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Error, YAXSerializationOptions.DontSerializeCyclingReferences);

            string input = ser.Serialize(inst);

            var deserializedInstance = (IndirectSelfReferringObject)ser.Deserialize(input);

            Assert.That(deserializedInstance, Is.Not.Null);
            Assert.IsNull(deserializedInstance.Child.Parent);
        }
Exemplo n.º 17
0
        public void CollectionNamespaceGoesThruRecursiveNoContainingElementDeserializationTest()
        {
            var serializer =
                new YAXSerializer(typeof(CellPhone_CollectionNamespaceGoesThruRecursiveNoContainingElement),
                                  YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Warning,
                                  YAXSerializationOptions.SerializeNullObjects);
            var got = serializer.Serialize(CellPhone_CollectionNamespaceGoesThruRecursiveNoContainingElement
                                           .GetSampleInstance());
            var deserialized =
                serializer.Deserialize(got) as CellPhone_CollectionNamespaceGoesThruRecursiveNoContainingElement;

            Assert.That(deserialized, Is.Not.Null);
            Assert.That(serializer.ParsingErrors, Has.Count.EqualTo(0));
        }
Exemplo n.º 18
0
        public void DeserializeDirectSelfReferringObjectWithSelfCycleWhenThrowUponSerializingCyclingReferencesIsNotSet()
        {
            var inst = DirectSelfReferringObject.GetSampleInstanceWithSelfCycle();

            var ser = new YAXSerializer(typeof(DirectSelfReferringObject),
                                        YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Error);

            string input = ser.Serialize(inst);

            var deserializedInstance = (DirectSelfReferringObject)ser.Deserialize(input);

            Assert.That(deserializedInstance, Is.Not.Null);
            Assert.IsNull(deserializedInstance.Next);
        }
Exemplo n.º 19
0
        private T getConfigurationFromPath(string path)
        {
            var    deserializer       = new YAXSerializer(typeof(T), YAXExceptionHandlingPolicies.ThrowErrorsOnly, YAXExceptionTypes.Warning);
            object deserializedObject = null;

            deserializedObject = deserializer.Deserialize(File.ReadAllText(path));

            if (deserializer.ParsingErrors.ContainsAnyError)
            {
                Console.Error.WriteLine("Succeeded to deserialize, but these problems also happened:");
                Console.Error.WriteLine(deserializer.ParsingErrors.ToString());
            }

            return((T)deserializedObject);
        }
Exemplo n.º 20
0
        public void DeserializingADictionaryDerivedInstance()
        {
            var inst = DictionarySample.GetSampleInstance();

            var ser = new YAXSerializer(typeof(DictionarySample));

            string input = ser.Serialize(inst);

            DictionarySample deserializedInstance = (DictionarySample)ser.Deserialize(input);

            Assert.That(deserializedInstance, Is.Not.Null);
            Assert.IsTrue(deserializedInstance.Count == inst.Count,
                          "Expected Count: {0}. Actual Count: {1}",
                          inst.Count,
                          deserializedInstance.Count);
        }
Exemplo n.º 21
0
        public void AttributeForKeyInDictionaryPropertyTest()
        {
            var container = DictionaryContainerSample.GetSampleInstance();

            var ser = new YAXSerializer(typeof(DictionaryContainerSample));

            string input = ser.Serialize(container);

            var deserializedContainer = (DictionaryContainerSample)ser.Deserialize(input);

            Assert.IsNotNull(deserializedContainer.Items);
            Assert.IsTrue(deserializedContainer.Items.Count == container.Items.Count,
                          "Expected Count: {0}. Actual Count: {1}",
                          container.Items.Count,
                          deserializedContainer.Items.Count);
        }
Exemplo n.º 22
0
        public static T Deserialize <T>(string xmlFilePath)
        {
            var deserializer = new YAXSerializer(typeof(T), YAXExceptionHandlingPolicies.ThrowErrorsOnly,
                                                 YAXExceptionTypes.Warning);
            object deserializedObject = null;

            deserializedObject = deserializer.Deserialize(File.ReadAllText(xmlFilePath));

            if (deserializer.ParsingErrors.ContainsAnyError)
            {
                //Console.WriteLine("Succeeded to deserialize, but these problems also happened:");
                //Console.WriteLine(deserializer.ParsingErrors.ToString());
            }

            return((T)deserializedObject);
        }
Exemplo n.º 23
0
 public void TestSingleMin()
 {
     try
     {
         var ser = new YAXSerializer(typeof(float), YAXExceptionHandlingPolicies.ThrowErrorsOnly,
                                     YAXExceptionTypes.Warning, YAXSerializationOptions.SerializeNullObjects);
         float f               = Single.MinValue;
         var   xml             = ser.Serialize(f);
         var   deseredInstance = ser.Deserialize(xml);
         Assert.AreEqual(f, deseredInstance);
     }
     catch (Exception ex)
     {
         Assert.Fail("No exception should have been throwned, but received:" + Environment.NewLine + ex);
     }
 }
Exemplo n.º 24
0
        public void Custom_Class_Level_Serializer_Value()
        {
            // The custom serializer for ClassLevelSample handles serialization options

            var original = new ClassLevelSampleAsValue {
                ClassLevelSample = new ClassLevelSample {
                    Title = "The Title", MessageBody = "The Message"
                }
            };
            var s            = new YAXSerializer(typeof(ClassLevelSampleAsValue));
            var xml          = s.Serialize(original);
            var deserialized = (ClassLevelSampleAsValue)s.Deserialize(xml);

            Assert.That(xml, Is.EqualTo("<ClassLevelSampleAsValue>VAL|The Title|The Message</ClassLevelSampleAsValue>"));
            Assert.That(deserialized.ToString(), Is.EqualTo(original.ToString()));
        }
Exemplo n.º 25
0
        public static object Deserialize_YAX(XElement xml)
        {
            Type type = Type.GetType("VideoCatalog.Main." + xml.Name.LocalName);

            if (type != null)
            {
                //! ! отключены все исключения YAX - более опасный режим восстановления каталога (не будет ругаться на отсутствующие поля)
                YAXSerializer serializer = new YAXSerializer(type, YAXExceptionHandlingPolicies.DoNotThrow, YAXExceptionTypes.Error, YAXSerializationOptions.DontSerializeNullObjects);

                //BUG YAX при десериализации портит XML данные (как минимум для списков с кастомными объектами), поэтому перегоняем XElement в строку
                return(serializer.Deserialize(xml.ToString()));
            }
            else
            {
                System.Windows.MessageBox.Show($"Wrong type <{xml.Name.LocalName}>", "Error Deserialize");
            }
            return(null);
        }
Exemplo n.º 26
0
        public void DeserializingPolymorphicCollectionWithNoContainingElement()
        {
            var ser       = new YAXSerializer(typeof(BaseContainer));
            var container = new DerivedContainer
            {
                Items = new BaseItem[]
                {
                    new BaseItem {
                        Data = "Some Data"
                    }
                }
            };
            string result = ser.Serialize(container);
            var    deserialzedInstance = ser.Deserialize(result) as BaseContainer;

            Assert.That(deserialzedInstance.Items[0].Data, Is.EqualTo("Some Data"));
            Assert.That(deserialzedInstance.Items.Length, Is.EqualTo(1));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Deserializes the project from a given string.
        /// </summary>
        /// <param name="xml">The input string for deserialization.</param>
        /// <param name="projectPath">Project path for correct lookup of items like state data.</param>
        /// <param name="restoreModelOnly">If set to true, only the model is deserialized, but not observers etc.</param>
        /// <returns>A deserialized project.</returns>
        public static MyProject Deserialize(string xml, string projectPath, bool restoreModelOnly = false)
        {
            xml = MyBaseConversion.ConvertOldFileVersioning(xml);
            xml = MyBaseConversion.ConvertOldModuleNames(xml);

            xml = CheckUsedModulesAndConvert(xml);

            YAXSerializer serializer = MyProject.GetSerializer();

            MyPathSerializer.ReferencePath = projectPath;
            MyProject loadedProject = (MyProject)serializer.Deserialize(xml);

            MyPathSerializer.ReferencePath = String.Empty;

            DumpSerializerErrors(serializer);

            if (loadedProject == null)
            {
                throw new YAXException("Cannot deserialize project.");
            }

            loadedProject.FileName = projectPath;

            loadedProject.World.FinalizeTasksDeserialization();

            loadedProject.World.UpdateAfterDeserialization();
            loadedProject.m_nodeCounter = loadedProject.Network.UpdateAfterDeserialization(0, loadedProject);

            if (loadedProject.World.Id > loadedProject.m_nodeCounter)
            {
                loadedProject.m_nodeCounter = loadedProject.World.Id;
            }

            loadedProject.m_nodeCounter++;

            loadedProject.ConnectWorld();

            if (!restoreModelOnly)
            {
                loadedProject.Restore();
            }

            return(loadedProject);
        }
Exemplo n.º 28
0
        private void GetSeries(object obj)
        {
            var url      = "https://chitanka.info/series/search.xml?q=all";
            var response = string.Empty;

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                response        = client.DownloadString(url);
            }

            var ser = new YAXSerializer(typeof(Results));

            try
            {
                Results sample = (Results)ser.Deserialize(response);

                foreach (var x in sample.CollectionOfSeries)
                {
                    this.SerieList.Add(new Serie
                    {
                        SerieId           = x.SerieId,
                        SerieSlug         = x.SerieSlug,
                        SerieName         = x.SerieName,
                        SerieOriginalName = x.SerieOriginalName,
                        Author            = new BookAuthor
                        {
                            AuthorId     = x.Author.AuthorId,
                            AuthorSlug   = x.Author.AuthorSlug,
                            Name         = x.Author.Name,
                            OriginalName = x.Author.OriginalName,
                            Country      = x.Author.Country,
                            Info         = x.Author.Country
                        }
                    });
                }

                this.SerieNumber = this.SerieList.Count;
            }
            catch (Exception e)
            {
                throw new Exception($"{e}");
            }
        }
Exemplo n.º 29
0
        public void YAXDefaultValueCannotBeAssignedWithLineNumbersTest()
        {
            const string bookXml =
                @"<Book>
  <Title>Inside C#</Title>
  <Author>Tom Archer &amp; Andrew Whitechapel</Author>
  <PublishYear>2002</PublishYear>
</Book>";

            var ex = Assert.Throws <YAXDefaultValueCannotBeAssigned>(() =>
            {
                var serializer = new YAXSerializer(typeof(BookWithBadDefaultValue), YAXExceptionHandlingPolicies.ThrowWarningsAndErrors, YAXExceptionTypes.Error, YAXSerializationOptions.DisplayLineInfoInExceptions);
                serializer.Deserialize(bookXml);
            });

            Assert.True(ex.HasLineInfo);
            Assert.AreEqual(1, ex.LineNumber);
            Assert.AreEqual(2, ex.LinePosition);
        }
Exemplo n.º 30
0
        public void DeserializingPolymorphicCollectionWithPolymorphicItems()
        {
            var ser       = new YAXSerializer(typeof(BaseContainer));
            var container = new BaseContainer
            {
                Items = new BaseItem[]
                {
                    new DerivedItem {
                        Data = "Some Data"
                    }
                }
            };
            var result = ser.Serialize(container); // This works correct
            var deserialzedInstance = ser.Deserialize(result) as BaseContainer;

            Assert.That(deserialzedInstance.Items[0], Is.InstanceOf <DerivedItem>());
            Assert.That(deserialzedInstance.Items[0].Data, Is.EqualTo("Some Data"));
            Assert.That(deserialzedInstance.Items.Length, Is.EqualTo(1));
        }