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(); }
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)); }
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)); } }
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)); }
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)); }
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)); }
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); }
/// <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; } }
//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 } }
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])); }
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); }
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)); }
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); } }
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); } }
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); }
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); }
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)); }
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); }
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); }
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); }
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); }
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); }
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); } }
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())); }
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); }
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)); }
/// <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); }
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}"); } }
public void YAXDefaultValueCannotBeAssignedWithLineNumbersTest() { const string bookXml = @"<Book> <Title>Inside C#</Title> <Author>Tom Archer & 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); }
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)); }