/// <summary>
 /// Initialize an IndexDatabase with the path to the index file,
 /// whether it exists or not
 /// </summary>
 /// <param name="pathToIndexFile">The path to the index file</param>
 /// <param name="method">The serialization method to use</param>
 /// <remarks>
 /// If the file exists, this object will attempt to deserialize it. If it does
 /// not exist, a new file will be created
 /// </remarks>
 public IndexDatabase(string pathToIndexFile, SerializationMethod method)
     : this()
 {
     _pathToIndexFile = pathToIndexFile;
     _indexEntries = DeserializeIndexDatabase(pathToIndexFile, method);
     _serializationMethod = method;
 }
        public static T AutoDeserialize <T>(this string raw, SerializationMethod method = SerializationMethod.Auto, bool catchFail = true)
        {
            if (method == SerializationMethod.Auto)
            {
                method = defaultSerializationMethod;
            }

            try {
                switch (method)
                {
                case SerializationMethod.RawBinary:
                    return(RawBase64Deserialize <T>(raw));

                case SerializationMethod.CompressedBinary:
                    return(Base64Deserialize <T>(raw));

                case SerializationMethod.RawJson:
                    return(JsonDeserialize <T>(raw));

                case SerializationMethod.CompressedJson:
                    return(JsonBase64Deserialize <T>(raw));

                default:
                    return(default(T));
                }
            }catch {
                //log exception
                return(default(T));
            }
        }
        public static string AutoSerialize <T>(this T raw, SerializationMethod method = SerializationMethod.Auto)
        {
            if (method == SerializationMethod.Auto)
            {
                method = defaultSerializationMethod;
            }

            switch (method)
            {
            case SerializationMethod.RawBinary:
                return(RawBase64Serialize <T>(raw));

            case SerializationMethod.CompressedBinary:
                return(Base64Serialize <T>(raw));

            case SerializationMethod.RawJson:
                return(JsonSerialize <T>(raw));

            case SerializationMethod.CompressedJson:
                return(JsonBase64Serialize <T>(raw));

            default:
                return("");
            }
        }
        public static ISerializedObject Serialize(this object graph, SerializationMethod method)
        {
            if (IsDebugEnabled)
            {
                log.Debug("객체를 직렬화하여 SerializedObject를 생성합니다. method=[{0}], graph=[{1}]", method, graph);
            }

            switch (method)
            {
            case SerializationMethod.Binary:
                return(new BinarySerializedObject(graph));

            case SerializationMethod.Bson:
                return(new BsonSerializedObject(graph));

            case SerializationMethod.Json:
                return(new JsonSerializedObject(graph));

            case SerializationMethod.Xml:
                return(new XmlSerializedObject(graph));

            case SerializationMethod.Soap:
                return(new SoapSerializedObject(graph));

            default:
                throw new NotSupportedException(string.Format("지원하지 않는 직렬화 방법입니다. method=[{0}]", method));
            }
        }
 private IndexDatabase()
 {
     _hashToEntriesMap =
         new Lazy<IDictionary<ImageFingerPrint, ICollection<IndexEntry>>>(IndexAllEntries);
     _queuedIndexEntriesForAddition = new ConcurrentQueue<IndexEntry>();
     _serializationMethod = SerializationMethod.JSON;
 }
        private static void TestMissingFieldCore(SerializationMethod method, EmitterFlavor flavor)
        {
            var context = new SerializationContext()
            {
                SerializationMethod = method, EmitterFlavor = flavor
            };

            var serializer = MessagePackSerializer.Create <VersioningTestTarget>(context);

            using (var stream = new MemoryStream())
            {
                if (method == SerializationMethod.Array)
                {
                    stream.Write(new byte[] { 0x91, 0x1 });
                }
                else
                {
                    var packer = Packer.Create(stream, false);
                    packer.PackMapHeader(1);
                    packer.Pack("Field1");
                    packer.Pack(1);
                }

                stream.Position = 0;

                var result = serializer.Unpack(stream);

                Assert.That(result.Field1, Is.EqualTo(1));
                Assert.That(result.Field2, Is.EqualTo(0));
                Assert.That(result.Field3, Is.Null);
            }
        }
        private void TestUnpackSuccess <T>(
            SerializationMethod method,
            Func <T> inputFactory,
            Func <byte[]> packedStreamFactory,
            Action <T, T> assertion
            )
            where T : new()
        {
            var context = this.CreateSerializationContext();

            context.SerializationMethod = method;
            var seraizlier = CreateTarget <T>(context);

            using (var buffer = new MemoryStream())
            {
                if (packedStreamFactory != null)
                {
                    var bytes = packedStreamFactory();
                    buffer.Write(bytes, 0, bytes.Length);
                }
                else
                {
                    seraizlier.Pack(buffer, inputFactory == null ? new T() : inputFactory());
                }

                buffer.Position = 0;
                assertion(seraizlier.Unpack(buffer), new T());
            }
        }
        /// <summary>
        /// десериализация
        /// </summary>
        /// <param name="stream">поток с данными для сериализации</param>
        /// <param name="method">способ сериализации</param>
        /// <returns>объект теста</returns>
        /// <exception cref="IOException"/>
        /// <exception cref="SerializationException"/>
        public static object Deserialize(Type type, Stream stream, SerializationMethod method)
        {
            if (method == SerializationMethod.XML)
            {
                //try
                //{
                //    XmlSerializer serializer = new XmlSerializer(type);
                ////-------
                //    byte[] bytes = new byte[stream.Length];
                //    stream.Read(bytes, 0, bytes.Length);
                //    string s = Encoding.Default.GetString(bytes);
                ////---------

                //    XmlReader r = XmlTextReader.Create(stream);

                //    Object res = serializer.Deserialize(
                //    //return res;
                //}
                //catch
                //{
                //    throw new ArgumentException();
                //}
            }
            if (method == SerializationMethod.Binary)
            {

            }
            return null;
        }
        private void TestUnpackingFail <T, TException>(
            SerializationMethod method,
            Func <T> inputFactory,
            Func <byte[]> packedStreamFactory
            )
            where T : new()
            where TException : Exception
        {
            var context = this.CreateSerializationContext();

            context.SerializationMethod = method;
            var seraizlier = CreateTarget <T>(context);

            using (var buffer = new MemoryStream())
            {
                if (packedStreamFactory != null)
                {
                    var bytes = packedStreamFactory();
                    buffer.Write(bytes, 0, bytes.Length);
                }
                else
                {
                    seraizlier.Pack(buffer, inputFactory == null ? new T() : inputFactory());
                }

                buffer.Position = 0;
                Assert.Throws <TException>(() => seraizlier.Unpack(buffer));
            }
        }
Exemple #10
0
        private static void TestExtraFieldCore <T>(SerializationMethod method, EmitterFlavor flavor)
        {
            var serializer = CreateSerializer <T>(flavor);

            using (var stream = new MemoryStream())
            {
                if (method == SerializationMethod.Array)
                {
                    stream.Write(new byte[] { 0x94, 0x1, 0xFF, 0xA1, ( byte )'a', 0xC0 });
                }
                else
                {
                    var packer = Packer.Create(stream, false);
                    packer.PackMapHeader(5);
                    packer.Pack("Field1");
                    packer.Pack(1);
                    packer.Pack("Extra");
                    packer.PackNull();
                    packer.Pack("Field2");
                    packer.Pack(-1);
                    packer.Pack("Field3");
                    packer.Pack("a");
                    packer.Pack("Extra");
                    packer.PackNull();
                }

                stream.Position = 0;

                serializer.Unpack(stream);
            }
        }
Exemple #11
0
        private static void TestFieldInvalidTypeCore(SerializationMethod method, EmitterFlavor flavor)
        {
            var serializer = CreateSerializer <VersioningTestTarget>(flavor);

            using (var stream = new MemoryStream())
            {
                if (method == SerializationMethod.Array)
                {
                    stream.Write(new byte[] { 0x93, 0x1, 0xFF, 0x1 });
                }
                else
                {
                    var packer = Packer.Create(stream, false);
                    packer.PackMapHeader(3);
                    packer.PackString("Field1");
                    packer.Pack(1);
                    packer.PackString("Field2");
                    packer.Pack(-1);
                    packer.PackString("Field3");
                    packer.Pack(1);
                }

                stream.Position = 0;

                var result = serializer.Unpack(stream);

                Assert.That(result.Field1, Is.EqualTo(1));
                Assert.That(result.Field2, Is.EqualTo(-1));
                Assert.That(result.Field3, Is.EqualTo("a"));
            }
        }
        private static void TestExtraFieldCore <T>(SerializationMethod method, EmitterFlavor flavor)
        {
            var context = new SerializationContext()
            {
                SerializationMethod = method, EmitterFlavor = flavor
            };

            var serializer = MessagePackSerializer.Create <T>(context);

            using (var stream = new MemoryStream())
            {
                if (method == SerializationMethod.Array)
                {
                    stream.Write(new byte[] { 0x94, 0x1, 0xFF, 0xA1, ( byte )'a', 0xC0 });
                }
                else
                {
                    var packer = Packer.Create(stream, false);
                    packer.PackMapHeader(4);
                    packer.Pack("Field1");
                    packer.Pack(1);
                    packer.Pack("Field2");
                    packer.Pack(-1);
                    packer.Pack("Field3");
                    packer.Pack("a");
                    packer.Pack("Extra");
                    packer.PackNull();
                }

                stream.Position = 0;

                var result = serializer.Unpack(stream);

                /*
                 * if ( result is IMessagePackExtensibleObject )
                 * {
                 *      var extensionData = ( ( IMessagePackExtensibleObject )result ).ExtensionData;
                 *      Assert.That( extensionData.IsNil, Is.False );
                 *
                 *      if ( method == SerializationMethod.Array )
                 *      {
                 *              Assert.That( extensionData.AsList().Count, Is.EqualTo( 4 ) );
                 *              Assert.That( extensionData.AsList()[ 0 ] == 1 );
                 *              Assert.That( extensionData.AsList()[ 1 ] == -1 );
                 *              Assert.That( extensionData.AsList()[ 2 ] == "a" );
                 *              Assert.That( extensionData.AsList()[ 3 ].IsNil );
                 *      }
                 *      else
                 *      {
                 *              Assert.That( extensionData.AsDictionary().Count, Is.EqualTo( 4 ) );
                 *              Assert.That( extensionData.AsDictionary()[ "Field1" ] == 1 );
                 *              Assert.That( extensionData.AsDictionary()[ "Field2" ] == -1 );
                 *              Assert.That( extensionData.AsDictionary()[ "Field3" ] == "a" );
                 *              Assert.That( extensionData.AsDictionary()[ "Extra" ].IsNil );
                 *      }
                 * }
                 */
            }
        }
        // ------ Unpacking ------


        private void TestUnpackSuccess <T>(
            SerializationMethod method,
            Action <T, T> assertion
            )
            where T : new()
        {
            this.TestUnpackSuccess(method, () => new T(), null, assertion);
        }
Exemple #14
0
 public SceneMessage(int Job_ID, string messageText, Scene scene, StatusUpdateMessage statusUpdateMessage, SerializationMethod method)
 {
     this.Job_ID              = Job_ID;
     this.method              = method;
     this.messageText         = messageText;
     this.scene               = scene;
     this.sceneBytes          = SceneFileToByteArray(this.scene, method);
     this.statusUpdateMessage = statusUpdateMessage;
 }
 private void TestUnpackSuccess <T>(
     SerializationMethod method,
     Func <byte[]> packedStreamFactory,
     Action <T, T> assertion
     )
     where T : new()
 {
     this.TestUnpackSuccess(method, () => new T(), packedStreamFactory, assertion);
 }
 private void TestUnpackFail <T, TException>(
     SerializationMethod method,
     Func <byte[]> packedStreamFactory
     )
     where T : new()
     where TException : Exception
 {
     this.TestUnpackingFail <T, TException>(method, null, packedStreamFactory);
 }
 private void TestUnpackSuccess <T>(
     SerializationMethod method,
     Func <T> inputFactory,
     Action <T, T> assertion
     )
     where T : new()
 {
     this.TestUnpackSuccess(method, inputFactory, null, assertion);
 }
Exemple #18
0
 /// <summary>
 ///		Initializes a new instance of the <see cref="SerializerCodeGenerationConfiguration"/> class.
 /// </summary>
 public SerializerCodeGenerationConfiguration()
 {
     // Set to defaults.
     this.OutputDirectory      = null;
     this.Language             = null;
     this.Namespace            = null;
     this.CodeIndentString     = null;
     this._serializationMethod = SerializationMethod.Array;
 }
        /// <summary>
        /// 지정된 직렬화 정보들을 가지고 <see cref="ISerializedObject"/>의 Concrete Class의 인스턴스를 생성합니다.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="typename"></param>
        /// <param name="serializedValue"></param>
        /// <returns></returns>
        public static ISerializedObject Create(SerializationMethod method, string typename, byte[] serializedValue)
        {
            if (IsDebugEnabled)
            {
                log.Debug("SerializedObject를 생성합니다. method=[{0]}, typename=[{1}], serializedValue=[{2}]", method, typename,
                          serializedValue);
            }

            switch (method)
            {
            case SerializationMethod.Binary:
                return(new BinarySerializedObject
                {
                    Method = method,
                    ObjectTypeName = typename,
                    SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                });

            case SerializationMethod.Bson:
                return(new BsonSerializedObject
                {
                    Method = method,
                    ObjectTypeName = typename,
                    SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                });

            case SerializationMethod.Json:
                return(new JsonSerializedObject
                {
                    Method = method,
                    ObjectTypeName = typename,
                    SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                });

            case SerializationMethod.Xml:
                return(new XmlSerializedObject
                {
                    Method = method,
                    ObjectTypeName = typename,
                    SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                });

            case SerializationMethod.Soap:
                return(new SoapSerializedObject
                {
                    Method = method,
                    ObjectTypeName = typename,
                    SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                });

            default:
                throw new NotSupportedException(string.Format("지원하지 않는 직렬화 방법입니다. method=[{0}]", method));
            }
        }
Exemple #20
0
        /// <summary>
        /// Deserialize string into an object of type T based on the serialization method.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <param name="serializationMethod"></param>
        /// <returns></returns>
        public static async Task <T> DeserializeStringAsync <T>(string input, SerializationMethod serializationMethod)
        {
            switch (serializationMethod)
            {
            case SerializationMethod.JsonString:
                return(await DeserializeJsonAsync <T>(input));

            default:
                return(default);
            }
        }
Exemple #21
0
 public OSMJobMessage(int x, int y, double tileWidth, double originLongitude, double originLatitude, string replyQueueName, string statusUpdateQueue, StatusUpdateMessage statusUpdateMessage, SerializationMethod method)
 {
     this.x                   = x;
     this.y                   = y;
     this.tileWidth           = tileWidth;
     this.originLongitude     = originLongitude;
     this.originLatitude      = originLatitude;
     this.replyToQueue        = replyQueueName;
     this.statusUpdateQueue   = statusUpdateQueue;
     this.statusUpdateMessage = statusUpdateMessage;
     this.method              = method;
 }
        private static void TestCore(EmitterFlavor emittingFlavor, SerializationMethod serializationMethod, Func <SerializationContext, SerializerBuilder <DirectoryItem> > builderProvider)
        {
            var root = new DirectoryItem()
            {
                Name = "/"
            };

            root.Directories =
                new[]
            {
                new DirectoryItem()
                {
                    Name = "tmp/"
                },
                new DirectoryItem()
                {
                    Name        = "var/",
                    Directories = new DirectoryItem[0],
                    Files       = new [] { new FileItem()
                                           {
                                               Name = "system.log"
                                           } }
                }
            };
            root.Files = new FileItem[0];

            var serializer = new AutoMessagePackSerializer <DirectoryItem>(new SerializationContext()
            {
                EmitterFlavor = emittingFlavor, SerializationMethod = serializationMethod, GeneratorOption = SerializationMethodGeneratorOption.CanDump
            }, builderProvider);

            using (var memoryStream = new MemoryStream())
            {
                serializer.Pack(memoryStream, root);

                memoryStream.Position = 0;
                var result = serializer.Unpack(memoryStream);
                Assert.That(result.Name, Is.EqualTo("/"));
                Assert.That(result.Files, Is.Not.Null.And.Empty);
                Assert.That(result.Directories, Is.Not.Null.And.Length.EqualTo(2));
                Assert.That(result.Directories[0], Is.Not.Null);
                Assert.That(result.Directories[0].Name, Is.EqualTo("tmp/"));
                Assert.That(result.Directories[0].Files, Is.Null);
                Assert.That(result.Directories[0].Directories, Is.Null);
                Assert.That(result.Directories[1], Is.Not.Null);
                Assert.That(result.Directories[1].Name, Is.EqualTo("var/"));
                Assert.That(result.Directories[1].Files, Is.Not.Null.And.Length.EqualTo(1));
                Assert.That(result.Directories[1].Files[0], Is.Not.Null);
                Assert.That(result.Directories[1].Files[0].Name, Is.EqualTo("system.log"));
                Assert.That(result.Directories[1].Directories, Is.Not.Null.And.Empty);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
        /// </summary>
        /// <param name="assemblyName">Name of the assembly to be generated.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="assemblyName"/> is <c>null</c>.
        /// </exception>
        public SerializerGenerator(AssemblyName assemblyName)
        {
            if (assemblyName == null)
            {
                throw new ArgumentNullException("assemblyName");
            }

            Contract.EndContractBlock();

            this._assemblyName = assemblyName;
            this._targetTypes  = new HashSet <Type>();
            this._method       = SerializationMethod.Array;
        }
Exemple #24
0
        /// <summary>
        /// Sends an IQ and returns the response.  This is called from separate thread since it waits
        /// </summary>
        /// <param name="iq">The IQ to send</param>
        /// <param name="nTimeoutMS">The timeout in ms to wait for a areponse</param>
        /// <returns>The IQ that was received, or null if one was not received within the timeout period</returns>
        public IQ SendRecieveIQ(IQ iq, int nTimeoutMS, SerializationMethod method)
        {
            SendRecvIQLogic iqlog = new SendRecvIQLogic(this, iq);

            iqlog.SerializationMethod = method;
            AddLogic(iqlog);

            iqlog.SendReceive(nTimeoutMS);

            RemoveLogic(iqlog);

            return(iqlog.RecvIQ);
        }
        private static ISerialization LoadSerializator(SerializationMethod method)
        {
            switch (method)
            {
            case SerializationMethod.XML: return(new SerializationToXML());

            case SerializationMethod.SOAP: return(new SerializationToSOAP());

            case SerializationMethod.JSON: return(new SerializationToJSON());

            default: return(new SerialitationToBinary());
            }
        }
Exemple #26
0
        /// <summary>
        /// Deserialize byte[] into an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <param name="serializationMethod"></param>
        /// <returns></returns>
        public static async Task <T> DeserializeAsync <T>(byte[] input, SerializationMethod serializationMethod)
        {
            switch (serializationMethod)
            {
            case SerializationMethod.Utf8Json:
                return(await DeserializeAsUtf8JsonFormatAsync <T>(input));

            case SerializationMethod.ZeroFormat:
                return(await DeserializeAsZeroFormatAsync <T>(input));

            default:
                return(default);
            }
        }
Exemple #27
0
 public SerializerGenerator(Type rootType, System.Reflection.AssemblyName assemblyName)
 {
     if (rootType == null)
     {
         throw new ArgumentNullException("rootType");
     }
     if (assemblyName == null)
     {
         throw new ArgumentNullException("assemblyName");
     }
     this._rootType     = rootType;
     this._assemblyName = assemblyName;
     this._method       = SerializationMethod.Array;
 }
        /// <summary>
        /// 지정된 직렬화 정보들을 가지고 <see cref="ISerializedObject"/>의 Concrete Class의 인스턴스를 생성합니다.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="typename"></param>
        /// <param name="serializedValue"></param>
        /// <returns></returns>
        public static ISerializedObject Create(SerializationMethod method, string typename, byte[] serializedValue) {
            if(IsDebugEnabled)
                log.Debug("SerializedObject를 생성합니다. method=[{0]}, typename=[{1}], serializedValue=[{2}]", method, typename,
                          serializedValue);

            switch(method) {
                case SerializationMethod.Binary:
                    return new BinarySerializedObject
                           {
                               Method = method,
                               ObjectTypeName = typename,
                               SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                           };

                case SerializationMethod.Bson:
                    return new BsonSerializedObject
                           {
                               Method = method,
                               ObjectTypeName = typename,
                               SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                           };

                case SerializationMethod.Json:
                    return new JsonSerializedObject
                           {
                               Method = method,
                               ObjectTypeName = typename,
                               SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                           };

                case SerializationMethod.Xml:
                    return new XmlSerializedObject
                           {
                               Method = method,
                               ObjectTypeName = typename,
                               SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                           };

                case SerializationMethod.Soap:
                    return new SoapSerializedObject
                           {
                               Method = method,
                               ObjectTypeName = typename,
                               SerializedValue = (serializedValue != null) ? (byte[])serializedValue.Clone() : null
                           };

                default:
                    throw new NotSupportedException(string.Format("지원하지 않는 직렬화 방법입니다. method=[{0}]", method));
            }
        }
Exemple #29
0
    public static byte[] SceneFileToByteArray(Scene scene, SerializationMethod method)
    {
        //Stopwatch sw = new Stopwatch();
        //sw.Start();

        MemoryStream memStream = new MemoryStream();

        byte[] sceneBytes = null;

        switch (method)
        {
        case SerializationMethod.DataContractSerializer:
            DataContractSceneSerialization.SceneSurrogate sceneSurrogate = new DataContractSceneSerialization.SceneSurrogate(scene);

            List <System.Type> knownTypes = new List <System.Type>();
            knownTypes.Add(typeof(DataContractSceneSerialization.Vector2Surrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.Vector3Surrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.Vector4Surrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.ColorSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.QuaternionSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.TransformSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.GameObjectSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.MeshFilterSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.MeshRendererSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.MeshSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.MaterialSurrogate));
            knownTypes.Add(typeof(DataContractSceneSerialization.ComponentSurrogate));

            DataContractSerializer serializer = new DataContractSerializer(typeof(DataContractSceneSerialization.SceneSurrogate), knownTypes);

            serializer.WriteObject(memStream, sceneSurrogate);
            sceneBytes = memStream.GetBuffer();
            break;

        case SerializationMethod.ProtoBuf:
            ProtobufSceneSerialization.SceneSurrogate sceneSurrogateProto = new ProtobufSceneSerialization.SceneSurrogate(scene);
            Serializer.Serialize <ProtobufSceneSerialization.SceneSurrogate>(memStream, sceneSurrogateProto);
            sceneBytes = memStream.ToArray();
            break;

        default:
            break;
        }

        memStream.Close();
        //sw.Stop();
        //UnityEngine.Debug.Log("Serialization using " + method.ToString() + " took " + sw.ElapsedMilliseconds + "ms");
        return(sceneBytes);
    }
		// ------ Packing ------

		private void TestPackFail<T, TException>(
			SerializationMethod method,
			Func<T> inputFactory
		)
			where T : new()
			where TException : Exception
		{
			var context = this.CreateSerializationContext();
			context.SerializationMethod = method;
			var seraizlier = CreateTarget<T>( context );

			using ( var buffer = new MemoryStream() )
			{
				Assert.Throws<TException>( () => seraizlier.Pack( buffer, inputFactory == null ? new T() : inputFactory() ) );
			}
		}
Exemple #31
0
        /// <summary>
        /// Take an object of type T and serialize to a string based on the serialization method.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message">The message to be serialized.</param>
        /// <param name="serializationMethod">Specifies the serialization method.</param>
        /// <param name="makePretty">Makes the string prettified (if useable).</param>
        /// <returns>A string message in the format determined appropriate by the serialization method.</returns>
        public static async Task <string> SerializeToStringAsync <T>(T message, SerializationMethod serializationMethod, bool makePretty = false)
        {
            var output = string.Empty;

            switch (serializationMethod)
            {
            case SerializationMethod.JsonString:
                output = await SerializeToJsonAsync(message, makePretty);

                break;

            default: break;
            }

            return(output);
        }
        /// <summary>
        ///		Creates new <see cref="SerializationContext"/> for generation based testing.
        /// </summary>
        /// <param name="method"><see cref="SerializationMethod"/>.</param>
        /// <param name="compatibilityLevel"><see cref="SerializationCompatibilityLevel"/> for built-in serializers.</param>
        /// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
        public static SerializationContext CreateContext(SerializationMethod method, SerializationCompatibilityLevel compatibilityLevel)
        {
            var context = SerializationContext.CreateClassicContext(compatibilityLevel);

            context.SerializationMethod = method;

            foreach (var entry in _serializers)
            {
                context.Serializers.Register(entry.Key, entry.Value, null, null, SerializerRegistrationOptions.None);
            }

#if !AOT
            context.SerializerOptions.DisableRuntimeCodeGeneration = true;
#endif // !AOT
            return(context);
        }
		private static void TestDataContractAndMessagePackMemberAndNonSerializedAreMixedCore( SerializationMethod method )
		{
			var context = new SerializationContext() { SerializationMethod = method };

			using ( var buffer = new MemoryStream() )
			{
				var target = new MessagePackMemberAndDataMemberMixedTarget();
				target.ShouldSerialized1 = 111;
				target.ShouldSerialized2 = 222;
				target.ShouldSerialized3 = 333;
				target.ShouldNotSerialized1 = 444;
				target.ShouldNotSerialized2 = 555;
				var serializer = MessagePackSerializer.Create<MessagePackMemberAndDataMemberMixedTarget>( context );
				serializer.Pack( buffer, target );

				buffer.Position = 0;
				var intermediate = Unpacking.UnpackObject( buffer );

				if ( method == SerializationMethod.Array )
				{
					var asArray = intermediate.AsList();
					Assert.That( asArray.Count, Is.EqualTo( 3 ) );
					Assert.That( asArray[ 0 ] == target.ShouldSerialized1 );
					Assert.That( asArray[ 1 ] == target.ShouldSerialized2 );
					Assert.That( asArray[ 2 ] == target.ShouldSerialized3 );
				}
				else
				{
					var asMap = intermediate.AsDictionary();
					Assert.That( asMap.Count, Is.EqualTo( 3 ) );
					Assert.That( asMap[ "ShouldSerialized1" ] == target.ShouldSerialized1 );
					Assert.That( asMap[ "ShouldSerialized2" ] == target.ShouldSerialized2 );
					Assert.That( asMap[ "ShouldSerialized3" ] == target.ShouldSerialized3 );
				}

				buffer.Position = 0;

				var result = serializer.Unpack( buffer );

				Assert.That( result.ShouldSerialized1, Is.EqualTo( target.ShouldSerialized1 ) );
				Assert.That( result.ShouldSerialized2, Is.EqualTo( target.ShouldSerialized2 ) );
				Assert.That( result.ShouldSerialized3, Is.EqualTo( target.ShouldSerialized3 ) );
				Assert.That( result.ShouldNotSerialized1, Is.Not.EqualTo( target.ShouldNotSerialized1 ).And.EqualTo( 0 ) );
				Assert.That( result.ShouldNotSerialized2, Is.Not.EqualTo( target.ShouldNotSerialized2 ).And.EqualTo( 0 ) );
			}
		}
        /// <summary>
        ///		Creates new <see cref="SerializationContext"/> for generation based testing.
        /// </summary>
        /// <param name="method"><see cref="SerializationMethod"/>.</param>
        /// <param name="compatibilityOptions"><see cref="PackerCompatibilityOptions"/> for built-in serializers.</param>
        /// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
        public static SerializationContext CreateContext(SerializationMethod method, PackerCompatibilityOptions compatibilityOptions)
        {
            var context = new SerializationContext(compatibilityOptions)
            {
                SerializationMethod = method
            };

            foreach (var entry in _serializers)
            {
                context.Serializers.Register(entry.Key, entry.Value, null, null, SerializerRegistrationOptions.None);
            }

#if !AOT
            context.SerializerOptions.IsRuntimeGenerationDisabled = true;
#endif // !AOT
            return(context);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
        /// </summary>
        /// <param name="rootType">Type of the root object which will be serialized/deserialized.</param>
        /// <param name="assemblyName">Name of the assembly to be generated.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="rootType"/> is <c>null</c>.
        ///		Or <paramref name="assemblyName"/> is <c>null</c>.
        /// </exception>
        public SerializerGenerator(Type rootType, AssemblyName assemblyName)
        {
            if (rootType == null)
            {
                throw new ArgumentNullException("rootType");
            }

            if (assemblyName == null)
            {
                throw new ArgumentNullException("assemblyName");
            }

            Contract.EndContractBlock();

            this._rootType     = rootType;
            this._assemblyName = assemblyName;
            this._method       = SerializationMethod.Array;
        }
        public static ISerializedObject Serialize(this object graph, SerializationMethod method) {
            if(IsDebugEnabled)
                log.Debug("객체를 직렬화하여 SerializedObject를 생성합니다. method=[{0}], graph=[{1}]", method, graph);

            switch(method) {
                case SerializationMethod.Binary:
                    return new BinarySerializedObject(graph);

                case SerializationMethod.Bson:
                    return new BsonSerializedObject(graph);

                case SerializationMethod.Json:
                    return new JsonSerializedObject(graph);

                case SerializationMethod.Xml:
                    return new XmlSerializedObject(graph);

                case SerializationMethod.Soap:
                    return new SoapSerializedObject(graph);

                default:
                    throw new NotSupportedException(string.Format("지원하지 않는 직렬화 방법입니다. method=[{0}]", method));
            }
        }
        /// <summary>
        /// сериализоать объект и соъранить в указанной директории
        /// </summary>
        /// <param name="o">объект</param>
        /// <param name="path">путь</param>
        /// <param name="method">способ сериализации</param>
        /// <exception cref="IOException"/>
        /// <exception cref="SerializationException"/>
        public static void Save(Object o, string path, SerializationMethod method)
        {
            if (method == SerializationMethod.XML)
            {
               FileStream writer = File.Create(path);
               XmlSerializer serializer = new XmlSerializer(o.GetType());
               serializer.Serialize(writer, o);
                writer.Close();
            }
            if (method == SerializationMethod.Binary)
            {

            }
        }
		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerCodeGenerationConfiguration"/> class.
		/// </summary>
		public SerializerCodeGenerationConfiguration()
		{
			// Set to defaults.
			this.OutputDirectory = null;
			this.Language = null;
			this.Namespace = null;
			this.CodeIndentString = null;
			this._serializationMethod = SerializationMethod.Array;
		}
        /// <summary>
        /// сериализация
        /// </summary>
        /// <param name="o">объект для сериализации</param>
        /// <param name="method">способ сериализации</param>
        /// <returns>строку с серализованным объектом</returns>
        /// <exception cref="IOException"/>
        /// <exception cref="SerializationException"/>
        public static string Serialize(Object o, SerializationMethod method)
        {
            if (method == SerializationMethod.XML)
            {
                string res = null;
                using (TextWriter writer = new StreamWriter("SerializeFile.xml",false,Encoding.UTF8))
                {
                    XmlSerializer serializer = new XmlSerializer(o.GetType());
                    serializer.Serialize(writer, o);
                }

                using (StreamReader reader = new StreamReader("SerializeFile.xml",Encoding.UTF8))
                {
                    res = reader.ReadToEnd();
                }

                File.Delete("SerializeFile.xml");

                return res;
            }
            if (method == SerializationMethod.Binary)
            {

            }
            return null;
        }
		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerAssemblyGenerationConfiguration"/> class.
		/// </summary>
		public SerializerAssemblyGenerationConfiguration()
		{
			this.OutputDirectory = null;
			this._serializationMethod = SerializationMethod.Array;
			this._namespace = DefaultNamespace;
		}
Exemple #41
0
		private static void TestCore( EmitterFlavor emittingFlavor, SerializationMethod serializationMethod, ISerializerBuilder<DirectoryItem> generator )
		{
			var root = new DirectoryItem() { Name = "/" };
			root.Directories =
				new[]
				{
					new DirectoryItem() { Name = "tmp/" },
					new DirectoryItem() 
					{ 
						Name = "var/", 
						Directories = new DirectoryItem[ 0 ], 
						Files = new []{ new FileItem(){ Name = "system.log" } }
					}
				};
			root.Files = new FileItem[ 0 ];

			var serializer = 
				new AutoMessagePackSerializer<DirectoryItem>( 
					new SerializationContext
					{
						EmitterFlavor = emittingFlavor, 
						SerializationMethod = serializationMethod, 
#if SILVERLIGHT
						GeneratorOption = SerializationMethodGeneratorOption.Fast
#else
						GeneratorOption = SerializationMethodGeneratorOption.CanDump
#endif
					}, 
					generator 
				);
			using ( var memoryStream = new MemoryStream() )
			{
				serializer.Pack( memoryStream, root );

				memoryStream.Position = 0;
				var result = serializer.Unpack( memoryStream );
				Assert.That( result.Name, Is.EqualTo( "/" ) );
				Assert.That( result.Files, Is.Not.Null.And.Empty );
				Assert.That( result.Directories, Is.Not.Null.And.Length.EqualTo( 2 ) );
				Assert.That( result.Directories[ 0 ], Is.Not.Null );
				Assert.That( result.Directories[ 0 ].Name, Is.EqualTo( "tmp/" ) );
				Assert.That( result.Directories[ 0 ].Files, Is.Null );
				Assert.That( result.Directories[ 0 ].Directories, Is.Null );
				Assert.That( result.Directories[ 1 ], Is.Not.Null );
				Assert.That( result.Directories[ 1 ].Name, Is.EqualTo( "var/" ) );
				Assert.That( result.Directories[ 1 ].Files, Is.Not.Null.And.Length.EqualTo( 1 ) );
				Assert.That( result.Directories[ 1 ].Files[ 0 ], Is.Not.Null );
				Assert.That( result.Directories[ 1 ].Files[ 0 ].Name, Is.EqualTo( "system.log" ) );
				Assert.That( result.Directories[ 1 ].Directories, Is.Not.Null.And.Empty );
			}
		}
 /// <summary>
 /// Get serializer by serialization method.
 /// </summary>
 /// <param name="method">One of predefined <c>SerializationMethod</c> enum values.</param>
 /// <returns>Serializer object.</returns>
 public ISerializer Get(SerializationMethod method)
 {
     return Get((int)method);
 }
		private static void TestDataContractAndNonSerializableAreMixedCore( SerializationMethod method )
		{
			var context = new SerializationContext() { SerializationMethod = method };

			using ( var buffer = new MemoryStream() )
			{
				var target = new DataContractAndNonSerializedMixedTarget();
				target.ShouldSerialized = 111;
				var serializer = MessagePackSerializer.Create<DataContractAndNonSerializedMixedTarget>( context );
				serializer.Pack( buffer, target );

				buffer.Position = 0;
				var intermediate = Unpacking.UnpackObject( buffer );

				if ( method == SerializationMethod.Array )
				{
					var asArray = intermediate.AsList();
					Assert.That( asArray.Count, Is.EqualTo( 1 ) );
					Assert.That( asArray[ 0 ] == target.ShouldSerialized );
				}
				else
				{
					var asMap = intermediate.AsDictionary();
					Assert.That( asMap.Count, Is.EqualTo( 1 ) );
					Assert.That( asMap[ "ShouldSerialized" ] == target.ShouldSerialized );
				}

				buffer.Position = 0;

				var result = serializer.Unpack( buffer );

				Assert.That( result.ShouldSerialized, Is.EqualTo( target.ShouldSerialized ) );
			}
		}
		/// <summary>
		///		Creates new <see cref="SerializationContext"/> for generation based testing.
		/// </summary>
		/// <param name="method"><see cref="SerializationMethod"/>.</param>
		/// <param name="compatibilityOptions"><see cref="PackerCompatibilityOptions"/> for built-in serializers.</param>
		/// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
		public static SerializationContext CreateContext( SerializationMethod method, PackerCompatibilityOptions compatibilityOptions )
		{
			var context = new SerializationContext( compatibilityOptions ) { SerializationMethod = method };

			foreach ( var entry in _serializers )
			{
				context.Serializers.Register( entry.Key, entry.Value, null, null, SerializerRegistrationOptions.None );
			}

#if !AOT
			context.SerializerOptions.DisableRuntimeCodeGeneration = true;
#endif // !AOT
			return context;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly to be generated.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="assemblyName"/> is <c>null</c>.
		/// </exception>
		public SerializerGenerator( AssemblyName assemblyName )
		{
			if ( assemblyName == null )
			{
				throw new ArgumentNullException( "assemblyName" );
			}

			Contract.EndContractBlock();

			this._assemblyName = assemblyName;
			this._targetTypes = new HashSet<Type>();
			this._method = SerializationMethod.Array;
		}
Exemple #46
0
		private static void TestCore( EmitterFlavor emittingFlavor, SerializationMethod serializationMethod, ISerializerBuilder generator )
		{
			var root = new DirectoryItem() { Name = "/" };
			root.Directories =
				new[]
				{
					new DirectoryItem() { Name = "tmp/" },
					new DirectoryItem() 
					{ 
						Name = "var/", 
						Directories = new DirectoryItem[ 0 ], 
						Files = new []{ new FileItem(){ Name = "system.log" } }
					}
				};
			root.Files = new FileItem[ 0 ];

			var context =
				new SerializationContext
				{
					SerializationMethod = serializationMethod,
					SerializerOptions =
					{
						GeneratorOption = SerializationMethodGeneratorOption.CanDump,
						EmitterFlavor = emittingFlavor
					}
				};

			var serializer =
				( MessagePackSerializer<DirectoryItem> ) generator.BuildSerializerInstance(
					context,
					typeof( DirectoryItem ),
					PolymorphismSchema.Default
				);
			using ( var memoryStream = new MemoryStream() )
			{
				serializer.Pack( memoryStream, root );

				memoryStream.Position = 0;
				var result = serializer.Unpack( memoryStream );
				Assert.That( result.Name, Is.EqualTo( "/" ) );
				Assert.That( result.Files, Is.Not.Null.And.Empty );
				Assert.That( result.Directories, Is.Not.Null.And.Length.EqualTo( 2 ) );
				Assert.That( result.Directories[ 0 ], Is.Not.Null );
				Assert.That( result.Directories[ 0 ].Name, Is.EqualTo( "tmp/" ) );
				Assert.That( result.Directories[ 0 ].Files, Is.Null );
				Assert.That( result.Directories[ 0 ].Directories, Is.Null );
				Assert.That( result.Directories[ 1 ], Is.Not.Null );
				Assert.That( result.Directories[ 1 ].Name, Is.EqualTo( "var/" ) );
				Assert.That( result.Directories[ 1 ].Files, Is.Not.Null.And.Length.EqualTo( 1 ) );
				Assert.That( result.Directories[ 1 ].Files[ 0 ], Is.Not.Null );
				Assert.That( result.Directories[ 1 ].Files[ 0 ].Name, Is.EqualTo( "system.log" ) );
				Assert.That( result.Directories[ 1 ].Directories, Is.Not.Null.And.Empty );
			}
		}
		/// <summary>
		///		Creates new <see cref="SerializationContext"/> for generation based testing.
		/// </summary>
		/// <param name="method"><see cref="SerializationMethod"/>.</param>
		/// <param name="compatibilityOptions"><see cref="PackerCompatibilityOptions"/> for built-in serializers.</param>
		/// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
		public static SerializationContext CreateContext( SerializationMethod method, PackerCompatibilityOptions compatibilityOptions )
		{
			var context = new SerializationContext( compatibilityOptions ) { SerializationMethod = method };

			var serializers =
				method == SerializationMethod.Array
				? _arrayBasedSerializers
				: _mapBasedSerializers;

			foreach ( var entry in serializers )
			{
				context.Serializers.Register( entry.Key, entry.Value );
			}

#if !XAMIOS && !UNITY_IPHONE
			context.IsRuntimeGenerationDisabled = true;
#endif
			return context;
		}
		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerAssemblyGenerationConfiguration"/> class.
		/// </summary>
		public SerializerAssemblyGenerationConfiguration()
		{
			this.OutputDirectory = null;
			this._serializationMethod = SerializationMethod.Array;
		}
 public SerializationOptions(SerializationMethod method, bool isCompress, bool isEncrypt) {
     Method = method;
     IsCompress = isCompress;
     IsEncrypt = isEncrypt;
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
		/// </summary>
		/// <param name="rootType">Type of the root object which will be serialized/deserialized.</param>
		/// <param name="assemblyName">Name of the assembly to be generated.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="rootType"/> is <c>null</c>.
		///		Or <paramref name="assemblyName"/> is <c>null</c>.
		/// </exception>
		public SerializerGenerator( Type rootType, AssemblyName assemblyName )
		{
			if ( rootType == null )
			{
				throw new ArgumentNullException( "rootType" );
			}

			if ( assemblyName == null )
			{
				throw new ArgumentNullException( "assemblyName" );
			}

			Contract.EndContractBlock();

			this._rootType = rootType;
			this._assemblyName = assemblyName;
			this._method = SerializationMethod.Array;
		}
 public void setCustomMethod(SerializationMethod pCustomMethod)
 {
     customMethods[pCustomMethod.serializeType] = pCustomMethod;
 }
Exemple #52
0
		private static TestResult[] Test(
			EmitterFlavor flavor,
			SerializationMethod method,
			EnumSerializationMethod enumMethod )
		{
			var stopWatch = new Stopwatch();
			using ( var buffer = new MemoryStream() )
			{
				// JIT
				TestCreateSerializer(
					stopWatch,
					new SerializationContext
					{
						EmitterFlavor = flavor,
						SerializationMethod = method,
						EnumSerializationMethod = enumMethod
					}
					);
				TestSerialize(
					stopWatch,
					buffer,
					new SerializationContext
					{
						EmitterFlavor = flavor,
						SerializationMethod = method,
						EnumSerializationMethod = enumMethod
					}
					);
				buffer.Position = 0;
				TestDeserialize(
					stopWatch,
					buffer,
					new SerializationContext
					{
						EmitterFlavor = flavor,
						SerializationMethod = method,
						EnumSerializationMethod = enumMethod
					}
					);

				var samples = new long[ flavor == EmitterFlavor.CodeDomBased ? 10 : Iteration ];

				// 1st-time only
				for ( int i = 0; i < samples.Length; i++ )
				{
					TestCreateSerializer(
						stopWatch,
						new SerializationContext
						{
							EmitterFlavor = flavor,
							SerializationMethod = method,
							EnumSerializationMethod = enumMethod
						}
						);
					samples[ i ] = stopWatch.Elapsed.Ticks;
				}

				var creationResult = Calculate( samples );

				samples = new long[ Iteration ];

				// Exept-1st time
				var context =
					new SerializationContext
					{
						EmitterFlavor = flavor,
						SerializationMethod = method,
						EnumSerializationMethod = enumMethod
					};

				var samples2 = new long[ samples.Length ];

				// Dry-run
				buffer.SetLength( 0 );
				TestSerialize( stopWatch, buffer, context );
				buffer.Position = 0;
				TestDeserialize( stopWatch, buffer, context );

				for ( int i = 0; i < samples.Length; i++ )
				{
					buffer.SetLength( 0 );
					TestSerialize( stopWatch, buffer, context );
					samples[ i ] = stopWatch.Elapsed.Ticks;
					buffer.Position = 0;
					TestDeserialize( stopWatch, buffer, context );
					samples2[ i ] = stopWatch.Elapsed.Ticks;
				}

				var serializationResult = Calculate( samples );
				var deserializationResult = Calculate( samples2 );

				return new TestResult[] { creationResult, serializationResult, deserializationResult };
			}
		}
        /// <summary>
        /// открытие сериализованного объекта из файла
        /// </summary>
        /// <param name="type">тип результата</param>
        /// <param name="path">путь</param>
        /// <param name="method">способ десериализации</param>
        /// <returns>десериализовнный объект</returns>
        /// <exception cref="SerializationException"/>
        /// <exception cref="IOException"/>
        public static object Open(Type type,string path, SerializationMethod method)
        {
            try
            {
                if (method == SerializationMethod.XML)
                {
                    FileStream fs = File.OpenRead(path);
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    string xml = Encoding.UTF8.GetString(bytes);

                    return DeserializeXML(type, xml);
                }
                if (method == SerializationMethod.Binary)
                {
                    return null;
                }
            }
            catch (SerializationException ex)
            {
                throw new SerializationException("", ex); ;
            }
            catch (Exception ex)
            {
                throw new IOException("", ex);
            }
            return null;
        }
        private static IndexEntries DeserializeIndexDatabase(string pathToIndexFile, SerializationMethod method)
        {
            if (File.Exists(pathToIndexFile) == false)
            {
                return new IndexEntries();
            }

            switch (method)
            {
                case SerializationMethod.BINARY:
                    using (var stream = new FileStream(pathToIndexFile, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        var formatter = new BinaryFormatter();
                        return (IndexEntries)formatter.Deserialize(stream);
                    }
                case SerializationMethod.JSON:
                    return JsonConvert.DeserializeObject<IndexEntries>(File.ReadAllText(pathToIndexFile));
            }

            throw new InvalidOperationException("Did not find appropriate deserialization method");
        }