示例#1
0
        private void ParseIProtoResponse(int code, MessagePackObject value)
        {
            switch (code)
            {
            case (int)Key.CODE:
                Code = value.AsInt32();
                break;

            case (int)Key.SYNC:
                Sync = value.AsInt32();
                break;

            case (int)Key.SCHEMA_ID:
                SchemaId = value.AsInt32();
                break;

            case (int)Key.DATA:
                Body = value.AsList().Select(i => new Tuple(i.AsList().Select(a => a.ToObject()).ToList())).ToList();
                break;

            case (int)Key.ERROR:
                Error   = value.AsString();
                IsError = true;
                break;
            }
        }
        public void TestAsString1_EncodingIsUtf32_SpecifyUtf32_Success()
        {
            var target = new MessagePackObject(Encoding.UTF32.GetBytes(_japanese));
            var result = target.AsString(Encoding.UTF32);

            Assert.AreEqual(_japanese, result);
        }
        public void TestAsString1_EncodingIsNotUtf32_SpecifyUtf32_Fail()
        {
#if MONO
            Assert.Inconclusive("UTF32Encoding does not throw exception on Mono FCL.");
#endif
            var target = new MessagePackObject(new byte[] { 0xFF });
            Assert.Throws <InvalidOperationException>(() => target.AsString(new UTF32Encoding(bigEndian: false, byteOrderMark: false, throwOnInvalidCharacters: true)));
        }
示例#4
0
        public static bool MsgUnPackTable(out LuaTable luatable, ref MessagePackObject pObj)
        {
            LuaTable result = new LuaTable();

            luatable = result;
            var    mPk      = pObj.AsDictionary();
            bool   isString = false;
            string key;
            object value;

            foreach (var item in mPk)
            {
                //parse for key
                MessagePackObject mKey = item.Key;
                if (mKey.IsRaw)
                {
                    key      = mKey.AsString();
                    isString = true;
                }
                else if (true == mKey.IsTypeOf <double>())
                {
                    key = mKey.AsDouble().ToString();
                }
                else
                {
                    LoggerHelper.Error("key type error");
                    return(false);
                }
                //parse for value
                MessagePackObject mValue = item.Value;
                if (mValue.IsRaw)
                {
                    value = mValue.AsString();
                }
                else if (mValue.IsDictionary)
                {
                    LuaTable luatbl;
                    MsgUnPackTable(out luatbl, ref mValue);
                    value = luatbl;
                }
                else if (true == mValue.IsTypeOf <bool>())
                {
                    value = mValue.AsBoolean();
                }
                else if (true == mValue.IsTypeOf <double>())
                {
                    value = mValue.AsDouble();
                }
                else
                {
                    LoggerHelper.Error("value type error");
                    return(false);
                }
                result.Add(key, isString, value);
                isString = false;
            }
            return(true);
        }
示例#5
0
        public static bool MsgUnPackTable(out LuaTable luatable, ref MessagePackObject pObj)
        {
            LuaTable table = new LuaTable();

            luatable = table;
            MessagePackObjectDictionary dictionary = pObj.AsDictionary();
            bool isString = false;

            foreach (KeyValuePair <MessagePackObject, MessagePackObject> pair in dictionary)
            {
                string            str;
                object            obj2;
                MessagePackObject key = pair.Key;
                if (key.IsRaw)
                {
                    str      = key.AsString();
                    isString = true;
                }
                else if (key.IsTypeOf <double>() == true)
                {
                    str = key.AsDouble().ToString();
                }
                else
                {
                    LoggerHelper.Error("key type error", true);
                    return(false);
                }
                MessagePackObject obj4 = pair.Value;
                if (obj4.IsRaw)
                {
                    obj2 = obj4.AsString();
                }
                else if (obj4.IsDictionary)
                {
                    LuaTable table2;
                    MsgUnPackTable(out table2, ref obj4);
                    obj2 = table2;
                }
                else if (obj4.IsTypeOf <bool>() == true)
                {
                    obj2 = obj4.AsBoolean();
                }
                else if (obj4.IsTypeOf <double>() == true)
                {
                    obj2 = obj4.AsDouble();
                }
                else
                {
                    LoggerHelper.Error("value type error", true);
                    return(false);
                }
                table.Add(str, isString, obj2);
                isString = false;
            }
            return(true);
        }
示例#6
0
        private static void TestString(String val, Encoding encoding)
        {
            var output = new MemoryStream();

            Packer.Create(output).PackString(val, encoding);
            MessagePackObject obj = UnpackOne(output);

            Assert.AreEqual(val, obj.AsString(encoding));
            Assert.IsTrue(obj.IsTypeOf <string>().GetValueOrDefault());
        }
示例#7
0
 /// <summary>
 ///		Invokes <see cref="MessagePackObject.AsString()"/> in deserializaton manner.
 /// </summary>
 /// <param name="source"><see cref="MessagePackObject"/>.</param>
 /// <returns>A deserialized value.</returns>
 /// <exception cref="SerializationException"><paramref name="source"/> is not expected type.</exception>
 public static string DeserializeAsString(this MessagePackObject source)
 {
     try
     {
         return(source.AsString());
     }
     catch (InvalidOperationException ex)
     {
         throw new SerializationException(String.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message), ex);
     }
 }
示例#8
0
        private static JToken CreateToken(MessagePackObject curObj)
        {
            if (curObj.IsDictionary)
            {
                JObject resultObj = new JObject();

                Dictionary <string, MessagePackObject> curDict = curObj.AsDictionary("inputFile");

                foreach (KeyValuePair <string, MessagePackObject> curProp in curDict)
                {
                    resultObj[curProp.Key] = CreateToken(curProp.Value);
                }

                return(resultObj);
            }
            else if (curObj.IsArray)
            {
                JArray resultArray = new JArray();

                IList <MessagePackObject> curArray = curObj.AsList();

                foreach (MessagePackObject curElem in curArray)
                {
                    resultArray.Add(CreateToken(curElem));
                }

                return(resultArray);
            }
            else if (curObj.IsNil)
            {
                return(null);
            }
            else if (curObj.IsTypeOf <Int64>().HasValue&& curObj.IsTypeOf <Int64>().Value)
            {
                return(curObj.AsInt64());
            }
            else if (curObj.IsTypeOf <double>().HasValue&& curObj.IsTypeOf <double>().Value)
            {
                return(curObj.AsDouble());
            }
            else if (curObj.IsTypeOf <string>().HasValue&& curObj.IsTypeOf <string>().Value)
            {
                return(curObj.AsString());
            }
            else if (curObj.IsTypeOf <bool>().HasValue&& curObj.IsTypeOf <bool>().Value)
            {
                return(curObj.AsBoolean());
            }
            else
            {
                throw new Exception("Unknown Type!");
            }
        }
示例#9
0
            protected void ReadPrimitive()

            {
                MessagePackObject lastReadData = mUnpacker.LastReadData;

                if (lastReadData.IsNil)

                {
                    mReader.SetToken(JsonToken.Null, null);
                }
                else if (lastReadData.UnderlyingType == typeof(byte[]))

                {
                    mReader.SetToken(JsonToken.Bytes, lastReadData.AsBinary());
                }
                else if (lastReadData.UnderlyingType == typeof(bool))

                {
                    mReader.SetToken(JsonToken.Boolean, lastReadData.AsBoolean());
                }
                else if (lastReadData.UnderlyingType == typeof(string))

                {
                    mReader.SetToken(JsonToken.String, lastReadData.AsString());
                }
                else if (lastReadData.UnderlyingType == typeof(double) ||

                         lastReadData.UnderlyingType == typeof(float))

                {
                    mReader.SetToken(JsonToken.Float, lastReadData.ToObject());
                }
                else if (lastReadData.IsTypeOf <sbyte>() == true ||

                         lastReadData.IsTypeOf <short>() == true ||

                         lastReadData.IsTypeOf <ushort>() == true ||

                         lastReadData.IsTypeOf <int>() == true ||

                         lastReadData.IsTypeOf <uint>() == true ||

                         lastReadData.IsTypeOf <long>() == true ||

                         lastReadData.IsTypeOf <ulong>() == true)

                {
                    mReader.SetToken(JsonToken.Integer, lastReadData.ToObject());
                }
            }
示例#10
0
        private static object MapEnum(Type targetType, MessagePackObject source)
        {
            if (source.IsTypeOf <int>() ?? false)
            {
                return(source.AsInt32());
            }
            if (source.IsTypeOf <string>() ?? false)
            {
                var strVal = source.AsString();
                return(Enum.Parse(targetType, strVal, true));
            }

            throw new MessagePackMapperException($"Cannot map value to enum {targetType.FullName}.");
        }
        public static string DeserializeAsString(this MessagePackObject source)
        {
            string str;

            try
            {
                str = source.AsString();
            }
            catch (InvalidOperationException exception)
            {
                throw new SerializationException(string.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", new object[] { exception.Message }), exception);
            }
            return(str);
        }
示例#12
0
        private object GetObject(MessagePackObject str)
        {
            if (str.UnderlyingType == typeof(byte[]))
            {
                return(System.Text.Encoding.ASCII.GetString(str.AsBinary()));
            }
            else if (str.UnderlyingType == typeof(string))
            {
                return(str.AsString());
            }
            else if (str.UnderlyingType == typeof(byte))
            {
                return(str.AsByte());
            }
            else if (str.UnderlyingType == typeof(bool))
            {
                return(str.AsBoolean());
            }

            return(str);
        }
		public void TestAsString1_EncodingMissmatchAndReturnsNull_Null()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			Assert.Throws<InvalidOperationException>( () => target.AsString( new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false ) ) );
		}
		public void TestAsString1_EncodingIsNull()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			Assert.Throws<ArgumentNullException>( () => target.AsString( null ) );
		}
		public void TestAsString_Null_Success()
		{
			var target = new MessagePackObject( default( string ) );
			Assert.IsNull( target.AsString() );
		}
		public void TestAsString_IsNotString()
		{
			var target = new MessagePackObject( 0 );
			Assert.Throws<InvalidOperationException>( () => target.AsString() );
		}
示例#17
0
		/// <summary>
		///		Unpacks <see cref="RpcErrorMessage"/> from stream in the specified context.
		/// </summary>
		/// <param name="context"><see cref="ClientResponseContext"/> which stores serialized error.</param>
		/// <returns>An unpacked <see cref="RpcErrorMessage"/>.</returns>
		internal static RpcErrorMessage UnpackError( ClientResponseContext context )
		{
			Contract.Assert( context != null );
			Contract.Assert( context.ErrorBuffer != null );
			Contract.Assert( context.ErrorBuffer.Length > 0 );
			Contract.Assert( context.ResultBuffer != null );
			Contract.Assert( context.ResultBuffer.Length > 0 );

			MessagePackObject error;
			try
			{
				error = Unpacking.UnpackObject( context.ErrorBuffer );
			}
			catch ( UnpackException )
			{
				error = new MessagePackObject( context.ErrorBuffer.GetBuffer().SelectMany( segment => segment.AsEnumerable() ).ToArray() );
			}

			if ( error.IsNil )
			{
				return RpcErrorMessage.Success;
			}

			bool isUnknown = false;
			RpcError errorIdentifier;
			if ( error.IsTypeOf<string>().GetValueOrDefault() )
			{
				var asString = error.AsString();
				errorIdentifier = RpcError.FromIdentifier( asString, null );
				// Check if the error is truely Unexpected error.
				isUnknown = errorIdentifier.ErrorCode == RpcError.Unexpected.ErrorCode && asString != RpcError.Unexpected.Identifier;
			}
			else if ( error.IsTypeOf<int>().GetValueOrDefault() )
			{
				errorIdentifier = RpcError.FromIdentifier( null, error.AsInt32() );
			}
			else
			{
				errorIdentifier = RpcError.Unexpected;
				isUnknown = true;
			}

			MessagePackObject detail;
			if ( context.ResultBuffer.Length == 0 )
			{
				detail = MessagePackObject.Nil;
			}
			else
			{
				try
				{
					detail = Unpacking.UnpackObject( context.ResultBuffer );
				}
				catch ( UnpackException )
				{
					detail = new MessagePackObject( context.ResultBuffer.GetBuffer().SelectMany( segment => segment.AsEnumerable() ).ToArray() );
				}
			}

			if ( isUnknown )
			{
				// Unknown error, the error should contain original Error field as message.
				if ( detail.IsNil )
				{
					return new RpcErrorMessage( errorIdentifier, error.AsString(), null );
				}
				else
				{
					var details = new MessagePackObjectDictionary( 2 );
					details[ RpcException.MessageKeyUtf8 ] = error;
					details[ RpcException.DebugInformationKeyUtf8 ] = detail;
					return new RpcErrorMessage( errorIdentifier, new MessagePackObject( details, true ) );
				}
			}
			else
			{
				return new RpcErrorMessage( errorIdentifier, detail );
			}
		}
        public void TestAsString1_EncodingMissmatchAndReturnsNull_Null()
        {
            var target = new MessagePackObject(Encoding.Unicode.GetBytes(_japanese));

            Assert.Throws <InvalidOperationException>(() => target.AsString(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false)));
        }
		public void TestAsString1_EncodingMissmatchAndThrowsDecoderFallbackException()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			var result = target.AsString( new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) );
		}
		public void TestAsString1_EncodingIsNotUtf32_SpecifyUtf32_Fail()
		{
#if MONO
			Assert.Inconclusive( "UTF32Encoding does not throw exception on Mono FCL." );
#endif
			var target = new MessagePackObject( new byte[] { 0xFF } );
			Assert.Throws<InvalidOperationException>( () => target.AsString( new UTF32Encoding( bigEndian: false, byteOrderMark: false, throwOnInvalidCharacters: true ) ) );
		}
        public void TestAsString_EncodingMissmatch()
        {
            var target = new MessagePackObject(Encoding.Unicode.GetBytes(_japanese));

            Assert.Throws <InvalidOperationException>(() => target.AsString());
        }
示例#22
0
        /// <summary>
        ///		Unpacks <see cref="RpcErrorMessage"/> from stream in the specified context.
        /// </summary>
        /// <param name="context"><see cref="ClientResponseContext"/> which stores serialized error.</param>
        /// <returns>An unpacked <see cref="RpcErrorMessage"/>.</returns>
        internal static RpcErrorMessage UnpackError(ClientResponseContext context)
        {
            Contract.Assert(context != null);
            Contract.Assert(context.ErrorBuffer != null);
            Contract.Assert(context.ErrorBuffer.Length > 0);
            Contract.Assert(context.ResultBuffer != null);
            Contract.Assert(context.ResultBuffer.Length > 0);

            MessagePackObject error;

            try
            {
                error = Unpacking.UnpackObject(context.ErrorBuffer);
            }
            catch (UnpackException)
            {
                error = new MessagePackObject(context.ErrorBuffer.GetBuffer().SelectMany(segment => segment.AsEnumerable()).ToArray());
            }

            if (error.IsNil)
            {
                return(RpcErrorMessage.Success);
            }

            bool     isUnknown = false;
            RpcError errorIdentifier;

            if (error.IsTypeOf <string>().GetValueOrDefault())
            {
                var asString = error.AsString();
                errorIdentifier = RpcError.FromIdentifier(asString, null);
                // Check if the error is truely Unexpected error.
                isUnknown = errorIdentifier.ErrorCode == RpcError.Unexpected.ErrorCode && asString != RpcError.Unexpected.Identifier;
            }
            else if (error.IsTypeOf <int>().GetValueOrDefault())
            {
                errorIdentifier = RpcError.FromIdentifier(null, error.AsInt32());
            }
            else
            {
                errorIdentifier = RpcError.Unexpected;
                isUnknown       = true;
            }

            MessagePackObject detail;

            if (context.ResultBuffer.Length == 0)
            {
                detail = MessagePackObject.Nil;
            }
            else
            {
                try
                {
                    detail = Unpacking.UnpackObject(context.ResultBuffer);
                }
                catch (UnpackException)
                {
                    detail = new MessagePackObject(context.ResultBuffer.GetBuffer().SelectMany(segment => segment.AsEnumerable()).ToArray());
                }
            }

            if (isUnknown)
            {
                // Unknown error, the error should contain original Error field as message.
                if (detail.IsNil)
                {
                    return(new RpcErrorMessage(errorIdentifier, error.AsString(), null));
                }
                else
                {
                    var details = new MessagePackObjectDictionary(2);
                    details[RpcException.MessageKeyUtf8]          = error;
                    details[RpcException.DebugInformationKeyUtf8] = detail;
                    return(new RpcErrorMessage(errorIdentifier, new MessagePackObject(details, true)));
                }
            }
            else
            {
                return(new RpcErrorMessage(errorIdentifier, detail));
            }
        }
        public void TestAsString_Null_Success()
        {
            var target = new MessagePackObject(default(string));

            Assert.IsNull(target.AsString());
        }
        public void TestAsString_IsNotString()
        {
            var target = new MessagePackObject(0);

            Assert.Throws <InvalidOperationException>(() => target.AsString());
        }
        public void TestAsString1_EncodingIsUtf32_SpecifyNotUtf32_Fail()
        {
            var target = new MessagePackObject(Encoding.UTF32.GetBytes(_japanese));

            Assert.Throws <InvalidOperationException>(() => target.AsString(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)));
        }
		public void TestAsString1_EncodingIsUtf32_SpecifyUtf32_Success()
		{
			var target = new MessagePackObject( Encoding.UTF32.GetBytes( _japanese ) );
			var result = target.AsString( Encoding.UTF32 );
			Assert.AreEqual( _japanese, result );
		}
		public void TestAsString1_EncodingIsNull()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			var result = target.AsString( null );
		}
		public void TestAsString1_EncodingIsUtf32_SpecifyNotUtf32_Fail()
		{
			var target = new MessagePackObject( Encoding.UTF32.GetBytes( _japanese ) );
			Assert.Throws<InvalidOperationException>( () => target.AsString( new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) ) );
		}
		public void TestAsString1_EncodingIsUtf32_SpecifyNotUtf32_Fail()
		{
			var target = new MessagePackObject( Encoding.UTF32.GetBytes( _japanese ) );
			var result = target.AsString( new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) );
		}
示例#30
0
        public static object Map(Type targetType, MessagePackObject source, PropertyInfo property = null)
        {
            if (source.IsNil)
            {
                return(null);
            }
            if (targetType == typeof(string))
            {
                return(source.AsString());
            }
            if (targetType == typeof(int) || targetType == typeof(int?))
            {
                return(source.AsInt32());
            }
            if (targetType == typeof(uint) || targetType == typeof(uint?))
            {
                return(source.AsUInt32());
            }
            if (targetType == typeof(long) || targetType == typeof(long?))
            {
                return(source.AsInt64());
            }
            if (targetType == typeof(ulong) || targetType == typeof(ulong?))
            {
                return(source.AsUInt64());
            }
            if (targetType == typeof(float) || targetType == typeof(float?))
            {
                return(source.AsSingle());
            }
            if (targetType == typeof(double) || targetType == typeof(double?))
            {
                return(source.AsDouble());
            }
            if (targetType == typeof(bool) || targetType == typeof(bool?))
            {
                return(source.AsBoolean());
            }
            if (targetType == typeof(byte[]))
            {
                return(source.AsBinary());
            }
            if (targetType == typeof(byte) || targetType == typeof(byte?))
            {
                return(source.AsByte());
            }
            if (targetType == typeof(sbyte) || targetType == typeof(sbyte?))
            {
                return(source.AsSByte());
            }
            if (targetType == typeof(char[]))
            {
                return(source.AsCharArray());
            }
            if (targetType == typeof(short) || targetType == typeof(short?))
            {
                return(source.AsInt16());
            }
            if (targetType == typeof(ushort) || targetType == typeof(ushort?))
            {
                return(source.AsUInt16());
            }
            if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
            {
                return(MapDateTime(property, source));
            }
            if (targetType == typeof(IList <MessagePackObject>))
            {
                return(source.AsList());
            }
            if (targetType == typeof(IEnumerable <MessagePackObject>))
            {
                return(source.AsEnumerable());
            }

            var ti = targetType.GetTypeInfo();

            if (targetType == typeof(MessagePackObject))
            {
                return(source);
            }

            if (ti.IsGenericType && (targetType.GetGenericTypeDefinition() == typeof(List <>) ||
                                     targetType.GetGenericTypeDefinition() == typeof(IList <>)))
            {
                return(MapList(targetType, source.AsList()));
            }

            if (ti.IsClass && source.IsList)
            {
                return(MapClass(targetType, source));
            }

            if (ti.IsClass && source.IsMap)
            {
                return(MapDictionary(targetType, source.AsDictionary()));
            }

            if (ti.IsEnum)
            {
                return(MapEnum(targetType, source));
            }

            throw new MessagePackMapperException(
                      $"Cannot find MsgPackObject converter for type {targetType.FullName}.");
        }
		public void TestAsString_EncodingMissmatch()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			Assert.Throws<InvalidOperationException>( () => target.AsString() );
		}
		public void TestAsString1_IsNotString()
		{
			var target = new MessagePackObject( 0 );
			target.AsString( Encoding.UTF32 );
		}
        public void TestAsString1_EncodingIsNull()
        {
            var target = new MessagePackObject(Encoding.Unicode.GetBytes(_japanese));

            Assert.Throws <ArgumentNullException>(() => target.AsString(null));
        }
		//this is a ridiculous method
		Dictionary<string, object> TypifyDictionary(MessagePackObjectDictionary dict)
		{
			Dictionary<string, object> returnDictionary = new Dictionary<string, object>();
			
			foreach (var pair in dict)
			{
				MessagePackObject obj = (MessagePackObject)pair.Value;
				string key = System.Text.Encoding.ASCII.GetString ((byte[])pair.Key);

				if (obj.UnderlyingType == null)
					continue;
				
				if (obj.IsRaw) {
					if (obj.UnderlyingType == typeof(string)) {
						if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value)
							returnDictionary [key] = obj.AsString ();
						else
							returnDictionary [pair.Key.ToString ()] = obj.AsString ();
					}
					else if (obj.IsTypeOf (typeof(int)).Value)
						returnDictionary [pair.Key.ToString ()] = (int)obj.ToObject ();
					else if (obj.IsTypeOf (typeof(Byte[])).Value) {
						if (key == "payload") 
							returnDictionary [key] = (byte[])obj;
						else 
							returnDictionary [key] = System.Text.Encoding.ASCII.GetString ((Byte[])obj.ToObject ());
					} else
						throw new Exception ("I don't know type: " + pair.Value.GetType ().Name);
				} else if (obj.IsArray) {
					List<object> arr = new List<object> ();
					foreach (var o in obj.ToObject() as MessagePackObject[]) {
						if (o.IsDictionary)
							arr.Add (TypifyDictionary (o.AsDictionary ()));
						else if (o.IsRaw)
							arr.Add (System.Text.Encoding.ASCII.GetString ((byte[])o));
						else if (o.IsArray) {
							var enu = o.AsEnumerable ();
							List<object> array = new List<object> ();
							foreach (var blah in enu)
								array.Add (blah as object);

							arr.Add (array.ToArray ());
						} else if (o.ToObject ().GetType () == typeof(Byte)) //this is a hack because I don't know what type you are...
							arr.Add (o.ToString ());
					}

					if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value)
						returnDictionary.Add (key, arr);
					else
						returnDictionary.Add (key, arr);
				} else if (obj.IsDictionary) {
					if (pair.Key.IsRaw && pair.Key.IsTypeOf(typeof(Byte[])).Value)
						returnDictionary [key] = TypifyDictionary (obj.AsDictionary ());
					else 
						returnDictionary [pair.Key.ToString ()] = TypifyDictionary (obj.AsDictionary ());
				} else if (obj.IsTypeOf (typeof(UInt16)).Value) {
					if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value)
						returnDictionary [key] = obj.AsUInt16 ();
					else
						returnDictionary [pair.Key.ToString ()] = obj.AsUInt16 ();
				} else if (obj.IsTypeOf (typeof(UInt32)).Value) {
					if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value)
						returnDictionary [key] = obj.AsUInt32 ();
					else
						returnDictionary [pair.Key.ToString ()] = obj.AsUInt32 ();
				} else if (obj.IsTypeOf (typeof(bool)).Value) {
					if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value)
						returnDictionary [key] = obj.AsBoolean ();
					else
						returnDictionary [pair.Key.ToString ()] = obj.AsBoolean ();
				}
				else 
					throw new Exception("Don't know type: " + obj.ToObject().GetType().Name);
			}
			
			return returnDictionary;
		}
		public void TestAsString_EncodingMissmatch()
		{
			var target = new MessagePackObject( Encoding.Unicode.GetBytes( _japanese ) );
			var result = target.AsString();
		}
		public void TestAsString_IsNotString()
		{
			var target = new MessagePackObject( 0 );
			target.AsString();
		}
示例#37
0
        /// <summary>
        ///		Create <see cref="RpcException"/> or dervied instance which corresponds to sepcified error information.
        /// </summary>
        /// <param name="error">Basic error information. This information will propagate to client.</param>
        /// <param name="errorDetail">Detailed error information, which is usally debugging purpose only, so will not propagate to client.</param>
        /// <returns>
        ///		<see cref="RpcException"/> or dervied instance which corresponds to sepcified error information.
        /// </returns>
        /// <exception cref="ArgumentException">
        ///		<paramref name="error"/> is <see cref="MessagePackObject.IsNil">nil</see>.
        /// </exception>
        public static RpcException FromMessage( MessagePackObject error, MessagePackObject errorDetail )
        {
            // TODO: Application specific customization
            // TODO: Application specific exception class

            if ( error.IsNil )
            {
                throw new ArgumentException( "'error' must not be nil.", "error" );
            }

            // Recommeded path
            if ( error.IsTypeOf<byte[]>().GetValueOrDefault() )
            {
                string identifier = null;
                try
                {
                    identifier = error.AsString();
                }
                catch ( InvalidOperationException ) { }

                int? errorCode = null;

                if ( errorDetail.IsTypeOf<IDictionary<MessagePackObject, MessagePackObject>>().GetValueOrDefault() )
                {
                    var asDictionary = errorDetail.AsDictionary();
                    MessagePackObject value;
                    if ( asDictionary.TryGetValue( _errorCodeKeyUtf8, out value ) && value.IsTypeOf<int>().GetValueOrDefault() )
                    {
                        errorCode = value.AsInt32();
                    }
                }

                if ( identifier != null || errorCode != null )
                {
                    RpcError rpcError = RpcError.FromIdentifier( identifier, errorCode );
                    return rpcError.ToException( errorDetail );
                }
            }

            // Other path.
            return new UnexpcetedRpcException( error, errorDetail );
        }