Beispiel #1
0
		internal RpcServerRuntime( RpcServerConfiguration configuration, SerializationContext serializationContext )
		{
			this._configuration = configuration;
			this._serializationContext = serializationContext;
			this._applicationContextPool =
				configuration.ApplicationContextPoolProvider(
					() => new RpcApplicationContext(
						configuration.ExecutionTimeout,
						configuration.HardExecutionTimeout
					),
				configuration.CreateApplicationContextPoolConfiguration()
			);
			this._softTimeoutDetails =
				new MessagePackObject(
					new MessagePackObjectDictionary()
					{
						{ RpcException.MessageKeyUtf8, "Execution timeout." },
						{ 
							RpcException.DebugInformationKeyUtf8, 
							String.Format( 
								CultureInfo.InvariantCulture, 
								"{{ \"ExecutionTimeout\" : \"{0}\", \"HardExecutionTimeout\" : \"{1}\" }}",
								configuration.ExecutionTimeout,
								configuration.HardExecutionTimeout
							)
						}
					},
					true
				);
		}
		/// <summary>
		///		Gets a serializer instance for specified parameter.
		/// </summary>
		/// <param name="context">A serialization context which holds global settings.</param>
		/// <param name="providerParameter">A provider specific parameter.</param>
		/// <returns>	
		/// A serializer object for specified parameter.
		/// </returns>
		public override object Get( SerializationContext context, object providerParameter )
		{
			if ( ( providerParameter is EnumSerializationMethod ) )
			{
				switch ( ( EnumSerializationMethod )providerParameter )
				{
					case EnumSerializationMethod.ByName:
					{
						return this._serializerForName;
					}
					case EnumSerializationMethod.ByUnderlyingValue:
					{
						return this._serializerForIntegral;
					}
				}
			}

			switch ( 
				EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod( 
					context, this._enumType, EnumMemberSerializationMethod.Default 
				) 
			)
			{
				case EnumSerializationMethod.ByUnderlyingValue:
				{
					return this._serializerForIntegral;
				}
				default:
				{
					return this._serializerForName;
				}
			}
		}
		public static DateTimeConversionMethod DetermineDateTimeConversionMethod(
			SerializationContext context,
			DateTimeMemberConversionMethod dateTimeMemberConversionMethod 
		)
		{
			if ( context == null )
			{
				throw new ArgumentNullException( "context" );
			}

			switch ( dateTimeMemberConversionMethod )
			{
				case DateTimeMemberConversionMethod.Native:
				{
					return DateTimeConversionMethod.Native;
				}
				case DateTimeMemberConversionMethod.UnixEpoc:
				{
					return DateTimeConversionMethod.UnixEpoc;
				}
				default:
				{
					return context.DefaultDateTimeConversionMethod;
				}
			}
		}
Beispiel #4
0
		public async Task RunAsync()
		{
			// Now supports async.
			var context = new SerializationContext();

			// Asynchronous is allowed by default.
			Assert.True( context.SerializerOptions.WithAsync );

			var serializer = context.GetSerializer<PhotoEntry>();
			var targetObject =
				new PhotoEntry // See Sample01_BasicUsage.cs
				{
					Id = 123,
					Title = "My photo",
					Date = DateTime.Now,
					Image = new byte[] { 1, 2, 3, 4 },
					Comment = "This is test object to be serialize/deserialize using MsgPack."
				};

			using ( var stream = new MemoryStream() )
			{
				// Note: PackAsync/UnpackAsync uses internal BufferedStream to avopid chatty asynchronous call for underlying I/O system.
				//       If you change this behavior, use PackToAsync/UnpackFromAsync with Packer/Unpacker factories to specify options.
				await serializer.PackAsync( stream, targetObject );
				stream.Position = 0;
				var roundTripped = await serializer.UnpackAsync( stream );
			}
		}
        public EntityPropertiesTests()
        {
            var context = new SerializationContext();
            context.SerializationMethod = SerializationMethod.Map;

            _serializer = context.GetSerializer<BasicEntity>();
        }
		public object Get( SerializationContext context, Type keyType )
		{
			object matched;
			object genericDefinitionMatched;
			if ( !this.Get( keyType, out matched, out genericDefinitionMatched ) )
			{
				return null;
			}

			if ( matched != null )
			{
				return matched;
			}
			// ReSharper disable once RedundantIfElseBlock
			else
			{
#if !UNITY_ANDROID && !UNITY_IPHONE
				Contract.Assert( keyType.GetIsGenericType() );
				Contract.Assert( !keyType.GetIsGenericTypeDefinition() );
#endif // !UNITY_ANDROID && !UNITY_IPHONE
				var type = genericDefinitionMatched as Type;
#if !UNITY_ANDROID && !UNITY_IPHONE
				Contract.Assert( type != null );
				Contract.Assert( type.GetIsGenericTypeDefinition() );
#endif // !UNITY_ANDROID && !UNITY_IPHONE
				var result = Activator.CreateInstance( type.MakeGenericType( keyType.GetGenericArguments() ), context );
#if !UNITY_ANDROID && !UNITY_IPHONE
				Contract.Assert( result != null );
#endif // !UNITY_ANDROID && !UNITY_IPHONE
				return result;
			}
		}
Beispiel #7
0
        public void OnImportsSatisfied()
        {
            var context = new SerializationContext();
            context.CompatibilityOptions.PackerCompatibilityOptions = MsgPack.PackerCompatibilityOptions.PackBinaryAsRaw;

            serializer = new MsgPackMessageSerializer(context);
        }
		public static IList<SerializingMember> Prepare( SerializationContext context, Type targetType )
		{
			var result = PrepareCore( context, targetType );

			VerifyNilImplication( targetType, result );

			return result;
		}
		byte IPolymorphicHelperAttribute.GetBindingCode( SerializationContext context )
		{
			if ( this.BindingCode > 127 )
			{
				throw new SerializationException( "BindingCode must be under 128(0x80)." );
			}

			return this.BindingCode;
		}
		public void TestCreate_WithContext_NewInstance()
		{
			var context = new SerializationContext();
			var first = MessagePackSerializer.Create<int>( context );
			Assert.That( first, Is.Not.Null );
			var second = MessagePackSerializer.Create<int>( context );
			Assert.That( second, Is.Not.Null );
			Assert.That( first, Is.Not.SameAs( second ) );
		}
        protected virtual SerializationContext GetSerializationContext()
        {
            var ctx = new MsgPack.Serialization.SerializationContext();

            foreach (var plugin in _plugins)
            {
                plugin.OnCreatingSerializationContext(ctx);
            }
            return(ctx);
        }
		public void TestCreate_WithContext_SameTypeAsCreate1()
		{
			var context = new SerializationContext();
			var first = MessagePackSerializer.Create( typeof( Image ), context );
			Assert.That( first, Is.Not.Null );
			var second = MessagePackSerializer.Create<Image>( context );
			Assert.That( second, Is.Not.Null );
#if !UNITY
			Assert.That( first.GetType(), Is.EqualTo( second.GetType() ) );
#endif // !UNITY
		}
		public static EnumSerializationMethod DetermineEnumSerializationMethod(
			SerializationContext context,
			Type enumType,
			EnumMemberSerializationMethod enumMemberSerializationMethod 
		)
		{
			if ( context == null )
			{
				throw new ArgumentNullException( "context" );
			}

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

			EnumSerializationMethod method = context.EnumSerializationMethod;
			switch ( enumMemberSerializationMethod )
			{
				case EnumMemberSerializationMethod.ByName:
				{
					method = EnumSerializationMethod.ByName;
					break;
				}
				case EnumMemberSerializationMethod.ByUnderlyingValue:
				{
					method = EnumSerializationMethod.ByUnderlyingValue;
					break;
				}
				default:
				{
#if NETFX_CORE
					var messagePackEnumAttribute = 
						enumType.GetTypeInfo().GetCustomAttribute<MessagePackEnumAttribute>();
					if ( messagePackEnumAttribute != null)
					{
						method = messagePackEnumAttribute.SerializationMethod;
#else
					var messagePackEnumAttributes =
						enumType.GetCustomAttributes( typeof( MessagePackEnumAttribute ), true );
					if ( messagePackEnumAttributes.Length > 0 )
					{
						// ReSharper disable once PossibleNullReferenceException
						method = ( messagePackEnumAttributes[ 0 ] as MessagePackEnumAttribute ).SerializationMethod;
#endif // NETFX_CORE
					}

					break;
				}
			}

			return method;
		}
	}
		private NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, PackerCompatibilityOptions? packerCompatibilityOptions )
		{
			if ( ownerContext == null )
			{
				throw new ArgumentNullException( "ownerContext" );
			}

			this._packerCompatibilityOptionsForCompatibility = packerCompatibilityOptions;
			this._ownerContext = ownerContext;
			this._targetType = targetType;
			this._isNullable = JudgeNullable( targetType );
		}
		public void SerializeThenDeserialize()
		{
			// They are object for just description. 
			var targetObject =
				new PhotoEntry // See Sample01_BasicUsage.cs
				{
					Id = 123,
					Title = "My photo",
					Date = DateTime.Now,
					Image = new byte[] { 1, 2, 3, 4 },
					Comment = "This is test object to be serialize/deserialize using MsgPack."
				};
			targetObject.Tags.Add( "Sample" );
			targetObject.Tags.Add( "Excellent" );
			var stream = new MemoryStream();

			// Set using Map instead of Array to serialize complex object. See Sample03 for details.
			var context = new SerializationContext();
			context.SerializationMethod = SerializationMethod.Map;
			// You can use default context if you want to use map in all serializations which use default context.
			// SerializationContext.Default.SerializationMethod = SerializationMethod.Map;

			// 1. Create serializer instance.
			var serializer = MessagePackSerializer.Get<PhotoEntry>( context );

			// 2. Serialize object to the specified stream.
			serializer.Pack( stream, targetObject );

			// Set position to head of the stream to demonstrate deserialization.
			stream.Position = 0;

			// 3. Unpack MessagePackObject to get raw representation.
			var rawObject = Unpacking.UnpackObject( stream );
			// You can read MPO tree via Unpacker
			// var unpacker = Unpacker.Create( stream );

			// Check its type
			Debug.WriteLine( "Is array? {0}", rawObject.IsArray ); // IsList is alias
			Debug.WriteLine( "Is map? {0}", rawObject.IsMap ); // IsDictionary is alias
			Debug.WriteLine( "Type: {0}", rawObject.UnderlyingType );

			// Gets serialized fields.
			// Note: When the object was serialized as array instead of map, use index instead.
			var asDictionary = rawObject.AsDictionary();
			Debug.WriteLine( "Id : {0}({1})", asDictionary[ "Id" ], asDictionary[ "Id" ].UnderlyingType );
			// String is encoded as utf-8 by default.
			Debug.WriteLine( "Title : {0}({1})", asDictionary[ "Title" ], asDictionary[ "Title" ].UnderlyingType );
			// Non-primitive is serialized as complex type or encoded primitive type.
			// DateTimeOffset is encoded as array[2]{ticks,offset}
			Debug.WriteLine( "Date : {0}({1})", asDictionary[ "Date" ], asDictionary[ "Date" ].UnderlyingType );
			// byte[] is byte[], as you know.
			Debug.WriteLine( "Image : {0}({1})", asDictionary[ "Image" ], asDictionary[ "Image" ].UnderlyingType );
		}
		public object Get( SerializationContext context, Type keyType )
		{
			object matched;
			object genericDefinitionMatched;
			if ( !this.Get( keyType, out matched, out genericDefinitionMatched ) )
			{
				return null;
			}

			if ( matched != null )
			{
				return matched;
			}
			else
			{
#if DEBUG
				Contract.Assert( keyType.GetIsGenericType(), "keyType.GetIsGenericType()" );
				Contract.Assert( !keyType.GetIsGenericTypeDefinition(), "!keyType.GetIsGenericTypeDefinition()" );
#endif // DEBUG
				var type = genericDefinitionMatched as Type;
#if DEBUG
				Contract.Assert( type != null, "type != null" );
				Contract.Assert( type.GetIsGenericTypeDefinition(), "type.GetIsGenericTypeDefinition()" );
#endif // DEBUG
#if !UNITY
				var result =
					ReflectionExtensions.CreateInstancePreservingExceptionType( 
						type.MakeGenericType( keyType.GetGenericArguments() ), 
						context
					);
#else
				var resultType = type.IsGenericTypeDefinition ? type.MakeGenericType( keyType.GetGenericArguments() ) : type;
				var constructor2 = resultType.GetConstructor( NonGenericSerializerConstructorParameterTypes );
				object result;
				try
				{
					result =
						constructor2 == null
						? ReflectionExtensions.CreateInstancePreservingExceptionType( resultType, context )
						: ReflectionExtensions.CreateInstancePreservingExceptionType( resultType, context, keyType );
				}
				catch ( Exception ex )
				{
					AotHelper.HandleAotError( keyType, ex );
					throw;
				}
#endif // !UNITY
				Contract.Assert( result != null, "result != null" );

				return result;
			}
		}
Beispiel #17
0
		private static IList<SerializingMember> PrepareCore( SerializationContext context, Type targetType )
		{
			var entries = GetTargetMembers( targetType ).OrderBy( item => item.Contract.Id ).ToArray();

			if ( entries.Length == 0 )
			{
				throw SerializationExceptions.NewNoSerializableFieldsException( targetType );
			}

			if ( entries.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
			{
				// Alphabetical order.
				return entries.OrderBy( item => item.Contract.Name ).ToArray();
			}

			// ID order.

#if DEBUG && !UNITY
			Contract.Assert( entries[ 0 ].Contract.Id >= 0 );
#endif // DEBUG && !UNITY

			if ( context.CompatibilityOptions.OneBoundDataMemberOrder && entries[ 0 ].Contract.Id == 0 )
			{
				throw new NotSupportedException( "Cannot specify order value 0 on DataMemberAttribute when SerializationContext.CompatibilityOptions.OneBoundDataMemberOrder is set to true." );
			}

			var maxId = entries.Max( item => item.Contract.Id );
			var result = new List<SerializingMember>( maxId + 1 );
			for ( int source = 0, destination = context.CompatibilityOptions.OneBoundDataMemberOrder ? 1 : 0; source < entries.Length; source++, destination++ )
			{
#if DEBUG && !UNITY
				Contract.Assert( entries[ source ].Contract.Id >= 0 );
#endif // DEBUG && !UNITY

				if ( entries[ source ].Contract.Id < destination )
				{
					throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The member ID '{0}' is duplicated in the '{1}' elementType.", entries[ source ].Contract.Id, targetType ) );
				}

				while ( entries[ source ].Contract.Id > destination )
				{
					result.Add( new SerializingMember() );
					destination++;
				}

				result.Add( entries[ source ] );
			}

			return result;
		} 
Beispiel #18
0
		public void TestConstructorRpcClient_Normal_SetPropertyAsIs()
		{
			using ( var environment = new InProcTestEnvironment() )
			{
				var configuration = RpcClientConfiguration.Default.Clone();
				configuration.TransportManagerProvider = conf => environment.ClientTransportManager;
				SerializationContext serializationContext = new SerializationContext();

				using ( RpcClient target = new RpcClient( environment.EndPoint, configuration, serializationContext ) )
				{
					Assert.That( target.SerializationContext, Is.SameAs( serializationContext ) );
				}
			}
		}
		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 ) );
			}
		}
Beispiel #20
0
		public void Issue147_161_162_HidingMembersWillNotBeDuplicated()
		{
			var context = new SerializationContext();
			context.SerializationMethod = SerializationMethod.Array;
			var serializer = context.GetSerializer<Child>();
			using ( var buffer = new MemoryStream() )
			{
				var obj = new Child { Field = new List<string> { "A", "B" }, Property = new List<string> { "C", "D" } };
				serializer.Pack( buffer, obj );
				
				buffer.Position = 0;

				using ( var unpacker = Unpacker.Create( buffer, ownsStream: false ) )
				{
					Assert.That( unpacker.Read() );
					// If the hiding is not respected, this value will be 4.
					Assert.That( unpacker.LastReadData.AsInt32(), Is.EqualTo( 2 ) );
				}
			}
		}
		public void Polymorphism()
		{
			// As of 0.7, polymorphism is implemented.

			// Setup the context to use map for pretty printing.
			var context = new SerializationContext { SerializationMethod = SerializationMethod.Map };

			var serializer = context.GetSerializer<PolymorphicHolder>();

			var rootObject =
				new PolymorphicHolder
				{
					WithRuntimeType = new FileObject { Path = "/path/to/file" },
					WithKnownType = new DirectoryObject { Path = "/path/to/dir/" }
				};

			using ( var buffer = new MemoryStream() )
			{
				serializer.Pack(
					buffer, new PolymorphicHolder
					{
						WithRuntimeType = new FileObject { Path = "/path/to/file" },
						WithKnownType = new DirectoryObject { Path = "/path/to/dir/" }
					}
				);

				buffer.Position = 0;

				Print( buffer );

				buffer.Position = 0;
				var deserialized = serializer.Unpack( buffer );

				Assert.That( deserialized.WithRuntimeType, Is.TypeOf<FileObject>() );
				Assert.That( deserialized.WithRuntimeType.Path, Is.EqualTo( "/path/to/file" ) );
				Assert.That( deserialized.WithKnownType, Is.TypeOf<DirectoryObject>() );
				Assert.That( deserialized.WithKnownType.Path, Is.EqualTo( "/path/to/dir/" ) );
			}
		}
		public static SerializationTarget Prepare( SerializationContext context, Type targetType )
		{
			var getters = GetTargetMembers( targetType ).OrderBy( entry => entry.Contract.Id ).ToArray();

			if ( getters.Length == 0 )
			{
				throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it does not have any serializable fields nor properties.", targetType ) );
			}

			var memberCandidates = getters.Where( entry => CheckTargetEligibility( entry.Member ) ).ToArray();

			if ( memberCandidates.Length == 0 )
			{
				var constructor = FindDeserializationConstructor( targetType );
				return new SerializationTarget( ComplementMembers( getters, context, targetType ), constructor );
			}

			var defaultConstructor = targetType.GetConstructor( ReflectionAbstractions.EmptyTypes );
			if ( defaultConstructor == null && !targetType.GetIsValueType() )
			{
				throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructor( targetType );
			}

			// Because members' order is equal to declared order is NOT guaranteed, so explicit ordering is required.
			IList<SerializingMember> members;
			if ( memberCandidates.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
			{
				// Alphabetical order.
				members = memberCandidates.OrderBy( item => item.Contract.Name ).ToArray();
			}
			else
			{
				// ID order.
				members = ComplementMembers( memberCandidates, context, targetType );
			}

			return new SerializationTarget( members, defaultConstructor );
		}
		public void CustomizeSerializeBehavior()
		{
			// 1. To take advantage of SerializationContext, you should create own context to isolate others.
			//    Note that SerializationContext is thread safe.
			//    As you imagine, you can change 'default' settings by modifying properties of SerializationContext.Default.
			var context = new SerializationContext();

			// 2. Set options.

			// 2-1. SerializationMethod: it changes comple type serialization method as array or map.
			//     Array(default): Space and time efficient, but depends on member declaration order so less version torrelant.
			//     Map : Less effitient, but more version torrelant (and easy to traverse as MesasgePackObject).
			context.SerializationMethod = SerializationMethod.Map;

			// 2-2. EnumSerializationMethod: it changes enum serialization as their name or underlying value.
			//    ByName(default): More version torrelant and interoperable, and backward compatible prior to 0.5 of MsgPack for CLI.
			//    ByUnderlyingValue: More efficient, but you should manage their underlying value and specify precise data contract between counterpart systems.
			context.EnumSerializationMethod = EnumSerializationMethod.ByUnderlyingValue;

			// 2-3. If CompatibilityOptions.OneBoundDataMemberOrder is set, the origin DataMemberAttribute.Order becomes 1.
			//      It is compatibility options 1 base library like Proto-buf.NET.
			context.CompatibilityOptions.OneBoundDataMemberOrder = true;

			// 2-4. The CompatibilityOptions.PackerCompatibilityOptions control packer compatibility level.
			//      If you want to communicate with the library which only supports legacy message pack format spec, use PackerCompatibilityOptions.Classic flag set (default).
			//      If you want to utilize full feature including tiny string type, binary type, extended type, specify PackerCompatibilityOptions.None explicitly.
			context.CompatibilityOptions.PackerCompatibilityOptions = PackerCompatibilityOptions.None;

			// 2-5. You can tweak default concrete collection types for collection interfaces including IEnumerable<T>, IList, etc.
			context.DefaultCollectionTypes.Unregister( typeof( IList<> ) );
			context.DefaultCollectionTypes.Register( typeof( IList<> ), typeof( Collection<> ) );

			// 3. Get a serializer instance with customized settings.
			var serializer = MessagePackSerializer.Get<PhotoEntry>( context );

			// Following instructions are omitted... see sample 01.
		}
			/// <summary>
			///		Generates serializers using a specified assembly builder.
			/// </summary>
			/// <param name="context">The dedicated <see cref="SerializationContext"/>.</param>
			/// <param name="generatorManager">The dedicated <see cref="SerializationMethodGeneratorManager"/>.</param>
			public abstract void GenerateSerializerTo( SerializationContext context, SerializationMethodGeneratorManager generatorManager );
 /// <summary>
 ///		Gets existing or new <see cref="MessagePackSerializer"/> instance with specified <see cref="SerializationContext"/>.
 /// </summary>
 /// <param name="targetType">Target type.</param>
 /// <param name="context">
 ///		<see cref="SerializationContext"/> to store known/created serializers.
 /// </param>
 /// <returns>
 ///		<see cref="MessagePackSerializer"/>.
 ///		If there is exiting one, returns it.
 ///		Else the new instance will be created.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="targetType"/> is <c>null</c>.
 ///		Or, <paramref name="context"/> is <c>null</c>.
 /// </exception>
 /// <remarks>
 ///		<para>
 ///			This method simply invokes <see cref="SerializationContext.GetSerializer(Type)"/>, so see the method description for details.
 ///		</para>
 ///		<para>
 ///		Although <see cref="Get{T}(SerializationContext)"/> is preferred,
 ///		this method can be used from non-generic type or methods.
 ///		</para>
 /// </remarks>
 public static MessagePackSerializer Get(Type targetType, SerializationContext context)
 {
     return(Get(targetType, context, null));
 }
			// ReSharper disable UnusedMember.Local
			// This method is invoked via Reflection on SerializerGetter.Get().
			public static MessagePackSerializer Get( SerializationContext context, object providerParameter )
			{
				return _func( context, providerParameter );
			}
Beispiel #27
0
            public IEnumerable <SerializerCodeGenerationResult> Generate(IEnumerable <Type> targetTypes, TConfig configuration)
            {
                if (targetTypes == null)
                {
                    throw new ArgumentNullException("targetTypes");
                }

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

                configuration.Validate();
                var context =
                    new SerializationContext
                {
                    SerializationMethod = configuration.SerializationMethod,
                    SerializerOptions   =
                    {
#if FEATURE_TAP
                        WithAsync       = configuration.WithAsync,
#endif // FEATURE_TAP
                        GeneratorOption = SerializationMethodGeneratorOption.CanDump,
                        EmitterFlavor   = this.EmitterFlavor
                    },
                    EnumSerializationOptions =
                    {
                        SerializationMethod = configuration.EnumSerializationMethod
                    },
                    CompatibilityOptions =
                    {
                        AllowNonCollectionEnumerableTypes = configuration.CompatibilityOptions.AllowNonCollectionEnumerableTypes,
                        IgnorePackabilityForCollection    = configuration.CompatibilityOptions.IgnorePackabilityForCollection,
                        OneBoundDataMemberOrder           = configuration.CompatibilityOptions.OneBoundDataMemberOrder,
                        PackerCompatibilityOptions        = configuration.CompatibilityOptions.PackerCompatibilityOptions
                    }
                };

                IEnumerable <Type> realTargetTypes;

                if (configuration.IsRecursive)
                {
                    realTargetTypes =
                        targetTypes
                        .SelectMany(t => ExtractElementTypes(context, configuration, t));
                }
                else
                {
                    realTargetTypes =
                        targetTypes
                        .Where(t => !SerializationTarget.BuiltInSerializerExists(configuration, t, t.GetCollectionTraits(CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes)));
                }

                var generationContext = this.CreateGenerationContext(context, configuration);
                var generatorFactory  = this.CreateGeneratorFactory(context);

                foreach (var targetType in realTargetTypes.Distinct())
                {
                    var generator = generatorFactory(targetType);

                    var concreteType = default(Type);
                    if (targetType.GetIsInterface() || targetType.GetIsAbstract())
                    {
                        concreteType = context.DefaultCollectionTypes.GetConcreteType(targetType);
                    }

                    generator.BuildSerializerCode(generationContext, concreteType, null);
                }

                Directory.CreateDirectory(configuration.OutputDirectory);

                return(generationContext.Generate());
            }
Beispiel #28
0
        public void TestDefaultCollectionTypes_Register_AbstractType_Fail()
        {
            var context = new SerializationContext();

            Assert.Throws <ArgumentException>(() => context.DefaultCollectionTypes.Register(typeof(IList), typeof(IList <MessagePackObject>)));
        }
        public static MessagePackSerializer Create(Type targetType, SerializationContext context)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

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

#if DEBUG
            Contract.Ensures(Contract.Result <MessagePackSerializer>() != null);
#endif // DEBUG

#if AOT
            return(CreateInternal(context, targetType, null));
#else
            // MPS.Create should always return new instance, and creator delegate should be cached for performance.
#if NETSTANDARD1_1 || NETSTANDARD1_3
            var factory =
                _creatorCache.GetOrAdd(
                    targetType,
                    type =>
                    // Utilize covariance of delegate.
                    Metadata._MessagePackSerializer.Create1_Method.MakeGenericMethod(type).CreateDelegate(
                        typeof(Func <SerializationContext, MessagePackSerializer>)
                        ) as Func <SerializationContext, MessagePackSerializer>
                    );
#elif SILVERLIGHT || NETFX_35
            Func <SerializationContext, MessagePackSerializer> factory;

            lock ( _syncRoot )
            {
                _creatorCache.TryGetValue(targetType, out factory);
            }

            if (factory == null)
            {
                // Utilize covariance of delegate.
                factory =
                    Delegate.CreateDelegate(
                        typeof(Func <SerializationContext, MessagePackSerializer>),
                        Metadata._MessagePackSerializer.Create1_Method.MakeGenericMethod(targetType)
                        ) as Func <SerializationContext, MessagePackSerializer>;

                Contract.Assert(factory != null);

                lock ( _syncRoot )
                {
                    _creatorCache[targetType] = factory;
                }
            }
#else
            var factory =
                _creatorCache.GetOrAdd(
                    targetType,
                    type =>
                    // Utilize covariance of delegate.
                    Delegate.CreateDelegate(
                        typeof(Func <SerializationContext, MessagePackSerializer>),
                        Metadata._MessagePackSerializer.Create1_Method.MakeGenericMethod(type)
                        ) as Func <SerializationContext, MessagePackSerializer>
                    );
#endif // NETSTANDARD1_1 || NETSTANDARD1_3
            return(factory(context));
#endif // AOT
        }
 private MessagePackSerializer <T> CreateTarget <T>(SerializationContext context)
 {
     return(MessagePackSerializer.CreateInternal <T>(context, PolymorphismSchema.Default));
 }
Beispiel #31
0
 /// <summary>
 ///		Gets a serializer instance for specified parameter.
 /// </summary>
 /// <param name="context">A serialization context which holds global settings.</param>
 /// <param name="providerParameter">A provider specific parameter.</param>
 /// <returns>A serializer object for specified parameter.</returns>
 public abstract object Get(SerializationContext context, object providerParameter);
Beispiel #32
0
 private MessagePackSerializer <T> CreateTarget <T>(SerializationContext context)
 {
     return(MessagePackSerializer.CreateInternal <T>(context));
 }
Beispiel #33
0
 public CustomImageSerializer(SerializationContext context)
     : base(context)
 {
 }
Beispiel #34
0
        public void TestGetSerializer_Null()
        {
            var target = new SerializationContext();

            Assert.Throws <ArgumentNullException>(() => target.GetSerializer(null));
        }
Beispiel #35
0
        public void TestDefaultCollectionTypes_Register_CloseOpen_Fail()
        {
            var context = new SerializationContext();

            Assert.Throws <ArgumentException>(() => context.DefaultCollectionTypes.Register(typeof(IList <string>), typeof(List <>)));
        }
Beispiel #36
0
		private static void TestSerialize( Stopwatch stopWatch, Stream buffer, SerializationContext serializationContext )
		{
			var target =
				new PhotoData
				{
					Id = 123,
					Image = Image,
					Rating = Rating.Good,
					TakenDateTime = DateTimeOffset.Now,
					Title = "Favorite"
				};
			target.Tags.Add( "Example" );
			target.Tags.Add( "Foo" );
			target.Tags.Add( "Bar" );

			var serializer = serializationContext.GetSerializer<PhotoData>();
			stopWatch.Restart();
			serializer.Pack( buffer, target );
			stopWatch.Stop();
		}
Beispiel #37
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 };
			}
		}
Beispiel #38
0
 public TestValueTypeWrapperSerializer(SerializationContext context)
     : base(context)
 {
     this._serializer0 = context.GetSerializer <TestValueType>(PolymorphismSchema.Default);
 }
        internal static MessagePackSerializer <T> CreateInternal <T>(SerializationContext context, PolymorphismSchema schema)
        {
#if DEBUG
            Contract.Ensures(Contract.Result <MessagePackSerializer <T> >() != null);
#endif // DEBUG

#if DEBUG && !AOT && !SILVERLIGHT
            SerializerDebugging.TraceEmitEvent(
                "SerializationContext::CreateInternal<{0}>(@{1}, {2})",
                typeof(T),
                context.GetHashCode(),
                schema == null ? "null" : schema.DebugString
                );
#endif // DEBUG && !AOT && !SILVERLIGHT
            Type             concreteType     = null;
            CollectionTraits collectionTraits =
#if AOT
                typeof(T).GetCollectionTraits(CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes);
#else
                typeof(T).GetCollectionTraits(CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes);
#endif // AOT

            if (typeof(T).GetIsAbstract() || typeof(T).GetIsInterface())
            {
                // Abstract collection types will be handled correctly.
                if (collectionTraits.CollectionType != CollectionKind.NotCollection)
                {
                    concreteType = context.DefaultCollectionTypes.GetConcreteType(typeof(T));
                }

                if (concreteType == null)
                {
                    // return null for polymoirphic provider.
                    return(null);
                }

                ValidateType(concreteType);
            }
            else
            {
                ValidateType(typeof(T));
            }

#if FEATURE_EMIT
            ISerializerBuilder builder;
            switch (context.SerializerOptions.EmitterFlavor)
            {
            case EmitterFlavor.CodeDomBased:
            {
                if (!SerializerDebugging.OnTheFlyCodeDomEnabled)
                {
                    throw new NotSupportedException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  "Flavor '{0:G}'({0:D}) is not supported for serializer instance creation.",
                                  context.SerializerOptions.EmitterFlavor
                                  )
                              );
                }

                builder = new CodeDomSerializerBuilder(typeof(T), collectionTraits);
                break;
            }

            case EmitterFlavor.FieldBased:
            {
                builder = new AssemblyBuilderSerializerBuilder(typeof(T), collectionTraits);
                break;
            }

            default:                     // EmitterFlavor.ReflectionBased
            {
#endif // FEATURE_EMIT
            return
                (GenericSerializer.TryCreateAbstractCollectionSerializer(context, typeof(T), concreteType, schema) as MessagePackSerializer <T>
                 ?? CreateReflectionInternal <T>(context, concreteType ?? typeof(T), schema));

#if FEATURE_EMIT
        }
    }

    return((MessagePackSerializer <T>)builder.BuildSerializerInstance(context, concreteType, schema == null ? null : schema.FilterSelf()));
#endif // FEATURE_EMIT
        }
 /// <summary>
 ///		Gets existing or new <see cref="MessagePackSerializer{T}"/> instance with specified <see cref="SerializationContext"/>.
 /// </summary>
 /// <typeparam name="T">Target type.</typeparam>
 /// <param name="context">
 ///		<see cref="SerializationContext"/> to store known/created serializers.
 /// </param>
 /// <returns>
 ///		<see cref="MessagePackSerializer{T}"/>.
 ///		If there is exiting one, returns it.
 ///		Else the new instance will be created.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="context"/> is <c>null</c>.
 /// </exception>
 /// <remarks>
 ///		This method simply invokes <see cref="Get{T}(SerializationContext,Object)"/> with <c>null</c> for the <c>providerParameter</c>.
 /// </remarks>
 public static MessagePackSerializer <T> Get <T>(SerializationContext context)
 {
     return(Get <T>(context, null));
 }
Beispiel #41
0
 protected abstract Func <Type, ISerializerCodeGenerator> CreateGeneratorFactory(SerializationContext context);
Beispiel #42
0
        public void TestDefaultCollectionTypes_Register_ArityIsTooFew_Fail()
        {
            var context = new SerializationContext();

            Assert.Throws <ArgumentException>(() => context.DefaultCollectionTypes.Register(typeof(IDictionary <,>), typeof(StringKeyDictionary <>)));
        }
Beispiel #43
0
 protected abstract ISerializerCodeGenerationContext CreateGenerationContext(SerializationContext context, TConfig configuration);
Beispiel #44
0
 protected override Func <Type, ISerializerCodeGenerator> CreateGeneratorFactory(SerializationContext context)
 {
     return(type => new CodeDomSerializerBuilder(type, type.GetCollectionTraits(CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes)));
 }
Beispiel #45
0
        /// <summary>
        ///		Initializes a new instance of the <see cref="SerializerBuilder&lt;TObject&gt;"/> class.
        /// </summary>
        /// <param name="context">The <see cref="SerializationContext"/>.</param>
        protected SerializerBuilder(SerializationContext context)
        {
            Contract.Requires(context != null);

            this._context = context;
        }
 public MsgPackContentFormatter(MsgPack.Serialization.SerializationContext serializationContext, string mediaType = "application/x-msgpack", string ext = "mpk")
     : base(mediaType, ext, null)
 {
     this.serializationContext = serializationContext;
 }
        internal static MessagePackSerializer <T> CreateReflectionInternal <T>(SerializationContext context, Type concreteType, PolymorphismSchema schema)
        {
            if (concreteType.GetIsAbstract() || concreteType.GetIsInterface())
            {
                // return null for polymoirphic provider.
                return(null);
            }

            var serializer = context.Serializers.Get <T>(context);

            if (serializer != null)
            {
                // For MessagePack.Create compatibility.
                // Required for built-in types.
                return(serializer);
            }

            ValidateType(typeof(T));
            var traits =
#if !UNITY
                typeof(T).GetCollectionTraits(CollectionTraitOptions.WithAddMethod, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes);
#else
                typeof(T).GetCollectionTraits(CollectionTraitOptions.WithAddMethod | CollectionTraitOptions.WithCountPropertyGetter, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes);
#endif
            switch (traits.CollectionType)
            {
            case CollectionKind.Array:
            case CollectionKind.Map:
            {
                return
                    (#if !UNITY
                     ReflectionSerializerHelper.CreateCollectionSerializer <T>(context, concreteType, traits, (schema ?? PolymorphismSchema.Default)));
#else
                     Wrap <T>(
                         context,
                         ReflectionSerializerHelper.CreateCollectionSerializer <T>(context, concreteType, traits, (schema ?? PolymorphismSchema.Default))
                         );
#endif // !UNITY
            }

            default:
            {
                if (typeof(T).GetIsEnum())
                {
                    return(ReflectionSerializerHelper.CreateReflectionEnumMessagePackSerializer <T>(context));
                }
#if !NETFX_35 && !UNITY
                if (TupleItems.IsTuple(typeof(T)))
                {
                    return
                        (new ReflectionTupleMessagePackSerializer <T>(
                             context,
                             (schema ?? PolymorphismSchema.Default).ChildSchemaList
                             ));
                }
#endif // !NETFX_35 && !UNITY

                SerializationTarget.VerifyType(typeof(T));
                var target = SerializationTarget.Prepare(context, typeof(T));
                return(new ReflectionObjectMessagePackSerializer <T>(context, target, target.GetCapabilitiesForObject()));
            }
            }
        }
Beispiel #48
0
 protected override ISerializerCodeGenerationContext CreateGenerationContext(SerializationContext context, SerializerCodeGenerationConfiguration configuration)
 {
     return(new CodeDomContext(context, configuration));
 }
		private void GenerateAssemblyFile( AssemblyBuilder assemblyBuilder )
		{
			var context = new SerializationContext();
			context.EmitterFlavor = EmitterFlavor.FieldBased;
			context.GeneratorOption = SerializationMethodGeneratorOption.CanDump;
			context.SerializationMethod = this._method;

			// AssemblyBuilder cannot be debugged because no PDB files (and 'dummy' source files to step).
			DefaultSerializationMethodGeneratorManager.SetUpAssemblyBuilderAttributes( assemblyBuilder, false );

			var generatorManager = SerializationMethodGeneratorManager.Get( assemblyBuilder );

			foreach( var targetType in this._targetTypes )
			{
				( Activator.CreateInstance( typeof( Builder<> ).MakeGenericType( targetType) ) as Builder ).GenerateSerializerTo( context, generatorManager );
			}

			assemblyBuilder.Save( this._assemblyName.Name + ".dll" );
		}
Beispiel #50
0
        public void TestDefaultCollectionTypes_Register_NonCollection_Fail()
        {
            var context = new SerializationContext();

            Assert.Throws <ArgumentException>(() => context.DefaultCollectionTypes.Register(typeof(Stream), typeof(MemoryStream)));
        }
Beispiel #51
0
		private static void TestCreateSerializer( Stopwatch stopWatch, SerializationContext serializationContext )
		{
			stopWatch.Restart();
			serializationContext.GetSerializer<PhotoData>();
			stopWatch.Stop();
		}
 internal ResolveSerializerEventArgs(SerializationContext context, Type targetType, PolymorphismSchema schema)
 {
     this.Context            = context;
     this.TargetType         = targetType;
     this.PolymorphismSchema = schema ?? PolymorphismSchema.Default;
 }
Beispiel #53
0
		private static void TestDeserialize( Stopwatch stopWatch, Stream buffer, SerializationContext serializationContext )
		{
			var serializer = serializationContext.GetSerializer<PhotoData>();
			stopWatch.Restart();
			serializer.Unpack( buffer );
			stopWatch.Stop();
		}
Beispiel #54
0
 protected override ISerializerCodeGenerationContext CreateGenerationContext(SerializationContext context, SerializerAssemblyGenerationConfiguration configuration)
 {
     return
         (new AssemblyBuilderCodeGenerationContext(
              context,
              AppDomain.CurrentDomain.DefineDynamicAssembly(
                  configuration.AssemblyName,
                  AssemblyBuilderAccess.RunAndSave,
                  configuration.OutputDirectory
                  ),
              configuration
              ));
 }
		internal static Dictionary<RuntimeTypeHandle, object> InitializeDefaultTable( SerializationContext ownerContext )
		{
			var dictionary = new Dictionary<RuntimeTypeHandle, object>( DefaultTableCapacity );
			dictionary.Add( typeof( MessagePackObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( MessagePackObjectDictionary ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectDictionaryMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( MessagePackExtendedTypeObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( List<MessagePackObject> ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer( ownerContext ) );
#if !UNITY
			dictionary.Add( typeof( Object ).TypeHandle, new MsgPack.Serialization.Polymorphic.PolymorphicSerializerProvider<object>( new MsgPack.Serialization.DefaultSerializers.System_ObjectMessagePackSerializer( ownerContext ) ) );
#else
			dictionary.Add( typeof( Object ).TypeHandle, new MsgPack.Serialization.Polymorphic.PolymorphicSerializerProvider<object>( ownerContext, new MsgPack.Serialization.DefaultSerializers.System_ObjectMessagePackSerializer( ownerContext ) ) );
#endif // !UNITY
			dictionary.Add( typeof( String ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_StringMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( StringBuilder ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Text_StringBuilderMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( Char[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_CharArrayMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( Byte[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteArrayMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( DateTime ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, false ) );
			dictionary.Add( typeof( DateTimeOffset ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext ) );
#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMIOS && !XAMDROID && !UNITY
			dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, false ) );
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMIOS && !XAMDROID && !UNITY
			// DateTime and FILETIME must have nullable providers.
			dictionary.Add( typeof( DateTime? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, true ) );
#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMIOS && !XAMDROID && !UNITY
			dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, true ) );
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMIOS && !XAMDROID && !UNITY
#if UNITY
			dictionary.Add( typeof( System.Collections.Generic.KeyValuePair<,> ).TypeHandle, typeof( System_Collections_Generic_KeyValuePair_2MessagePackSerializer ) );
			dictionary.Add( typeof( System.ArraySegment<> ).TypeHandle, typeof( System_ArraySegment_1MessagePackSerializer ) );
#endif // UNITY
#if !NETFX_CORE
			dictionary.Add( typeof( DBNull ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DBNullMessagePackSerializer( ownerContext ) );
#endif // !NETFX_CORE
			dictionary.Add( typeof( System.Boolean ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_BooleanMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Byte ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Char ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_CharMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Decimal ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DecimalMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Double ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DoubleMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Guid ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_GuidMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Int16 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int16MessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Int32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int32MessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Int64 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int64MessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.SByte ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_SByteMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Single ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_SingleMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.TimeSpan ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_TimeSpanMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.UInt16 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt16MessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.UInt32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt32MessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.UInt64 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt64MessagePackSerializer( ownerContext ) );
#if !SILVERLIGHT && !NETFX_CORE
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Collections.Specialized.BitVector32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Specialized_BitVector32MessagePackSerializer( ownerContext ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !SILVERLIGHT && !NETFX_CORE
#if !WINDOWS_PHONE
#if !NETFX_35 && !UNITY
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Numerics.BigInteger ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_BigIntegerMessagePackSerializer( ownerContext ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NETFX_35 && !UNITY
#endif // !WINDOWS_PHONE
#if !UNITY
			dictionary.Add( typeof( System.ArraySegment<> ).TypeHandle, typeof( System_ArraySegment_1MessagePackSerializer<> ) );
#endif // !UNITY
			dictionary.Add( typeof( System.Globalization.CultureInfo ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Globalization_CultureInfoMessagePackSerializer( ownerContext ) );
			dictionary.Add( typeof( System.Collections.DictionaryEntry ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_DictionaryEntryMessagePackSerializer( ownerContext ) );
#if !SILVERLIGHT && !NETFX_CORE
			dictionary.Add( typeof( System.Collections.Stack ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_StackMessagePackSerializer( ownerContext ) );
#endif // !SILVERLIGHT && !NETFX_CORE
#if !SILVERLIGHT && !NETFX_CORE
			dictionary.Add( typeof( System.Collections.Queue ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_QueueMessagePackSerializer( ownerContext ) );
#endif // !SILVERLIGHT && !NETFX_CORE
#if !UNITY
			dictionary.Add( typeof( System.Collections.Generic.KeyValuePair<,> ).TypeHandle, typeof( System_Collections_Generic_KeyValuePair_2MessagePackSerializer<, > ) );
#endif // !UNITY
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Collections.Generic.Stack<> ).TypeHandle, typeof( System_Collections_Generic_Stack_1MessagePackSerializer<> ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Collections.Generic.Queue<> ).TypeHandle, typeof( System_Collections_Generic_Queue_1MessagePackSerializer<> ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#if !WINDOWS_PHONE
#if !NETFX_35 && !UNITY
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Numerics.Complex ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_ComplexMessagePackSerializer( ownerContext ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NETFX_35 && !UNITY
#endif // !WINDOWS_PHONE
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Uri ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UriMessagePackSerializer( ownerContext ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Version ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_VersionMessagePackSerializer( ownerContext ) );
#if !SILVERLIGHT && !NETFX_CORE
#if !UNITY || MSGPACK_UNITY_FULL
			dictionary.Add( typeof( System.Collections.Specialized.NameValueCollection ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Specialized_NameValueCollectionMessagePackSerializer( ownerContext ) );
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !SILVERLIGHT && !NETFX_CORE
			return dictionary;
		}
        public LazyDelegatingMessagePackSerializer(SerializationContext context)
            : base((context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
#endif
        {
            this._context = context;
        }
        /// <summary>
        ///		Initializes a new instance of the <see cref="LazyDelegatingMessagePackSerializer&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="context">
        ///		The serialization context to support lazy retrieval.
        ///	</param>
#if UNITY_IOS
        public LazyDelegatingMessagePackSerializer(Type type, SerializationContext context)
            : base(type, (context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
        public void ProtoBufPriceDto()
        {
            var aggregate = new SpotPriceDto
            {
                ask = 123.13212,
                bid = 122.12323,
                creationTimestamp = DateTime.Now.ToFileTimeUtc(),
                mid       = 103.12132,
                symbol    = "EURUSD",
                valueDate = DateTime.Today.ToString("yyyyMMdd")
            };

            var aggregate2 = new SpotPriceDto2
            {
                ask = 123.13212,
                bid = 122.12323,
                creationTimestamp = DateTime.Now.ToFileTimeUtc(),
                mid       = 103.12132,
                symbol    = "EURUSD",
                valueDate = DateTime.Today
            };

            Console.WriteLine(aggregate2.creationTimestamp.ToString());

            File.WriteAllText(@"c:\temp\example.proto", Serializer.GetProto <SpotPriceDto>());


            Console.WriteLine();
            Console.WriteLine("Serializers");
            Console.WriteLine("===========");
            Console.WriteLine();

            using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(aggregate2))))
            {
                mem.Position = 0;
                var payload = new byte[mem.Length];
                mem.Read(payload, 0, (int)mem.Length);

                var spotPrice = JsonConvert.DeserializeObject <SpotPriceDto2>(Encoding.UTF8.GetString(payload));
                Console.WriteLine("JSON/UTF8 Length Normal\t\t\t{0} bytes", mem.Length);
                Assert.Equal(aggregate.ask, spotPrice.ask);
            }


            using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(aggregate))))
            {
                mem.Position = 0;
                var payload = new byte[mem.Length];
                mem.Read(payload, 0, (int)mem.Length);

                var spotPrice = JsonConvert.DeserializeObject <SpotPriceDto>(Encoding.UTF8.GetString(payload));
                Console.WriteLine("JSON/UTF8 Length Reduced Names\t\t{0} bytes", mem.Length);
                Assert.Equal(aggregate.ask, spotPrice.ask);
            }


            using (var mem = new FileStream(@"c:\temp\spot.proto", FileMode.Create))
            {
                Serializer.Serialize(mem, aggregate);
                mem.Position = 0;

                var spotPrice = Serializer.Deserialize <SpotPriceDto>(mem);
                Console.WriteLine("ProtoBuf Length\t\t\t\t{0} bytes", mem.Length);
                Assert.Equal(aggregate.ask, spotPrice.ask);
            }

            var s = SpotPriceSerializer.Serialize(aggregate);

            Console.WriteLine("Custom Length\t\t\t\t{0} bytes", s.Length);

            using (var mem = new MemoryStream())
            {
                var mp = MessagePackSerializer.Get <SpotPriceDto>();
                mp.Pack(mem, aggregate);

                mem.Position = 0;

                Console.WriteLine("MsgPack Length\t\t\t\t{0} bytes", mem.Length);

                var spotPrice = mp.Unpack(mem);

                Assert.Equal(aggregate.ask, spotPrice.ask);
            }

            using (var mem = new FileStream(@"c:\temp\spot.mp", FileMode.Create))
            {
                var context = new SerializationContext
                {
                    SerializationMethod     = SerializationMethod.Map,
                    EnumSerializationMethod = EnumSerializationMethod.ByName
                };

                var mp = context.GetSerializer <SpotPriceDto>();

                mp.Pack(mem, aggregate);

                mem.Position = 0;

                Console.WriteLine("MsgPack Length Normal Name\t\t{0} bytes", mem.Length);

                var spotPrice = mp.Unpack(mem);

                Assert.Equal(aggregate.ask, spotPrice.ask);
            }

            Console.WriteLine();
            Console.WriteLine();
        }
			public void DoTest( string testAssemblyFile, int packerCompatiblityOptions, byte[] bytesValue, byte[] expectedPackedValue, int expectedSerializerTypeCounts, TestType testType )
			{
				var assembly = Assembly.LoadFrom( testAssemblyFile );
				var types = assembly.GetTypes().Where( t => typeof( IMessagePackSerializer ).IsAssignableFrom( t ) ).ToList();
				Assert.That( types.Count, Is.EqualTo( expectedSerializerTypeCounts ), String.Join( ", ", types.Select( t => t.ToString() ).ToArray() ) );

				var context = new SerializationContext( ( PackerCompatibilityOptions )packerCompatiblityOptions );

				byte[] binary;
				switch ( testType )
				{
					case TestType.GeneratorTestObject:
					{
						var serializer = Activator.CreateInstance( types.Single( t => typeof( MessagePackSerializer<GeneratorTestObject> ).IsAssignableFrom( t ) ), context ) as MessagePackSerializer<GeneratorTestObject>;
						binary = serializer.PackSingleObject( new GeneratorTestObject() { Val = bytesValue } );
						break;
					}
					case TestType.RootGeneratorTestObject:
					{
						var serializer = Activator.CreateInstance( types.Single( t => typeof( MessagePackSerializer<RootGeneratorTestObject> ).IsAssignableFrom( t ) ), context ) as MessagePackSerializer<RootGeneratorTestObject>;
						binary = serializer.PackSingleObject( new RootGeneratorTestObject() { Val = null, Child = new GeneratorTestObject() { Val = bytesValue } } );
						break;
					}
					default:
					{
						var serializer = Activator.CreateInstance( types.Single( t => typeof( MessagePackSerializer<AnotherGeneratorTestObject> ).IsAssignableFrom( t ) ), context ) as MessagePackSerializer<AnotherGeneratorTestObject>;
						binary = serializer.PackSingleObject( new AnotherGeneratorTestObject() { Val = bytesValue } );
						break;
					}
				}
				Assert.That(
					binary,
					Is.EqualTo( expectedPackedValue ),
					"{0} != {1}",
					Binary.ToHexString( binary ),
					Binary.ToHexString( expectedPackedValue ) );
			}
Beispiel #60
0
        public void TestDefaultCollectionTypes_Register_Incompatible_Fail()
        {
            var context = new SerializationContext();

            Assert.Throws <ArgumentException>(() => context.DefaultCollectionTypes.Register(typeof(IList <>), typeof(ArrayList)));
        }