/// <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 #2
0
 /// <exception cref="System.IO.IOException"/>
 /// <exception cref="System.Exception"/>
 private static JobSplit.SplitMetaInfo[] WriteNewSplits <T>(Configuration conf, T[]
                                                            array, FSDataOutputStream @out)
     where T : InputSplit
 {
     JobSplit.SplitMetaInfo[] info = new JobSplit.SplitMetaInfo[array.Length];
     if (array.Length != 0)
     {
         SerializationFactory factory = new SerializationFactory(conf);
         int i = 0;
         int maxBlockLocations = conf.GetInt(MRConfig.MaxBlockLocationsKey, MRConfig.MaxBlockLocationsDefault
                                             );
         long offset = @out.GetPos();
         foreach (T split in array)
         {
             long prevCount = @out.GetPos();
             Text.WriteString(@out, split.GetType().FullName);
             Org.Apache.Hadoop.IO.Serializer.Serializer <T> serializer = factory.GetSerializer(
                 (Type)split.GetType());
             serializer.Open(@out);
             serializer.Serialize(split);
             long     currCount = @out.GetPos();
             string[] locations = split.GetLocations();
             if (locations.Length > maxBlockLocations)
             {
                 Log.Warn("Max block location exceeded for split: " + split + " splitsize: " + locations
                          .Length + " maxsize: " + maxBlockLocations);
                 locations = Arrays.CopyOf(locations, maxBlockLocations);
             }
             info[i++] = new JobSplit.SplitMetaInfo(locations, offset, split.GetLength());
             offset   += currCount - prevCount;
         }
     }
     return(info);
 }
Exemple #3
0
        /// <exception cref="System.Exception"/>
        public virtual void TestAcceptHandlingPrimitivesAndArrays()
        {
            SerializationFactory factory = new SerializationFactory(conf);

            NUnit.Framework.Assert.IsNull(factory.GetSerializer <byte[]>());
            NUnit.Framework.Assert.IsNull(factory.GetSerializer <byte>());
        }
            /// <summary>
            /// Restores the storage entity to a strongly typed in-memory array representation with element type <typeparamref name="T"/> by deserializing state that was loaded by <see cref="LoadCore(IStateReader)"/>.
            /// If the entity has not been persisted before, this methods returns a new array instance with default values of type <typeparamref name="T"/> for each of its elements.
            /// </summary>
            /// <typeparam name="T">The type of the elements stored in the array.</typeparam>
            /// <returns>An instance of type <typeparamref name="T"/>[] containing the data represented by the storage entity.</returns>
            private T[] Restore <T>()
            {
                //
                // If the state was loaded by LoadCore, we have a eventual objects to deserialize array elements from. Otherwise, return a fresh array instance.
                //

                if (_data != null)
                {
                    //
                    // Obtain the deserializer once to reduce overhead.
                    //

                    var deserializer = SerializationFactory.GetDeserializer <T>();

                    //
                    // Deserialize all the array elements.
                    //

                    var res = new T[_data.Length];

                    for (var i = 0; i < _data.Length; i++)
                    {
                        res[i] = _data[i].Deserialize(deserializer);
                    }

                    _data = null;

                    return(res);
                }
                else
                {
                    return(new T[_length]);
                }
            }
Exemple #5
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);
                    }
                }
            }
        }
Exemple #6
0
 /// <exception cref="System.Exception"/>
 /// <exception cref="System.IO.IOException"/>
 public ReduceContextImpl(Configuration conf, TaskAttemptID taskid, RawKeyValueIterator
                          input, Counter inputKeyCounter, Counter inputValueCounter, RecordWriter <KEYOUT,
                                                                                                   VALUEOUT> output, OutputCommitter committer, StatusReporter reporter, RawComparator
                          <KEYIN> comparator, Type keyClass, Type valueClass)
     : base(conf, taskid, output, committer, reporter)
 {
     iterable = new ReduceContextImpl.ValueIterable(this);
     // current key
     // current value
     // first value in key
     // more w/ this key
     // more in file
     this.input                = input;
     this.inputKeyCounter      = inputKeyCounter;
     this.inputValueCounter    = inputValueCounter;
     this.comparator           = comparator;
     this.serializationFactory = new SerializationFactory(conf);
     this.keyDeserializer      = serializationFactory.GetDeserializer(keyClass);
     this.keyDeserializer.Open(buffer);
     this.valueDeserializer = serializationFactory.GetDeserializer(valueClass);
     this.valueDeserializer.Open(buffer);
     hasMore         = input.Next();
     this.keyClass   = keyClass;
     this.valueClass = valueClass;
     this.conf       = conf;
     this.taskid     = taskid;
 }
Exemple #7
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);
                    }
                }
            }
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            var binarySerializer           = SerializationFactory.GetBinarySerializer();
            var binarySerializationContext = new BinarySerializationContextInfo(info);

            binarySerializer.Serialize(this, binarySerializationContext);
        }
Exemple #9
0
        /// <summary><inheritDoc/></summary>
        /// <exception cref="System.IO.IOException">
        /// If the child InputSplit cannot be read, typically
        /// for failing access checks.
        /// </exception>
        public virtual void ReadFields(DataInput @in)
        {
            // Generic array assignment
            int card = WritableUtils.ReadVInt(@in);

            if (splits == null || splits.Length != card)
            {
                splits = new InputSplit[card];
            }
            Type[] cls = new Type[card];
            try
            {
                for (int i = 0; i < card; ++i)
                {
                    cls[i] = Sharpen.Runtime.GetType(Text.ReadString(@in)).AsSubclass <InputSplit>();
                }
                for (int i_1 = 0; i_1 < card; ++i_1)
                {
                    splits[i_1] = ReflectionUtils.NewInstance(cls[i_1], null);
                    SerializationFactory factory      = new SerializationFactory(conf);
                    Deserializer         deserializer = factory.GetDeserializer(cls[i_1]);
                    deserializer.Open((DataInputStream)@in);
                    splits[i_1] = (InputSplit)deserializer.Deserialize(splits[i_1]);
                }
            }
            catch (TypeLoadException e)
            {
                throw new IOException("Failed split init", e);
            }
        }
Exemple #10
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);
            }
        }
        protected static string Serialize(object val, SerializerType serializerType)
        {
            if (val == null)
            {
                return(null);
            }

            var serialized = val as string;

            if (serialized != null)
            {
                return(serialized);
            }

            switch (serializerType)
            {
            case SerializerType.DataContractSerializer:
                return(SerializationFactory.DataContractSerialize(val));

            case SerializerType.DataContractJsonSerializer:
                return(SerializationFactory.DataContractJsonSerialize(val));

            case SerializerType.JsonNetSerializer:
                return(SerializationFactory.JsonNetSerialize(val));

            case SerializerType.XmlSerializer:
            default:
                return(SerializationFactory.XmlSerialize(val));
            }

            #endregion
        }
Exemple #12
0
        public void GetBsonReaderSettingsDefaults()
        {
            var factory        = new SerializationFactory();
            var readerSettings = factory.GetBsonReaderSettings(typeof(int));

            Assert.AreEqual(readerSettings.ReadLocalTime, true);
            Assert.IsNotNull(readerSettings.Builder);
        }
Exemple #13
0
 private static SerializationFactory GetFactory(Configuration conf)
 {
     if (serialFactory == null)
     {
         serialFactory = new SerializationFactory(conf);
     }
     return(serialFactory);
 }
Exemple #14
0
        public void ReadLocalTimeCanBeChangedByConfig()
        {
            var factory = new SerializationFactory(new MongoConfiguration {
                ReadLocalTime = false
            });
            var readerSettings = factory.GetBsonReaderSettings(typeof(int));

            Assert.AreEqual(readerSettings.ReadLocalTime, false);
        }
        //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;
        }
        /// <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 #17
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());
 }
Exemple #18
0
            public void XmlSerializationWithXmlIgnore()
            {
                var serializer = SerializationFactory.GetXmlSerializer();

                var obj = new ObjectWithXmlMappings();

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

                Assert.IsFalse(xml.Contains("IgnoredProperty"));
            }
        /// <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 #20
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                var level = EntityContainer as Level;
                SerializationFactory.SerializeToFile(level, level.LevelPath);
                PCGame.SceneManager.LoadScene(new MainMenuScene(), true, true);
            }
        }
        /// <exception cref="System.IO.IOException"/>
        public virtual void ReadFields(DataInput @in)
        {
            inputSplitClass  = (Type)ReadClass(@in);
            inputFormatClass = (Type)ReadClass(@in);
            mapperClass      = (Type)ReadClass(@in);
            inputSplit       = (InputSplit)ReflectionUtils.NewInstance(inputSplitClass, conf);
            SerializationFactory factory      = new SerializationFactory(conf);
            Deserializer         deserializer = factory.GetDeserializer(inputSplitClass);

            deserializer.Open((DataInputStream)@in);
            inputSplit = (InputSplit)deserializer.Deserialize(inputSplit);
        }
Exemple #22
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);
        }
        /// <exception cref="System.IO.IOException"/>
        public virtual void Write(DataOutput @out)
        {
            Text.WriteString(@out, inputSplitClass.FullName);
            Text.WriteString(@out, inputFormatClass.FullName);
            Text.WriteString(@out, mapperClass.FullName);
            SerializationFactory factory = new SerializationFactory(conf);

            Org.Apache.Hadoop.IO.Serializer.Serializer serializer = factory.GetSerializer(inputSplitClass
                                                                                          );
            serializer.Open((DataOutputStream)@out);
            serializer.Serialize(inputSplit);
        }
Exemple #24
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 #25
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 #26
0
        /// <summary>Configures all the chain elements for the task.</summary>
        /// <param name="jobConf">chain job's JobConf.</param>
        public virtual void Configure(JobConf jobConf)
        {
            string prefix = GetPrefix(isMap);

            chainJobConf = jobConf;
            SerializationFactory serializationFactory = new SerializationFactory(chainJobConf
                                                                                 );
            int index = jobConf.GetInt(prefix + ChainMapperSize, 0);

            for (int i = 0; i < index; i++)
            {
                Type    klass = jobConf.GetClass <Mapper>(prefix + ChainMapperClass + i, null);
                JobConf mConf = new JobConf(GetChainElementConf(jobConf, prefix + ChainMapperConfig
                                                                + i));
                Mapper mapper = ReflectionUtils.NewInstance(klass, mConf);
                mappers.AddItem(mapper);
                if (mConf.GetBoolean(MapperByValue, true))
                {
                    mappersKeySerialization.AddItem(serializationFactory.GetSerialization(mConf.GetClass
                                                                                              (MapperOutputKeyClass, null)));
                    mappersValueSerialization.AddItem(serializationFactory.GetSerialization(mConf.GetClass
                                                                                                (MapperOutputValueClass, null)));
                }
                else
                {
                    mappersKeySerialization.AddItem(null);
                    mappersValueSerialization.AddItem(null);
                }
            }
            Type klass_1 = jobConf.GetClass <Reducer>(prefix + ChainReducerClass, null);

            if (klass_1 != null)
            {
                JobConf rConf = new JobConf(GetChainElementConf(jobConf, prefix + ChainReducerConfig
                                                                ));
                reducer = ReflectionUtils.NewInstance(klass_1, rConf);
                if (rConf.GetBoolean(ReducerByValue, true))
                {
                    reducerKeySerialization = serializationFactory.GetSerialization(rConf.GetClass(ReducerOutputKeyClass
                                                                                                   , null));
                    reducerValueSerialization = serializationFactory.GetSerialization(rConf.GetClass(
                                                                                          ReducerOutputValueClass, null));
                }
                else
                {
                    reducerKeySerialization   = null;
                    reducerValueSerialization = null;
                }
            }
        }
Exemple #27
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 #29
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 #30
0
            /// <exception cref="System.IO.IOException"/>
            public KeyValueWriter(Configuration conf, OutputStream output, Type kyClass, Type
                                  valClass)
            {
                keyClass   = kyClass;
                valueClass = valClass;
                dataBuffer = new DataOutputBuffer();
                SerializationFactory serializationFactory = new SerializationFactory(conf);

                keySerializer = (Org.Apache.Hadoop.IO.Serializer.Serializer <K>)serializationFactory
                                .GetSerializer(keyClass);
                keySerializer.Open(dataBuffer);
                valueSerializer = (Org.Apache.Hadoop.IO.Serializer.Serializer <V>)serializationFactory
                                  .GetSerializer(valueClass);
                valueSerializer.Open(dataBuffer);
                outputStream = new DataOutputStream(output);
            }