Esempio n. 1
0
        /// <summary>
        /// Serialize to file.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static Result SerializeXml(string filename, object p)
        {
            try
            {
                // Create folder if not exists.
                if (Directory.Exists(Path.GetDirectoryName(filename)) == false)
                {
                    DirectoryInfo info = Directory.CreateDirectory(Path.GetDirectoryName(filename));
                    if (info == null || info.Exists == false)
                    {
                        return(Result.Fail(string.Format("Failed to create directory [{0}].", Path.GetDirectoryName(filename))));
                    }
                }

                using (XmlWriter xw = XmlWriter.Create(filename))
                {
                    return(SerializationHelper.SerializeXml(xw, p));
                }
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.OperationError("Failed to serialize object [" + p.ToString() + "] to xml file [" + filename + "].", ex);
                return(Result.Failure);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Perform object serialization to a file.
        /// </summary>
        public static Result Serialize(string filename, object value)
        {
            try
            {
                // Create folder if not exists.
                if (Directory.Exists(Path.GetDirectoryName(filename)) == false)
                {
                    DirectoryInfo info = Directory.CreateDirectory(Path.GetDirectoryName(filename));
                    if (info == null || info.Exists == false)
                    {
                        return(Result.Fail(string.Format("Failed to create directory [{0}].", Path.GetDirectoryName(filename))));
                    }
                }

                byte[] data = SerializationHelper.Serialize(value);
                File.WriteAllBytes(filename, data);
            }
            catch (Exception ex)
            {
                string message = string.Format("Failed to serialize to file [{0}]", filename);
                CoreSystemMonitor.OperationError(message, ex);
                return(Result.Fail(message));
            }

            return(Result.Success);
        }
Esempio n. 3
0
        /// <summary>
        /// Serialize to text writer.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static Result SerializeXml(TextWriter writer, object p)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(p.GetType());
                serializer.Serialize(writer, p);
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.Error("Failed to xml-serialize object [" + p.GetType().Name + "]", ex);
                return(Result.Fail(ex));
            }

            return(Result.Success);
        }
Esempio n. 4
0
 /// <summary>
 /// Serialize to memory stream.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="p"></param>
 /// <returns></returns>
 public static Result SerializeXml(MemoryStream stream, object p)
 {
     try
     {
         using (XmlWriter xw = XmlWriter.Create(stream))
         {
             return(SerializationHelper.SerializeXml(xw, p));
         }
     }
     catch (Exception ex)
     {
         CoreSystemMonitor.OperationError("Failed to serialize object [" + p.ToString() + "] to xml stream.", ex);
         return(Result.Fail(ex));
     }
 }
Esempio n. 5
0
        /// <summary>
        /// Perform deserialization of an object from a stream.
        /// </summary>
        public static Result Deserialize(MemoryStream stream, out object value)
        {
            try
            {
                IFormatter formatter = ObtainFormatter();
                value = formatter.Deserialize(stream);
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.Error("Failed to deserialize object.", ex);
                value = null;
                return(Result.Fail(ex));
            }

            return(Result.Success);
        }
Esempio n. 6
0
        public static Result DeSerializeXml <TType>(TextReader reader, out TType output)
            where TType : class
        {
            output = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TType));
                output = (TType)serializer.Deserialize(reader);
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.Error("Failed to xml-deserialize object [" + typeof(TType).Name + "]", ex);
                return(Result.Fail(ex));
            }

            return(Result.Success);
        }
Esempio n. 7
0
        /// <summary>
        /// Throws.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        protected override object DeserializeData(Stream stream)
        {
            BinaryFormatter formatter = _formatter;

            if (formatter == null)
            {
                return(null);
            }

            try
            {
                return(formatter.Deserialize(stream));
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.OperationError("Failed to deserialize object", ex);
                throw new InvalidDataException(ex.Message, ex);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Serialize to memory stream.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static Result Serialize(MemoryStream stream, object p)
        {
            try
            {
                IFormatter formatter = ObtainFormatter();
                formatter.Serialize(stream, p);
                if (stream.Position > SerializationWarningLimit)
                {
                    CoreSystemMonitor.Warning("Serialialization of object [" + p.GetType().Name + "] has grown above the default serialization limit to [" + stream.Position.ToString() + "] bytes.");
                }

                return(Result.Success);
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.Error("Failed to serialize object [" + p.GetType().Name + "," + ex.Message + "].");
                return(Result.Fail(ex));
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Helper, overrides.
        /// </summary>
        public static TType Deserialize <TType>(string filename)
            where TType : class
        {
            try
            {
                byte[] data = File.ReadAllBytes(filename);
                if (data != null)
                {
                    object dummy;
                    SerializationHelper.Deserialize(data, out dummy);
                    return((TType)dummy);
                }
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.OperationError("Failed to extract proxies manager.", ex);
            }

            return(null);
        }
Esempio n. 10
0
        /// <summary>
        /// Returns false if failed to serialize.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool Serialize(MemoryStream stream, object message)
        {
            if (message == null)
            {
                return(false);
            }

            long startPosition = stream.Position;

            // Placeholder.
            byte[] sizeBytes = BitConverter.GetBytes(int.MaxValue);
            stream.Write(sizeBytes, 0, sizeBytes.Length);

            if (SerializeData(stream, message) == false)
            {
                stream.Seek(startPosition, SeekOrigin.Begin);
                return(false);
            }

            int length = (int)stream.Position - (int)startPosition;

            long lastPosition = stream.Position;

            stream.Seek(startPosition, SeekOrigin.Begin);

            if (length > MaxMessageSize)
            {
                CoreSystemMonitor.OperationError("Message size too big.");
                return(false);
            }

            // Encoding (int.MaxValue - value); this helps diagnostics of message transport errors.
            sizeBytes = BitConverter.GetBytes(int.MaxValue - length);
            stream.Write(sizeBytes, 0, sizeBytes.Length);

            stream.Seek(lastPosition, SeekOrigin.Begin);

            return(true);
        }
Esempio n. 11
0
        /// <summary>
        /// Static constructor - create the default formatter.
        /// </summary>
        static SerializationHelper()
        {
            lock (_syncRoot)
            {
                if (_formatter != null)
                {
                    CoreSystemMonitor.Error("Not expected, formatter already created.");
                    return;
                }

                // Create the formatter.
                _formatter = new BinaryFormatter();

                // 2. Construct a SurrogateSelector object
                SurrogateSelector surrogateSelector = new SurrogateSelector();

                // 3. Tell the surrogate selector to use our object when a
                // object is serialized/deserialized.
                List <ISerializationSurrogate> surrogates = ReflectionHelper.GetTypeChildrenInstances <ISerializationSurrogate>(
                    ReflectionHelper.GetAssemblies(true, true));

                foreach (ISerializationSurrogate surrogate in surrogates)
                {
                    SerializationSurrogateAttribute attribute = ReflectionHelper.GetTypeCustomAttributeInstance <SerializationSurrogateAttribute>(
                        surrogate.GetType(), false);

                    if (attribute != null)
                    {
                        surrogateSelector.AddSurrogate(attribute.Type, new StreamingContext(StreamingContextStates.All), surrogate);
                    }
                    else
                    {
                        CoreSystemMonitor.Info(string.Format("Surrogate type [{0}] not marked with SerializationSurrogateAttribute.", surrogate.GetType().Name));
                    }
                }

                _formatter.SurrogateSelector = surrogateSelector;
            }
        }