Exemple #1
0
            public void RespectsTheXmlAttributeAttribute()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var person      = new ModelBaseFacts.Person("Geert", "van", "Horrik", 42);
                var xmlDocument = person.ToXml(serializer);

                var personElement = xmlDocument.Element("MappedPerson");

                Assert.IsNotNull(personElement);

                var ageAttribute = personElement.Attribute("FutureAge");

                Assert.IsNotNull(ageAttribute);
                Assert.AreEqual("42", ageAttribute.Value);

                using (var memoryStream = new MemoryStream())
                {
                    using (var streamWriter = new StreamWriter(memoryStream))
                    {
                        streamWriter.Write(xmlDocument.ToString());
                        streamWriter.Flush();

                        memoryStream.Position = 0L;

                        var deserializedPerson = serializer.Deserialize <ModelBaseFacts.Person>(memoryStream);

                        Assert.AreEqual(42, deserializedPerson.Age);
                    }
                }
            }
Exemple #2
0
        protected virtual void SaveSettings(IControlTool tool)
        {
            var settingsProperties = tool.GetType()
                                     .GetProperties()
                                     .Where(prop => Attribute.IsDefined(prop, typeof(ToolSettingsAttribute)));

            foreach (var settingsProperty in settingsProperties)
            {
                var settings = settingsProperty.GetValue(tool);
                if (settings is null)
                {
                    continue;
                }

                var serializer       = SerializationFactory.GetXmlSerializer();
                var settingsFilePath = GetSettingsFilePath(tool, settingsProperty);
                using (var fileStream = File.Open(settingsFilePath, FileMode.Create))
                {
                    try
                    {
                        serializer.Serialize(settings, fileStream);
                    }
                    catch (Exception e)
                    {
                        //Vladimir:Don't crash if something went wrong while saving tool settings into file
                        Log.Error(e);
                    }
                }
            }
        }
            /// <summary>
            /// Restores the backup to the object.
            /// </summary>
            public void RestoreBackup()
            {
                Dictionary <string, object> oldPropertyValues = null;

                using (var stream = new MemoryStream(_propertyValuesBackup))
                {
                    try
                    {
                        var serializer = SerializationFactory.GetXmlSerializer();
                        var properties = serializer.DeserializeMembers(_object.GetType(), stream);

                        oldPropertyValues = properties.ToDictionary(property => property.Name, property => property.Value);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Failed to deserialize the data for backup, which is weird. However, for Silverlight, Windows Phone and Windows 8 there is no other option");
                    }
                }

                if (oldPropertyValues == null)
                {
                    return;
                }

                foreach (KeyValuePair <string, object> propertyValue in oldPropertyValues)
                {
                    if (PropertyDataManager.IsPropertyRegistered(_object.GetType(), propertyValue.Key))
                    {
                        // Set value so the PropertyChanged event is invoked
                        _object.SetValue(propertyValue.Key, propertyValue.Value);
                    }
                }

                _object.IsDirty = (bool)_objectValuesBackup[IsDirty];
            }
Exemple #4
0
        public void EnumerableOfAbstractClassesViaKnownTypes_SameNameDifferentNamespaces_SaveLoadRoundTrip()
        {
            var c = new ContainerAbstractClasses();

            var pA = new PluginA.Params();

            pA.SettingA = "TestA";
            c.Parameters.Add(pA);

            var pB = new PluginB.Params();

            pB.SettingB = "TestB";
            c.Parameters.Add(pB);

            using (var memoryStream = new MemoryStream())
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                c.Save(memoryStream, serializer);
                memoryStream.Position = 0L;

                var c2 = serializer.Deserialize <ContainerAbstractClasses>(memoryStream);

                Assert.AreEqual(c, c2);
            }
        }
        //public ContentControl RegionContentControl { get; set; }

        //private bool _IsManageable=true;
        ///// <summary>
        ///// displayed in the management manu
        ///// </summary>
        //public bool IsManageable
        //{
        //    get { return _IsManageable; }
        //    set
        //    {
        //        if (value != _IsManageable)
        //        {
        //            _IsManageable = value;
        //            RaisePropertyChanged(() => this.IsManageable);
        //        }
        //    }
        //}



        public virtual void SaveState(Stream stream)
        {
            IXmlSerializer xmlSerializer = SerializationFactory.GetXmlSerializer();

            xmlSerializer.Serialize(this, stream);
            Log.Debug("Saved object {0}", this.ContentId);
            base.ClearIsDirtyOnAllChilds();
            this.IsDataDirty = false;
        }
Exemple #6
0
            public void XmlSerializationWithXmlIgnore()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var obj = new ObjectWithXmlMappings();

                var xml = obj.ToXml(serializer).ToString();

                Assert.IsFalse(xml.Contains("IgnoredProperty"));
            }
        /// <summary>
        /// Serializes the data in the view model for tombstoning.
        /// </summary>
        /// <returns>A byte array representing the data.</returns>
        internal byte[] SerializeForTombstoning()
        {
            using (var memoryStream = new MemoryStream())
            {
                var xmlSerializer = SerializationFactory.GetXmlSerializer();
                xmlSerializer.SerializeMembers(this, memoryStream);

                return(memoryStream.ToArray());
            }
        }
Exemple #8
0
 private void CreateDatabase(String path)
 {
     _rootPath = path;
     _info     = new DatabaseInfo
     {
         Title       = "<Give a title here>",
         Description = "<Write a description here>"
     };
     DatabaseInfo.Save(DatabaseInfoPath, SerializationFactory.GetXmlSerializer());
 }
        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                return;
            }

            var serializer = SerializationFactory.GetXmlSerializer();

            serializer.Deserialize(this, new XmlSerializationContextInfo(reader, this));
        }
Exemple #10
0
        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement && !reader.HasAttributes)
            {
                return;
            }

            var serializer  = SerializationFactory.GetXmlSerializer();
            var contextInfo = new XmlSerializationContextInfo(reader, this);

            serializer.Deserialize(this, contextInfo);
        }
Exemple #11
0
        public void CloseDatabase()
        {
            DatabaseInfo.Save(DatabaseInfoPath, SerializationFactory.GetXmlSerializer());

            _fileStorage.Stop();
            _metadata.Stop();
            _fileStorage = null;
            _metadata    = null;
            _rootPath    = null;
            _info        = null;

            RaisePropertyChanged(string.Empty);
        }
Exemple #12
0
            public void RespectsTheXmlIgnoreAttribute()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var person      = new ModelBaseFacts.Person("Geert", "van", "Horrik", 42);
                var xmlDocument = person.ToXml(serializer);

                var personElement = xmlDocument.Element("MappedPerson");

                Assert.IsNotNull(personElement);

                Assert.IsNull(personElement.Element("FullName"));
            }
Exemple #13
0
        private void CommonCreationOpening(String pathToMongod, String path)
        {
            _info = DatabaseInfo.Load(File.OpenRead(DatabaseInfoPath), SerializationFactory.GetXmlSerializer());

            // create the file database
            _fileStorage = new FileDatabase(path);
            _fileStorage.Start();

            // create the mongodb
            _metadata = new MetadataDatabase(pathToMongod, path);
            _metadata.Start();

            RaisePropertyChanged(String.Empty);
        }
        /// <summary>
        /// Initialize boot tasks.
        /// </summary>
        /// <param name="bootTasks">The additional boot tasks.</param>
        /// <remarks>Override this method to add additional tasks that will be executed before shell initialization.</remarks>
        protected override void InitializeBootTasks(IList <ITask> bootTasks)
        {
            base.InitializeBootTasks(bootTasks);

            bootTasks.Add(new ActionTask(OrchestraShellResources.BootTaskWarmingUpSerializers, tracker =>
            {
                var xmlSerializer = (IModelBaseSerializer)SerializationFactory.GetXmlSerializer();
                xmlSerializer.Warmup();

                var binarySerializer = (IModelBaseSerializer)SerializationFactory.GetBinarySerializer();
                binarySerializer.Warmup();
            }));

            base.InitializeBootTasks(bootTasks);
        }
Exemple #15
0
        /// <summary>
        /// Loads the object from a stream using a specific formatting.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="stream">Stream that contains the serialized data of this object.</param>
        /// <param name="mode"><see cref="SerializationMode" /> to use.</param>
        /// <returns>Deserialized instance of the object. If the deserialization fails, <c>null</c> is returned.</returns>
        /// <remarks>When enableRedirects is enabled, loading will take more time. Only set
        /// the parameter to <c>true</c> when the deserialization without redirects fails.</remarks>
        public static IModel Load(Type type, Stream stream, SerializationMode mode)
        {
            Argument.IsNotNull("type", type);

            object result = null;

            Log.Debug("Loading object '{0}' as '{1}'", type.Name, mode);

            switch (mode)
            {
#if NET
            case SerializationMode.Binary:
                try
                {
                    var binarySerializer = SerializationFactory.GetBinarySerializer();
                    result = binarySerializer.Deserialize(type, stream);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to deserialize the binary object");
                }

                break;
#endif

            case SerializationMode.Xml:
                try
                {
                    var xmlSerializer = SerializationFactory.GetXmlSerializer();
                    result = xmlSerializer.Deserialize(type, stream);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to deserialize the binary object");
                }
                break;
            }

            Log.Debug("Loaded object");

            var resultAsModelBase = result as ModelBase;
            if (resultAsModelBase != null)
            {
                resultAsModelBase.Mode = mode;
            }

            return(result as IModel);
        }
Exemple #16
0
        public static string ToXmlString(this object model)
        {
            Argument.IsNotNull(() => model);

            using (var memoryStream = new MemoryStream())
            {
                var xmlSerializer = SerializationFactory.GetXmlSerializer();
                xmlSerializer.Serialize(model, memoryStream, null);

                memoryStream.Position = 0L;
                using (var xmlReader = XmlReader.Create(memoryStream))
                {
                    return(XDocument.Load(xmlReader).ToString());
                }
            }
        }
Exemple #17
0
            public void WarmsUpAllTypes()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                TimeMeasureHelper.MeasureAction(5, "Xml serializer warmup",
                                                () => serializer.Warmup(),
                                                () =>
                {
                    TypeCache.InitializeTypes(false);

                    ConsoleHelper.Write("TypeCache contains {0} items", TypeCache.GetTypes().Count());
                    ConsoleHelper.Write("TypeCache contains {0} ModelBase items", TypeCache.GetTypes(x => typeof(ModelBase).IsAssignableFromEx(x)).Count());
                });

                // TODO: No way to see if this is cached (otherwise we have to write this feature on DataContractSerializerFactory)
                // This unit test is written to easily test this functionality though.
            }
Exemple #18
0
            public void CorrectlySerializesAndDeserializes()
            {
                var inputGesture = new InputGesture(Key.A, ModifierKeys.Control | ModifierKeys.Shift);

                var xmlSerializer = SerializationFactory.GetXmlSerializer();

                using (var memoryStream = new MemoryStream())
                {
                    xmlSerializer.Serialize(inputGesture, memoryStream);

                    memoryStream.Position = 0L;

                    var finalInputGesture = xmlSerializer.Deserialize(typeof(InputGesture), memoryStream);

                    Assert.AreEqual(inputGesture, finalInputGesture);
                }
            }
Exemple #19
0
        /// <summary>
        /// Converts an object into its XML representation.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            var type = GetType();

            var element    = new XElement(type.Name);
            var serializer = SerializationFactory.GetXmlSerializer();

            serializer.Serialize(this, new XmlSerializationContextInfo(element, this));

            // The serializer gives us the full element, but we only need the actual content. According to
            // http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement, this method is the fastest:
            var reader = element.CreateReader();

            reader.MoveToContent();
            var elementContent = reader.ReadInnerXml();

            writer.WriteRaw(elementContent);
        }
            /// <summary>
            /// Creates a backup of the object property values.
            /// </summary>
            private void CreateBackup()
            {
                using (var stream = new MemoryStream())
                {
                    var catelTypeInfo      = PropertyDataManager.GetCatelTypeInfo(_object.GetType());
                    var propertiesToIgnore = (from propertyData in catelTypeInfo.GetCatelProperties()
                                              where !propertyData.Value.IncludeInBackup
                                              select propertyData.Value.Name).ToArray();

                    var serializer = SerializationFactory.GetXmlSerializer();
                    serializer.SerializeMembers(_object, stream, propertiesToIgnore);

                    _propertyValuesBackup = stream.ToByteArray();
                }

                _objectValuesBackup = new Dictionary <string, object>();
                _objectValuesBackup.Add(IsDirty, _object.IsDirty);
            }
Exemple #21
0
            public void RespectsTheXmlRootAndXmlElementAttribute()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var person      = new ModelBaseFacts.Person("Geert", "van", "Horrik", 42);
                var xmlDocument = person.ToXml(serializer);

                var personElement = xmlDocument.Element("MappedPerson");

                Assert.IsNotNull(personElement);

                var firstNameElement = personElement.Element("NameFirst");

                Assert.IsNotNull(firstNameElement);
                Assert.AreEqual("Geert", firstNameElement.Value);

                var middleNameElement = personElement.Element("NameMiddle");

                Assert.IsNotNull(middleNameElement);
                Assert.AreEqual("van", middleNameElement.Value);

                var lastNameElement = personElement.Element("NameLast");

                Assert.IsNotNull(lastNameElement);
                Assert.AreEqual("Horrik", lastNameElement.Value);

                using (var memoryStream = new MemoryStream())
                {
                    using (var streamWriter = new StreamWriter(memoryStream))
                    {
                        streamWriter.Write(xmlDocument.ToString());
                        streamWriter.Flush();

                        memoryStream.Position = 0L;

                        var deserializedPerson = serializer.Deserialize <ModelBaseFacts.Person>(memoryStream);

                        Assert.AreEqual("Geert", deserializedPerson.FirstName);
                        Assert.AreEqual("van", deserializedPerson.MiddleName);
                        Assert.AreEqual("Horrik", deserializedPerson.LastName);
                    }
                }
            }
        public void MyCatelModel_SerializationTest()
        {
            var input = new IsDirtyModelTestModel
            {
                MyDecimal = 123.4567m,
                MyInteger = 98765,
                MyString  = "This is a serialization test."
            };

            // Round-trip the instance: Serialize and de-serialize with a BinaryFormatter
            var actual = SerializationTestHelper.SerializeAndDeserialize(input, SerializationFactory.GetXmlSerializer());

            // Double-check that the internal values are preserved
            Assert.AreEqual(input.MyDecimal, actual.MyDecimal, "MyDecimal values do not match.");
            Assert.AreEqual(input.MyInteger, actual.MyInteger, "MyInteger values do not match.");
            Assert.AreEqual(input.MyString, actual.MyString, "MyString values do not match.");
            //Assert.AreEqual(input.IsDirty, actual.IsDirty, "IsDirty values do not match.");
            Assert.IsFalse(actual.IsDirty);
        }
Exemple #23
0
        public static T FromXmlString <T>(this string xml)
            where T : ModelBase
        {
            Argument.IsNotNullOrWhitespace(() => xml);

            var xmlDocument = XDocument.Parse(xml);

            using (var memoryStream = new MemoryStream())
            {
                using (var xmlWriter = XmlWriter.Create(memoryStream))
                {
                    xmlDocument.Save(xmlWriter);
                }

                memoryStream.Position = 0L;

                var xmlSerializer = SerializationFactory.GetXmlSerializer();
                return((T)xmlSerializer.Deserialize(typeof(T), memoryStream, null));
            }
        }
Exemple #24
0
            public void SupportsSerialization()
            {
                dynamic model = new DynamicModel();

                model.NonExistingProperty = "a dynamic value";

                var serializer = SerializationFactory.GetXmlSerializer();

                using (var memoryStream = new MemoryStream())
                {
                    var dynamicModel = (DynamicModel)model;
                    serializer.Serialize(dynamicModel, memoryStream, null);

                    memoryStream.Position = 0L;

                    dynamic deserializedModel        = serializer.Deserialize(typeof(DynamicModel), memoryStream, null);
                    var     deserializedDynamicModel = (DynamicModel)deserializedModel;

                    Assert.IsTrue(deserializedDynamicModel.IsPropertyRegistered("NonExistingProperty"));
                    Assert.AreEqual("a dynamic value", deserializedModel.NonExistingProperty);
                }
            }
Exemple #25
0
        public void DictionaryWithKnownTypes()
        {
            var dictionary = new DictionaryTestClass();

            dictionary.Values.Add("A", new ModelBaseFacts.Person
            {
                FirstName = "John",
                LastName  = "Doe"
            });

            dictionary.Values.Add("B", new ModelBaseFacts.Person
            {
                FirstName = "Jane",
                LastName  = "Doe"
            });

            using (var memoryStream = new MemoryStream())
            {
                var serializer = SerializationFactory.GetXmlSerializer();
                serializer.Serialize(dictionary, memoryStream);

                memoryStream.Position = 0L;

                var dictionary2 = serializer.Deserialize <DictionaryTestClass>(memoryStream);

                Assert.AreEqual(dictionary, dictionary2);

                var dic1Elem1 = dictionary.Values.ElementAt(0);
                var dic2Elem1 = dictionary2.Values.ElementAt(0);

                Assert.AreEqual(dic1Elem1, dic2Elem1);

                var dic1Elem2 = dictionary.Values.ElementAt(1);
                var dic2Elem2 = dictionary2.Values.ElementAt(1);

                Assert.AreEqual(dic1Elem2, dic2Elem2);
            }
        }
Exemple #26
0
        /// <summary>
        /// Saves the object to a stream using a specific formatting.
        /// </summary>
        /// <param name="stream">Stream that will contain the serialized data of this object.</param>
        /// <param name="mode"><see cref="SerializationMode"/> to use.</param>
        public void Save(Stream stream, SerializationMode mode)
        {
            Log.Debug("Saving object '{0}' as '{1}'", GetType().Name, mode);

            switch (mode)
            {
#if NET
            case SerializationMode.Binary:
                var binarySerializer = SerializationFactory.GetBinarySerializer();
                binarySerializer.Serialize(this, stream);
                break;
#endif

            case SerializationMode.Xml:
                var xmlSerializer = SerializationFactory.GetXmlSerializer();
                xmlSerializer.Serialize(this, stream);
                break;
            }

            Log.Debug("Saved object");

            ClearIsDirtyOnAllChilds();
        }
Exemple #27
0
        /// <summary>
        /// Converts an object into its XML representation.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            var type = GetType();

            var element    = new XElement(type.Name);
            var serializer = SerializationFactory.GetXmlSerializer();

            serializer.Serialize(this, new XmlSerializationContextInfo(element, this));

            // The serializer gives us the full element, but we only need the actual content. According to
            // http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement, this method is the fastest:
            var reader = element.CreateReader();

            reader.MoveToContent();

            // CTL-710: fix attributes on top level elements
            if (reader.HasAttributes)
            {
                for (int i = 0; i < reader.AttributeCount; i++)
                {
                    reader.MoveToAttribute(i);

                    var attributePrefix    = reader.Prefix;
                    var attributeLocalName = reader.LocalName;
                    var attributeNs        = reader.NamespaceURI;
                    var attributeValue     = reader.Value;

                    writer.WriteAttributeString(attributePrefix, attributeLocalName, attributeNs, attributeValue);
                }

                reader.MoveToElement();
            }

            var elementContent = reader.ReadInnerXml();

            writer.WriteRaw(elementContent);
        }
        /// <summary>
        /// Deserializes the data from a previously stored tombstoning state.
        /// </summary>
        /// <param name="data">The previously stored data.</param>
        internal void DeserializeFromTombstoning(byte[] data)
        {
            try
            {
                using (var memoryStream = new MemoryStream(data))
                {
                    var xmlSerializer  = SerializationFactory.GetXmlSerializer();
                    var propertyValues = xmlSerializer.DeserializeMembers(GetType(), memoryStream);

                    LeanAndMeanModel = true;

                    foreach (var propertyValue in propertyValues)
                    {
                        SetValue(propertyValue.Name, propertyValue.Value, false, false);
                    }

                    LeanAndMeanModel = false;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "An error occurred while deserializing the view model from tombstoned data");
            }
        }
Exemple #29
0
        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                return;
            }

            var type = GetType();

            reader.MoveToContent();
            var nodeContent = reader.ReadOuterXml();

            var document = XElement.Parse(nodeContent);

            if (document == null)
            {
                Log.Error("Cannot retrieve xml document from the xml reader for type '{0}'", type.FullName);
                return;
            }

            var serializer = SerializationFactory.GetXmlSerializer();

            serializer.Deserialize(this, new XmlSerializationContextInfo(document, this));
        }
Exemple #30
0
            public void SupportsNestedHierarchySerialization()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var root = new ModelBaseFacts.Group()
                {
                    Name = "myRoot"
                };

                var child = new ModelBaseFacts.Group()
                {
                    Name = "myChild"
                };

                root.Items = new ObservableCollection <ModelBaseFacts.Item>();
                root.Items.Add(child);

                var newRoot = SerializationTestHelper.SerializeAndDeserialize(root, serializer);

                Assert.IsNotNull(newRoot);
                Assert.AreEqual("myRoot", newRoot.Name);
                Assert.AreEqual(1, newRoot.Items.Count);
                Assert.AreEqual("myChild", newRoot.Items[0].Name);
            }