Example #1
0
 private static object ProcessUuid(MessagePackObjectDictionary dic, string value)
 {
     if (!dic.TryGetValue(value, out var uuid))
     {
         return(string.Empty);
     }
     return(uuid.ToObject());
 }
 void onRecv_FakeRemote(MessagePackObjectDictionary dict)
 {
     if (dict.TryGetValue("msg", out MessagePackObject msg))
     {
         var msgdict = msg.AsDictionary();
         var cmd     = (CmdList)msgdict["cmd"].AsUInt16();
         this.OnReceiveMsgFromRemote(null, cmd, msgdict);//null应该修改为自己到自己的pipeline,不然在处理消息过程用到from的时候,可能报错。
     }
 }
        public MessagePackObject makeCmd_SendMsg(string targetEndpoint, MessagePackObject msg)
        {
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]    = (UInt16)CmdList.Request_SendMsg;
            dict["msg"]    = msg;
            dict["target"] = targetEndpoint;
            return(new MessagePackObject(dict));
        }
        void OnRecv_Request_ConnectTo(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var endpointstr = dict["endpoint"].AsString();

            if (IPEndPoint.TryParse(endpointstr, out IPEndPoint endpoint))
            {
                this.ConnectOne(endpoint);
            }
        }
        void Tell_Response_Iamhere(IModulePipeline remote, string provedpubep)
        {
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]         = (UInt16)CmdList.Response_Iamhere;
            dict["provedpubep"] = provedpubep;
            dict["isProved"]    = this.isProved;
            remote.Tell(new MessagePackObject(dict));
        }
        void Tell_BoardCast_Tx(IModulePipeline remote, byte[] message, byte[] signData)
        {
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]      = (UInt16)CmdList.BoardCast_Tx;
            dict["message"]  = message;
            dict["signData"] = signData;
            remote.Tell(new MessagePackObject(dict));
        }
Example #7
0
    private static MessagePackObjectDictionary WriteCamera(Transform cameraPivot)
    {
        var camera = new MessagePackObjectDictionary();

        camera[FileKeys.CAMERA_PAN]    = WriteVector3(cameraPivot.position);
        camera[FileKeys.CAMERA_ROTATE] = WriteQuaternion(cameraPivot.rotation);
        camera[FileKeys.CAMERA_SCALE]  = cameraPivot.localScale.z;
        return(camera);
    }
Example #8
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);
        }
Example #9
0
        /// <summary>
        ///		Get <see cref="MessagePackObject"/> which contains data about this instance.
        /// </summary>
        /// <param name="isDebugMode">
        ///		If this method should include debug information then true.
        /// </param>
        /// <returns>
        ///		<see cref="MessagePackObject"/> which contains data about this instance.
        /// </returns>
        public MessagePackObject GetExceptionMessage(bool isDebugMode)
        {
            var store = new MessagePackObjectDictionary(2);

            store.Add(_errorCodeUtf8, this.RpcError.ErrorCode);
            store.Add(MessageKeyUtf8, isDebugMode ? this.Message : this.RpcError.DefaultMessageInvariant);
            this.GetExceptionMessage(store, isDebugMode);

            return(new MessagePackObject(store));
        }
        void Tell_SendRaw(IModulePipeline remote, byte[] message, byte[] signData)
        {
            logger.Info($"------Tell_SendRaw  To:{remote.ToString()}-------");
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]      = (UInt16)CmdList.Post_SendRaw;
            dict["message"]  = message;
            dict["signData"] = signData;
            remote.Tell(new MessagePackObject(dict));
        }
        //private IModulePipeline observer;
        //void OnRecv_IamObserver(IModulePipeline from, MessagePackObjectDictionary dict)
        //{
        //    observer = from;
        //}

        void OnRecv_Response_plevel(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var id     = from.system.PeerID;
            var plevel = dict["plevel"].AsInt32();

            if (this.linkNodes.TryGetValue(id, out LinkObj obj))
            {
                logger.Info(" plevel:" + plevel + "from:" + obj.publicEndPoint);
            }
        }
        void OnRecv_SendMsg(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var msg         = dict["msg"];
            var endpointStr = dict["target"].AsString();

            if (this.linkIDs.TryGetValue(endpointStr, out ulong peer))
            {
                this.linkNodes[peer].remoteNode.Tell(msg);
            }
        }
        void Tell_Request_ProvePeer(IModulePipeline remote, byte[] addinfo, byte[] signdata)
        {
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]      = (UInt16)CmdList.Request_ProvePeer;
            dict["pubkey"]   = this.pubkey;
            dict["addinfo"]  = addinfo;
            dict["signdata"] = signdata;
            remote.Tell(new MessagePackObject(dict));
        }
        void OnRecv_Response_Iamhere(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var link = this.linkNodes[from.system.PeerID];

            link.provedPubep = dict["provedpubep"].AsString();
            link.isProved    = dict["isProved"].AsBoolean();
            if (!ContainsRemote(link.publicEndPoint))
            {
                this.provedNodes[from.system.PeerID] = link;
            }
        }
Example #15
0
        public HANDSHAKE()
            : base(0x0000)
        {
            var payload = new MessagePackObjectDictionary {
                { "major", (byte)Protocol.MAJOR },
                { "minor", (byte)Protocol.MINOR },
                { "patch", (byte)Protocol.PATCH }
            };

            Serialize(payload);
        }
        void Tell_ReqJoinPeer(IModulePipeline remote)
        {
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]   = (UInt16)CmdList.Request_JoinPeer;
            dict["id"]    = this.guid.data;
            dict["pubep"] = this.config.PublicEndPoint.ToString();
            //Console.WriteLine("Tell_ReqJoinPeer----->:"+ dict["pubep"]);
            dict["chaininfo"] = chainHash.data;
            remote.Tell(new MessagePackObject(dict));
        }
        void Tell_Request_PeerList(IModulePipeline remote)
        {
            if (!this.beEnableQueryPeers)
            {
                return;
            }
            var dict = new MessagePackObjectDictionary();

            dict["cmd"] = (UInt16)CmdList.Request_PeerList;
            remote.Tell(new MessagePackObject(dict));
        }
 private void ReadObjectEntity(MessagePackObjectDictionary entityDict, ObjectEntity objectEntity)
 {
     ReadEntity(entityDict, objectEntity);
     if (entityDict.ContainsKey(FileKeys.OBJECT_POSITION))
     {
         objectEntity.position = ReadVector3Int(entityDict[FileKeys.OBJECT_POSITION]);
     }
     if (entityDict.ContainsKey(FileKeys.OBJECT_ROTATION))
     {
         objectEntity.rotation = entityDict[FileKeys.OBJECT_ROTATION].AsSingle();
     }
 }
Example #19
0
        /// <summary>
        ///		Get <see cref="MessagePackObject"/> which contains data about this instance.
        /// </summary>
        /// <param name="isDebugMode">
        ///		If this method should include debug information then true.
        /// </param>
        /// <returns>
        ///		<see cref="MessagePackObject"/> which contains data about this instance.
        /// </returns>
        public MessagePackObject GetExceptionMessage(bool isDebugMode)
        {
            var store = new MessagePackObjectDictionary(2)
            {
                { errorCodeUtf8, RpcError.ErrorCode },
                { messageKeyUtf8, isDebugMode ? Message : RpcError.DefaultMessageInvariant }
            };

            GetExceptionMessage(store, isDebugMode);

            return(new MessagePackObject(store));
        }
        void Tell_Post_TouchProvedPeer(IModulePipeline remote, string pubep, string nodeid)
        {
            if (this.beObserver)
            {
                return;
            }
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]    = (UInt16)CmdList.Post_TouchProvedPeer;
            dict["pubep"]  = pubep;
            dict["nodeid"] = nodeid;
            remote.Tell(new MessagePackObject(dict));
        }
        void Tell_ResponseAcceptJoin(IModulePipeline remote)
        {
            var link = this.linkNodes[remote.system.PeerID];

            link.CheckInfo = Guid.NewGuid().ToByteArray();
            var dict = new MessagePackObjectDictionary();

            dict["cmd"]       = (UInt16)CmdList.Response_AcceptJoin;
            dict["checkinfo"] = link.CheckInfo;
            dict["plevel"]    = this.pLevel;//告诉对方我的优先级
            //选个挑战信息
            remote.Tell(new MessagePackObject(dict));
        }
    private void CheckWorldValid(MessagePackObjectDictionary worldDict)
    {
        if (!worldDict.ContainsKey(FileKeys.WORLD_WRITER_VERSION) ||
            !worldDict.ContainsKey(FileKeys.WORLD_MIN_READER_VERSION))
        {
            throw new InvalidMapFileException();
        }

        if (worldDict[FileKeys.WORLD_MIN_READER_VERSION].AsInt32() > VERSION)
        {
            throw new MapReadException("This world file requires a newer version of the app");
        }
    }
 private IEnumerable <IList <MessagePackObject> > IterateProperties(MessagePackObjectDictionary worldDict)
 {
     foreach (var propsDict in IterateWorldPropObjects(worldDict))
     {
         if (propsDict.ContainsKey(FileKeys.PROPOBJ_PROPERTIES))
         {
             foreach (var propObj in propsDict[FileKeys.PROPOBJ_PROPERTIES].AsList())
             {
                 yield return(propObj.AsList());
             }
         }
     }
 }
        void OnRecv_Request_Tx(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var txid = dict["txid"].AsBinary();

            if (txid != null)
            {
                var tx = this.blockChain.GetTx(txid);
                if (tx != null)
                {
                    Tell_Response_Tx(from, tx);
                }
            }
        }
 private Material ReadMaterial(MessagePackObjectDictionary matDict, bool alpha)
 {
     if (matDict.ContainsKey(FileKeys.MATERIAL_NAME))
     {
         string name = matDict[FileKeys.MATERIAL_NAME].AsString();
         foreach (string dirEntry in ResourcesDirectory.dirList)
         {
             if (dirEntry.Length <= 2)
             {
                 continue;
             }
             string newDirEntry   = dirEntry.Substring(2);
             string checkFileName = Path.GetFileNameWithoutExtension(newDirEntry);
             if ((!editor) && checkFileName.StartsWith("$")) // special alternate materials for game
             {
                 checkFileName = checkFileName.Substring(1);
             }
             if (checkFileName == name)
             {
                 return(ResourcesDirectory.GetMaterial(newDirEntry));
             }
         }
         warnings.Add("Unrecognized material: " + name);
         return(ReadWorldFile.missingMaterial);
     }
     else if (matDict.ContainsKey(FileKeys.MATERIAL_MODE))
     {
         ColorMode mode = (ColorMode)System.Enum.Parse(typeof(ColorMode), matDict[FileKeys.MATERIAL_MODE].AsString());
         if (matDict.ContainsKey(FileKeys.MATERIAL_COLOR))
         {
             Color color = ReadColor(matDict[FileKeys.MATERIAL_COLOR]);
             if (matDict.ContainsKey(FileKeys.MATERIAL_ALPHA))
             {
                 alpha = matDict[FileKeys.MATERIAL_ALPHA].AsBoolean();
             }
             Material mat = ResourcesDirectory.MakeCustomMaterial(mode, alpha);
             mat.color = color;
             return(mat);
         }
         else
         {
             return(ResourcesDirectory.MakeCustomMaterial(mode));
         }
     }
     else
     {
         warnings.Add("Error reading material");
         return(ReadWorldFile.missingMaterial);
     }
 }
 void OnRecv_BoardCast_LosePlevel(IModulePipeline from, MessagePackObjectDictionary dict)
 {
     if (this.linkNodes.TryGetValue(from.system.PeerID, out LinkObj obj))
     {
         var beAffected = this.losePlevelFromLinkObj(obj);
         if (!beAffected)
         {
             if (this.pLevel != -1)
             {
                 this.Tell_BoradCast_PeerState(from);
             }
         }
     }
 }
Example #27
0
            public RemoteExceptionInformation(IList <MessagePackObject> unpacked)
            {
                if (unpacked.Count != 6)
                {
                    throw new SerializationException("Count of remote exception information must be 6.");
                }

                this.Hop        = unpacked[0].AsInt32();
                this.TypeName   = unpacked[1].AsString();
                this.HResult    = unpacked[2].AsInt32();
                this.Message    = unpacked[3].AsString();
                this.StackTrace = unpacked[4].AsList().Select(item => new RemoteStackFrame(item.AsList())).ToArray();
                this.Data       = unpacked[5].AsDictionary();
            }
        protected internal override async Task <object> UnpackFromAsyncCore(Unpacker unpacker, CancellationToken cancellationToken)
        {
            if (unpacker.IsArrayHeader)
            {
                var result = new MessagePackObject[UnpackHelpers.GetItemsCount(unpacker)];
                for (int i = 0; i < result.Length; i++)
                {
                    var item = await unpacker.ReadObjectAsync(cancellationToken).ConfigureAwait(false);

                    if (!item.Success)
                    {
                        SerializationExceptions.ThrowUnexpectedEndOfStream(unpacker);
                    }

                    result[i] = item.Value;
                }

                return(new MessagePackObject(result));
            }
            else if (unpacker.IsMapHeader)
            {
                var itemsCount = UnpackHelpers.GetItemsCount(unpacker);
                var result     = new MessagePackObjectDictionary(itemsCount);
                for (int i = 0; i < itemsCount; i++)
                {
                    var key = await unpacker.ReadObjectAsync(cancellationToken).ConfigureAwait(false);

                    if (!key.Success)
                    {
                        SerializationExceptions.ThrowUnexpectedEndOfStream(unpacker);
                    }

                    var value = await unpacker.ReadObjectAsync(cancellationToken).ConfigureAwait(false);

                    if (!value.Success)
                    {
                        SerializationExceptions.ThrowUnexpectedEndOfStream(unpacker);
                    }

                    result.Add(key.Value, value.Value);
                }

                return(new MessagePackObject(result));
            }
            else
            {
                var result = unpacker.LastReadData;
                return(result.IsNil ? MessagePackObject.Nil : result);
            }
        }
Example #29
0
    private IEnumerable <Material> IterateCustomTextures(
        MessagePackObjectDictionary worldDict, bool overlay)
    {
        string key   = overlay ? FileKeys.WORLD_CUSTOM_OVERLAYS : FileKeys.WORLD_CUSTOM_MATERIALS;
        var    names = new Dictionary <string, Material>();

        if (worldDict.ContainsKey(key))
        {
            foreach (var matObj in worldDict[key].AsList())
            {
                yield return(ReadCustomTexture(matObj.AsDictionary(), names, overlay));
            }
        }
    }
        void OnRecv_Response_BlockHeight(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var index = dict["blockIndex"].AsUInt64();

            if (index >= this.blockIndex)//blockIndex始终要比当前存在的block高度大一个
            {
                for (ulong i = this.blockIndex; i < index; i++)
                {
                    if (i != 0)
                    {
                        Tell_Request_Block(from, i);
                    }
                }
            }
        }
        void OnRecv_BoradCast_PeerState(IModulePipeline from, MessagePackObjectDictionary dict)
        {
            var parentPleve = dict["plevel"].AsInt32();

            if (this.linkNodes.TryGetValue(from.system.PeerID, out LinkObj link))
            {
                this.getPlevelFromLinkObj(link, parentPleve);
            }
            //Console.WriteLine("# from:" + link.publicEndPoint + " plevel:" + link.pLevel + " node:" + this.config.PublicEndPoint + " plevel:" + this.pLevel);

            //if (this.pLevel > parentPleve||this.pLevel==-1)
            //{
            //    this.pLevel = parentPleve + 1;
            //}
        }
Example #32
0
		internal bool ReadSubtreeObject( bool isDeep, out MessagePackObject result )
		{
			byte header;
			long integral;
			float real32;
			double real64;
			var type = this.ReadValue( out header, out integral, out real32, out real64 );
			switch( type )
			{
				case ReadValueResult.Eof:
				{
					result = default( MessagePackObject );
					return false;
				}
				case ReadValueResult.Nil:
				{
					this.InternalCollectionType = CollectionType.None;
					result = MessagePackObject.Nil;
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Boolean:
				{
					this.InternalCollectionType = CollectionType.None;
					result = integral != 0;
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.SByte:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( SByte )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Int16:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( Int16 )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Int32:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( Int32 )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Int64:
				{
					this.InternalCollectionType = CollectionType.None;
					result = integral;
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Byte:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( Byte )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.UInt16:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( UInt16 )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.UInt32:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( UInt32 )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.UInt64:
				{
					this.InternalCollectionType = CollectionType.None;
					result = unchecked( ( UInt64 )integral );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Single:
				{
					this.InternalCollectionType = CollectionType.None;
					result = real32;
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Double:
				{
					this.InternalCollectionType = CollectionType.None;
					result = real64;
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.ArrayLength:
				{
					var length = unchecked( ( UInt32 )this.ReadArrayLengthCore( integral ) );
					if ( !isDeep )
					{
						result = length;
						this.InternalData = result;
						return true;
					}
				
					this.CheckLength( length, ReadValueResult.ArrayLength );
					var collection = new List<MessagePackObject>( unchecked( ( int ) length ) );
					for( var i = 0; i < length; i++ )
					{
						MessagePackObject item;
						if( !this.ReadSubtreeObject( /* isDeep */true, out item ) )
						{
							result = default( MessagePackObject );
							return false;
						}
				
						collection.Add( item );
					}
				
					{
						result = new MessagePackObject( collection, /* isImmutable */true );
						this.InternalData = result;
						return true;
					}
				}
				case ReadValueResult.MapLength:
				{
					var length = unchecked( ( UInt32 )this.ReadMapLengthCore( integral ) );
					if ( !isDeep )
					{
						result = length;
						this.InternalData = result;
						return true;
					}
				
					this.CheckLength( length, ReadValueResult.MapLength );
					var collection = new MessagePackObjectDictionary( unchecked( ( int ) length ) );
					for( var i = 0; i < length; i++ )
					{
						MessagePackObject key;
						if( !this.ReadSubtreeObject( /* isDeep */true, out key ) )
						{
							result = default( MessagePackObject );
							return false;
						}
				
						MessagePackObject value;
						if( !this.ReadSubtreeObject( /* isDeep */true, out value ) )
						{
							result = default( MessagePackObject );
							return false;
						}
				
						collection.Add( key, value );
					}
				
					{
						result = new MessagePackObject( collection, /* isImmutable */true );
						this.InternalData = result;
						return true;
					}
				}
				
				case ReadValueResult.String:
				{
					result = new MessagePackObject( new MessagePackString( this.ReadBinaryCore( integral ), false ) );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.Binary:
				{
					result = new MessagePackObject( new MessagePackString( this.ReadBinaryCore( integral ), true ) );
					this.InternalData = result;
					return true;
				}
				case ReadValueResult.FixExt1:
				case ReadValueResult.FixExt2:
				case ReadValueResult.FixExt4:
				case ReadValueResult.FixExt8:
				case ReadValueResult.FixExt16:
				case ReadValueResult.Ext8:
				case ReadValueResult.Ext16:
				case ReadValueResult.Ext32:
				{
					result = this.ReadMessagePackExtendedTypeObjectCore( type );
					this.InternalData = result;
					return true;
				}
				default:
				{
					this.ThrowTypeException( typeof( MessagePackObject ), header );
					// Never reach
					result = default( MessagePackObject );
					return false;
				}
			}
		} 
Example #33
0
		internal async Task<AsyncReadResult<MessagePackObject>> ReadSubtreeObjectAsync( bool isDeep, CancellationToken cancellationToken )
		{
			var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false );
			var type = asyncResult.type;
			switch( type )
			{
				case ReadValueResult.Eof:
				{
					return AsyncReadResult.Fail<MessagePackObject>();
				}
				case ReadValueResult.Nil:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = MessagePackObject.Nil;
					this.InternalData = result;
					return AsyncReadResult.Success( result );
				}
				case ReadValueResult.Boolean:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = asyncResult.integral != 0;
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.SByte:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( SByte )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Int16:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( Int16 )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Int32:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( Int32 )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Int64:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = asyncResult.integral;
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Byte:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( Byte )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.UInt16:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( UInt16 )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.UInt32:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( UInt32 )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.UInt64:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = unchecked( ( UInt64 )asyncResult.integral );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Single:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = asyncResult.real32;
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.Double:
				{
					this.InternalCollectionType = CollectionType.None;
					var result = asyncResult.real64;
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				case ReadValueResult.ArrayLength:
				{
					// ReadArrayLengthCore does not perform I/O, so no ReadArrayLengthAsyncCore exists.
					var length = unchecked( ( UInt32 )this.ReadArrayLengthCore( asyncResult.integral ) );
					if ( !isDeep )
					{
						var result = length;
						this.InternalData = result;
						return AsyncReadResult.Success<MessagePackObject>( result );
					}
				
					this.CheckLength( length, ReadValueResult.ArrayLength );
					var collection = new List<MessagePackObject>( unchecked( ( int ) length ) );
					for( var i = 0; i < length; i++ )
					{
						MessagePackObject item;
						if( !this.ReadSubtreeObject( /* isDeep */true, out item ) )
						{
							return AsyncReadResult.Fail<MessagePackObject>();
						}
				
						collection.Add( item );
					}
				
					{
						var result = new MessagePackObject( collection, /* isImmutable */true );
						this.InternalData = result;
						return AsyncReadResult.Success<MessagePackObject>( result );
					}
				}
				case ReadValueResult.MapLength:
				{
					// ReadMapLengthCore does not perform I/O, so no ReadMapLengthAsyncCore exists.
					var length = unchecked( ( UInt32 )this.ReadMapLengthCore( asyncResult.integral ) );
					if ( !isDeep )
					{
						var result = length;
						this.InternalData = result;
						return AsyncReadResult.Success<MessagePackObject>( result );
					}
				
					this.CheckLength( length, ReadValueResult.MapLength );
					var collection = new MessagePackObjectDictionary( unchecked( ( int ) length ) );
					for( var i = 0; i < length; i++ )
					{
						MessagePackObject key;
						if( !this.ReadSubtreeObject( /* isDeep */true, out key ) )
						{
							return AsyncReadResult.Fail<MessagePackObject>();
						}
				
						MessagePackObject value;
						if( !this.ReadSubtreeObject( /* isDeep */true, out value ) )
						{
							return AsyncReadResult.Fail<MessagePackObject>();
						}
				
						collection.Add( key, value );
					}
				
					{
						var result = new MessagePackObject( collection, /* isImmutable */true );
						this.InternalData = result;
						return AsyncReadResult.Success<MessagePackObject>( result );
					}
				}
				
				case ReadValueResult.String:
				{
					var result = new MessagePackObject( new MessagePackString( await this.ReadBinaryAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ), false ) );
					this.InternalData = result;
					return AsyncReadResult.Success( result );
				}
				case ReadValueResult.Binary:
				{
					var result = new MessagePackObject( new MessagePackString( await this.ReadBinaryAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ), true ) );
					this.InternalData = result;
					return AsyncReadResult.Success( result );
				}
				case ReadValueResult.FixExt1:
				case ReadValueResult.FixExt2:
				case ReadValueResult.FixExt4:
				case ReadValueResult.FixExt8:
				case ReadValueResult.FixExt16:
				case ReadValueResult.Ext8:
				case ReadValueResult.Ext16:
				case ReadValueResult.Ext32:
				{
					var result = await this.ReadMessagePackExtendedTypeObjectAsyncCore( type, cancellationToken ).ConfigureAwait( false );
					this.InternalData = result;
					return AsyncReadResult.Success<MessagePackObject>( result );
				}
				default:
				{
					this.ThrowTypeException( typeof( MessagePackObject ), asyncResult.header );
					// Never reach
					return AsyncReadResult.Fail<MessagePackObject>();
				}
			}
		} 
        //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;
        }
Example #35
0
 public void Deserialize()
 {
     var serializer = MessagePackSerializer.Get<MessagePackObjectDictionary>();
     m_Dict = serializer.Unpack(m_ReadStream.Stream);
 }
Example #36
0
		public void TestToException_RpcErrorMessagePackObject_DictionaryMesssagePackObject_AsIs()
		{
			var error = RpcError.MessageRefusedError;
			var message = Guid.NewGuid().ToString();
			var debugInformation = Guid.NewGuid().ToString();
			var detail =
				new MessagePackObjectDictionary()
				{
					{ RpcException.MessageKeyUtf8, message },
					{ RpcException.DebugInformationKeyUtf8, debugInformation }
				};

			var target = new RpcErrorMessage( error, new MessagePackObject( detail ) );
			var result = target.ToException();

			Assert.That( result.RpcError, Is.EqualTo( error ) );
			Assert.That( result.Message, Is.EqualTo( message ) );
			Assert.That( result.DebugInformation, Is.EqualTo( debugInformation ) );

		}
Example #37
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 );
			}
		}
		private static void DictionaryEquals( MessagePackObjectDictionary actual, IDictionary<int, int> expected )
		{
			foreach( var entry in actual )
			{
				int value;
				Assert.That( expected.TryGetValue( entry.Key.AsInt32(), out value ), "Key: " + entry.Key );
				Assert.That( entry.Value, Is.EqualTo( ( MessagePackObject )value ), "Value: " + entry.Key );
			}
		}
Example #39
0
		public void TestPackT_IDictionary_ItemIsMessagePackObject_Success()
		{
			var value = new MessagePackObjectDictionary() { { 1, 1 }, { 2, 2 } };
			using ( var buffer = new MemoryStream() )
			using ( var packer = Packer.Create( buffer ) )
			{
				packer.Pack( value );
				Assert.AreEqual(
					new byte[] { 0x82, 0x1, 0x1, 0x2, 0x2 },
					buffer.ToArray()
				);
			}
		}
Example #40
0
			public RemoteExceptionInformation( IList<MessagePackObject> unpacked )
			{
				if ( unpacked.Count != 6 )
				{
					throw new SerializationException( "Count of remote exception information must be 6." );
				}

				this.Hop = unpacked[ 0 ].AsInt32();
				this.TypeName = unpacked[ 1 ].AsString();
				this.HResult = unpacked[ 2 ].AsInt32();
				this.Message = unpacked[ 3 ].AsString();
				this.StackTrace = unpacked[ 4 ].AsList().Select( item => new RemoteStackFrame( item.AsList() ) ).ToArray();
				this.Data = unpacked[ 5 ].AsDictionary();
			}
Example #41
0
		/// <summary>
		///		Get <see cref="MessagePackObject"/> which contains data about this instance.
		/// </summary>
		/// <param name="isDebugMode">
		///		If this method should include debug information then true.
		/// </param>
		/// <returns>
		///		<see cref="MessagePackObject"/> which contains data about this instance.
		/// </returns>
		public MessagePackObject GetExceptionMessage( bool isDebugMode )
		{
			var store = new MessagePackObjectDictionary( 2 );
			store.Add( _errorCodeUtf8, this.RpcError.ErrorCode );
			store.Add( MessageKeyUtf8, isDebugMode ? this.Message : this.RpcError.DefaultMessageInvariant );
			this.GetExceptionMessage( store, isDebugMode );

			return new MessagePackObject( store );
		}
Example #42
0
 public void Serialize(MessagePackObjectDictionary body)
 {
     var serializer = MessagePackSerializer.Get<MessagePackObjectDictionary>();
     var stream = new MemoryStream();
     serializer.Pack(stream, body);
     var buffer = stream.GetBuffer();
     EnsureCapacity((ushort)stream.Length);
     m_Stream.Write(buffer, 0, (int)stream.Length);
 }
Example #43
0
		private static MessagePackObjectDictionary UnpackDictionaryCore( Unpacker unpacker )
		{
			if ( IsNil( unpacker ) )
			{
				return null;
			}


			uint count = ( uint )unpacker.Data.Value;
			if ( count > Int32.MaxValue )
			{
				throw new MessageNotSupportedException( "The map which count is greater than Int32.MaxValue is not supported." );
			}

			var result = new MessagePackObjectDictionary( unchecked( ( int )count ) );
			for ( int i = 0; i < count; i++ )
			{
				var key = UnpackObjectCore( unpacker );
				var value = UnpackObjectCore( unpacker );
				try
				{
					result.Add( key, value );
				}
				catch ( ArgumentException ex )
				{
					throw new InvalidMessagePackStreamException( "The dicationry key is duplicated in the stream.", ex );
				}
			}

			return result;
		}
Example #44
0
		/// <summary>
		///		Stores derived type specific information to specified dictionary.
		/// </summary>
		/// <param name="store">
		///		Dictionary to be stored. This value will not be <c>null</c>.
		///	</param>
		/// <param name="includesDebugInformation">
		///		<c>true</c>, when this method should include debug information; otherwise, <c>false</c>.
		///	</param>
		protected virtual void GetExceptionMessage( IDictionary<MessagePackObject, MessagePackObject> store, bool includesDebugInformation )
		{
			Contract.Requires( store != null );

			if ( !includesDebugInformation )
			{
				return;
			}

			if ( this.InnerException != null || this._remoteExceptions != null )
			{
				var innerList = new List<MessagePackObject>();
				if ( this._remoteExceptions != null )
				{
					foreach ( var remoteException in this._remoteExceptions )
					{
						MessagePackObject[] properties = new MessagePackObject[ 6 ];
						properties[ 0 ] = remoteException.Hop + 1;
						properties[ 1 ] = MessagePackConvert.EncodeString( remoteException.TypeName );
						// HResult is significant for some exception (e.g. IOException).
						properties[ 2 ] = remoteException.HResult;
						properties[ 3 ] = MessagePackConvert.EncodeString( remoteException.Message );
						properties[ 4 ] =
#if !SILVERLIGHT
							Array.ConvertAll(
#else
							ArrayExtensions.ConvertAll(
#endif
								remoteException.StackTrace,
								frame =>
									frame.FileName == null
									? new MessagePackObject( new MessagePackObject[] { frame.MethodSignature, frame.ILOffset, frame.NativeOffset } )
									: new MessagePackObject( new MessagePackObject[] { frame.MethodSignature, frame.ILOffset, frame.NativeOffset, frame.FileName, frame.FileLineNumber, frame.FileColumnNumber } )
							);
						properties[ 5 ] = new MessagePackObject( remoteException.Data );
						innerList.Add( properties );
					}
				}

				for ( var inner = this.InnerException; inner != null; inner = inner.InnerException )
				{
					MessagePackObject[] properties = new MessagePackObject[ 6 ];
					properties[ 0 ] = 0;
					properties[ 1 ] = MessagePackConvert.EncodeString( inner.GetType().FullName );
					// HResult is significant for some exception (e.g. IOException).
					properties[ 2 ] = SafeGetHRFromException( inner );
					properties[ 3 ] = MessagePackConvert.EncodeString( inner.Message );

					// stack trace
					var innerStackTrace = 
#if !SILVERLIGHT
						new StackTrace( inner, true );
#else
						new StackTrace( inner );
#endif
					var frames = new MessagePackObject[ innerStackTrace.FrameCount ];
					for ( int i = 0; i < frames.Length; i++ )
					{
						var frame = innerStackTrace.GetFrame( innerStackTrace.FrameCount - ( i + 1 ) );
#if !SILVERLIGHT
						if ( frame.GetFileName() == null )
						{
#endif
							frames[ i ] = new MessagePackObject[] { ToStackFrameMethodSignature( frame.GetMethod() ), frame.GetILOffset(), frame.GetNativeOffset() };
#if !SILVERLIGHT
						}
						else
						{
							frames[ i ] = new MessagePackObject[] { ToStackFrameMethodSignature( frame.GetMethod() ), frame.GetILOffset(), frame.GetNativeOffset(), frame.GetFileName(), frame.GetFileLineNumber(), frame.GetFileColumnNumber() };
						}
#endif
					}
					properties[ 4 ] = new MessagePackObject( frames );

					// data
					if ( inner.Data != null && inner.Data.Count > 0 )
					{
						var data = new MessagePackObjectDictionary( inner.Data.Count );
						foreach ( System.Collections.DictionaryEntry entry in inner.Data )
						{
							data.Add( MessagePackObject.FromObject( entry.Key ), MessagePackObject.FromObject( entry.Value ) );
						}

						properties[ 5 ] = new MessagePackObject( data );
					}

					innerList.Add( properties );
				}

				store.Add( _remoteExceptionsUtf8, new MessagePackObject( innerList ) );
			}

			store.Add( DebugInformationKeyUtf8, this.DebugInformation );

		}