public byte[] MakePacket(string label, DateTime timestamp, params object[] records)
        {
            string tag;
            if (!string.IsNullOrEmpty(label))
            {
                tag = _tag + "." + label;
            }
            else
            {
                tag = _tag;
            }

            var xs = new List<MessagePackObject>();
            xs.Add(tag);
            var children = new List<MessagePackObject>();
            foreach (var record in records)
            {
                var child = new List<MessagePackObject>();
                child.Add(timestamp.ToUniversalTime().Subtract(_epoc).TotalSeconds);
                child.Add(CreateTypedMessagePackObject(record.GetType(), record, first:true));
                children.Add(new MessagePackObject(child));
            }
            xs.Add(new MessagePackObject(children));

            var x = new MessagePackObject(xs);

            var ms = new MemoryStream();
            var packer = Packer.Create(ms);
            packer.Pack(x);
            return ms.ToArray();
        }
		/// <summary>
		///		Initialize new instance with unpacked data.
		/// </summary>
		/// <param name="rpcError">
		///		Metadata of error. If you specify null, <see cref="MsgPack.Rpc.RpcError.RemoteRuntimeError"/> is used.
		///	</param>
		/// <param name="unpackedException">
		///		Exception data from remote MessagePack-RPC server.
		///	</param>
		/// <exception cref="SerializationException">
		///		Cannot deserialize instance from <paramref name="unpackedException"/>.
		/// </exception>
		protected internal RpcException( RpcError rpcError, MessagePackObject unpackedException )
			: this( rpcError, unpackedException.GetString( MessageKeyUtf8 ), unpackedException.GetString( DebugInformationKeyUtf8 ) )
		{
			if ( unpackedException.IsDictionary )
			{
				MessagePackObject mayBeArray;
				if ( unpackedException.AsDictionary().TryGetValue( _remoteExceptionsUtf8, out mayBeArray ) && mayBeArray.IsArray )
				{
					var array = mayBeArray.AsList();
					this._remoteExceptions = new RemoteExceptionInformation[ array.Count ];
					for ( int i = 0; i < this._remoteExceptions.Length; i++ )
					{
						if ( array[ i ].IsList )
						{
							this._remoteExceptions[ i ] = new RemoteExceptionInformation( array[ i ].AsList() );
						}
						else
						{
							// Unexpected type.
							Debug.WriteLine( "Unexepcted ExceptionInformation at {0}, type: {1}, value: \"{2}\".", i, array[ i ].UnderlyingType, array[ i ] );
							this._remoteExceptions[ i ] = new RemoteExceptionInformation( new MessagePackObject[] { array[ i ] } );
						}
					}
				}
			}

#if !SILVERLIGHT && !MONO
			this.RegisterSerializeObjectStateEventHandler();
#endif
		}
Beispiel #3
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;
 }
		public void TestAsByteOverflow()
		{
			var target = new MessagePackObject( Byte.MaxValue + 1 );
			Assert.Throws<InvalidOperationException>(
				() =>
				{
					var result = ( Byte )target;
					Console.WriteLine( "TestAsByteOverflow:0x{0:x}({0:#,0})[{1}]", result, result.GetType() );
				}
			);
		}
Beispiel #5
0
        public void TestAsInt16Underflow()
        {
            var target = new MessagePackObject(Int16.MinValue - 1);

            Assert.Throws <InvalidOperationException>(
                () =>
            {
                var result = ( Int16 )target;
                Console.WriteLine("TestAsInt16Overflow:0x{0:x}({0:#,0})[{1}]", result, result.GetType());
            }
                );
        }
Beispiel #6
0
        public static TimeSpan?GetTimeSpan(this MessagePackObject source, MessagePackObject key)
        {
            if (source.IsDictionary)
            {
                if (source.AsDictionary().TryGetValue(key, out var value) && value.IsTypeOf <long>().GetValueOrDefault())
                {
                    return(new TimeSpan(value.AsInt64()));
                }
            }

            return(null);
        }
Beispiel #7
0
        public void SetPlayerData(string id, MessagePackObject data)
        {
            _playerData[id] = data;

            _scene.Broadcast(PLAYERDATA_UPDATED_ROUTE,
                             new PlayerDataUpdate {
                PlayerId = id, Data = data
            },
                             PacketPriority.LOW_PRIORITY,
                             PacketReliability.RELIABLE_ORDERED
                             );
        }
        /// <summary>
        ///		Initialize new instance.
        /// </summary>
        /// <param name="error">Error information of the error.</param>
        /// <param name="detail">Unpacked detailed information of the error which was occurred in remote endpoint.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="error"/> is null.
        /// </exception>
        public RpcErrorMessage( RpcError error, MessagePackObject detail )
        {
            if ( error == null )
            {
                throw new ArgumentNullException( "error" );
            }

            Contract.EndContractBlock();

            this._error = error;
            this._detail = detail;
        }
        /// <summary>
        /// </summary>
        /// <param name="objects">
        /// </param>
        /// <returns>
        /// </returns>
        public static string List(MessagePackObject[] objects)
        {
            string output = string.Empty;

            foreach (MessagePackObject mpo in objects)
            {
                // Using \r\n here with purpose, dont change to Environment.NewLine
                output += mpo.UnderlyingType.ToString() + ": " + mpo.ToString() + "\r\n";
            }

            return output;
        }
Beispiel #10
0
        public static string GetString(this MessagePackObject source, MessagePackObject key)
        {
            if (source.IsDictionary)
            {
                if (source.AsDictionary().TryGetValue(key, out var value) && value.IsTypeOf <string>().GetValueOrDefault())
                {
                    return(value.AsString());
                }
            }

            return(null);
        }
Beispiel #11
0
        public void TestAsSByteOverflow()
        {
            var target = new MessagePackObject(SByte.MaxValue + 1);

            Assert.Throws <InvalidOperationException>(
                () =>
            {
                var result = ( SByte )target;
                Console.WriteLine("TestAsSByteOverflow:0x{0:x}({0:#,0})[{1}]", result, result.GetType());
            }
                );
        }
        public void TestDynamicInvocation_Success()
        {
            string arg        = Guid.NewGuid().ToString();
            int    messageId  = Environment.TickCount % 1000;
            string methodName = "SomeMethod";

            using (var environment = new InProcTestEnvironment((method, id, args) => method == methodName && args[0].AsString() == arg))
                using (dynamic target = new DynamicRpcProxy(environment.EndPoint, environment.Configuration))
                {
                    MessagePackObject result = target.SomeMethod(arg);
                    Assert.That(result == true);
                }
        }
    private Color ReadColor(MessagePackObject o)
    {
        var l = o.AsList();

        if (l.Count == 4)
        {
            return(new Color(l[0].AsSingle(), l[1].AsSingle(), l[2].AsSingle(), l[3].AsSingle()));
        }
        else
        {
            return(new Color(l[0].AsSingle(), l[1].AsSingle(), l[2].AsSingle()));
        }
    }
Beispiel #14
0
        public void SetState(MessagePackObject state, int remoteCurrentTime, int remoteElapsedTime)
        {
            this.state.Set(state);

            // TODO:
            // Create a "clock" for remoteCurrentTime / remoteElapsedTime to match the JavaScript API.

            // Creates serializer.
            var serializer = MessagePackSerializer.Get <MessagePackObject>();

            this.OnUpdate.Invoke(this, new RoomUpdateEventArgs(this, state, null));
            this._previousState = serializer.PackSingleObject(state);
        }
		public static string GetString( this MessagePackObject source, MessagePackObject key )
		{
			if ( source.IsDictionary )
			{
				MessagePackObject value;
				if ( source.AsDictionary().TryGetValue( key, out value ) && value.IsTypeOf<string>().GetValueOrDefault() )
				{
					return value.AsString();
				}
			}

			return null;
		}
        private static void TestRuntimeSerializationCore(MessagePackObject target)
        {
            var formatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, target);
                stream.Position = 0;
                var actual = ( MessagePackObject )formatter.Deserialize(stream);

                Assert.AreEqual(target, actual);
            }
        }
		public static TimeSpan? GetTimeSpan( this MessagePackObject source, MessagePackObject key )
		{
			if ( source.IsDictionary )
			{
				MessagePackObject value;
				if ( source.AsDictionary().TryGetValue( key, out value ) && value.IsTypeOf<Int64>().GetValueOrDefault() )
				{
					return new TimeSpan( value.AsInt64() );
				}
			}

			return null;
		}
        public void TestEquals_Map_SubMap_False()
        {
            var target = new MessagePackObject(new MessagePackObjectDictionary()
            {
                { "A", 1 }, { "B", 2 }, { "C", 3 }
            });
            var other = new MessagePackObject(new MessagePackObjectDictionary()
            {
                { "A", 1 }, { "B", 2 }
            });

            Assert.IsFalse(target.Equals(other));
        }
Beispiel #19
0
        private static object MapDateTime(PropertyInfo property, MessagePackObject source)
        {
            var conversionMethod = property?.GetCustomAttribute <MessagePackDateTimeMemberAttribute>()
                                   ?.DateTimeConversionMethod;

            switch (conversionMethod)
            {
            case DateTimeMemberConversionMethod.UnixEpoc:
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                return(epoch.AddMilliseconds(source.AsInt64()));

            default: return(DateTime.FromBinary(source.AsInt64()));
            }
        }
Beispiel #20
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}.");
        }
        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);
            }
        }
Beispiel #22
0
        private static void TestInt(int val)
        {
            MessagePackObject objInt  = val;
            MessagePackObject objLong = ( long )val;

#pragma warning disable 1718
            Assert.IsTrue(objInt == objInt);
#pragma warning restore 1718
            Assert.IsTrue(objInt == objLong);
            Assert.IsTrue(objLong == objInt);
#pragma warning disable 1718
            Assert.IsTrue(objLong == objLong);
#pragma warning restore 1718
        }
        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);
        }
Beispiel #24
0
        protected override async Task <bool> ReadAsyncCore(CancellationToken cancellationToken)
        {
            var result = await this.ReadSubtreeObjectAsync(/* isDeep */ false, cancellationToken).ConfigureAwait(false);

            if (result.Success)
            {
                this.InternalData = result.Value;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #25
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());
                }
            }
Beispiel #26
0
        protected override bool ReadCore()
        {
            MessagePackObject value;
            var success = this.ReadSubtreeObject(out value);

            if (success)
            {
                this.InternalData = value;
                return(true);
            }
            else
            {
                return(false);
            }
        }
    private void ReadEdge(MessagePackObject edgeObj, Voxel voxel)
    {
        var edgeList = edgeObj.AsList();

        if (edgeList.Count == 0)
        {
            return;
        }
        int edgeI = edgeList[0].AsInt32();

        if (edgeList.Count >= 2)
        {
            voxel.edges[edgeI].bevel = edgeList[1].AsByte();
        }
    }
        /// <inheritdoc />
        public object Unpack(MessagePackObject obj)
        {
            if (obj.IsList)
            {
                IList <MessagePackObject> list = obj.AsList();
                return(this.Unpack(list));
            }
            if (obj.IsMap)
            {
                MessagePackObjectDictionary map = obj.AsDictionary();
                return(map.ToDictionary(k => k.Key.ToString(), k => Unpack(k.Value)));
            }

            return(obj.ToObject());
        }
        public override bool Execute(
            INamedEntity self,
            IEntity caller,
            IInstancedEntity target,
            MessagePackObject[] arguments)
        {
            ICharacter character = (ICharacter)self;

            int statelId = (int)((uint)0xC0000000 | arguments[1].AsInt32() | (arguments[2].AsInt32() << 16));
            character.Stats[StatIds.externaldoorinstance].BaseValue = 0;
            character.Stats[StatIds.externalplayfieldinstance].BaseValue = 0;

            if (arguments[1].AsInt32() > 0)
            {
                StatelData sd = PlayfieldLoader.PFData[arguments[1].AsInt32()].GetDoor(statelId);
                if (sd == null)
                {
                    throw new Exception(
                        "Statel " + arguments[3].AsInt32().ToString("X") + " not found? Check the rdb dammit");
                }

                Vector3 v = new Vector3(sd.X, sd.Y, sd.Z);

                Quaternion q = new Quaternion(sd.HeadingX, sd.HeadingY, sd.HeadingZ, sd.HeadingW);

                Quaternion.Normalize(q);
                Vector3 n = (Vector3)q.RotateVector3(Vector3.AxisZ);

                v.x += n.x * 2.5;
                v.z += n.z * 2.5;
                character.Playfield.Teleport(
                    (Dynel)character,
                    new Coordinate(v),
                    q,
                    new Identity() { Type = (IdentityType)arguments[0].AsInt32(), Instance = arguments[1].AsInt32() });
            }

            return true;

            self.Stats[StatIds.externalplayfieldinstance].Value = 0;
            self.Stats[StatIds.externaldoorinstance].Value = 0;
            self.Playfield.Teleport(
                (Dynel)self,
                new Coordinate(100, 10, 100),
                ((ICharacter)self).Heading,
                new Identity() { Type = (IdentityType)arguments[0].AsInt32(), Instance = arguments[1].AsInt32() });
            return true;
        }
Beispiel #30
0
        public void TestNestedArray()
        {
            var output = new MemoryStream();

            Packer.Create(output).Pack(new[] { new int[0], new[] { 0 }, new[] { 0, 1 } });
            MessagePackObject obj = UnpackOne(output);
            var outer             = obj.AsList();

            Assert.AreEqual(3, outer.Count);
            Assert.AreEqual(0, outer[0].AsList().Count);
            Assert.AreEqual(1, outer[1].AsList().Count);
            Assert.That(outer[1].AsList()[0].AsInt32(), Is.EqualTo(0).With.TypeOf <int>());
            Assert.AreEqual(2, outer[2].AsList().Count);
            Assert.That(outer[2].AsList()[0].AsInt32(), Is.EqualTo(0).With.TypeOf <int>());
            Assert.AreEqual(1, outer[2].AsList()[1].AsInt32());
        }
 private static void PackValuesAsArray(
     Packer packer,
     MessagePackObject memberDefault,
     MessagePackObject nullButValueType,
     MessagePackObject nullAndNullableValueType,
     MessagePackObject nullAndReferenceType,
     MessagePackObject prohibitReferenceType
     )
 {
     packer.PackArrayHeader(5);
     packer.Pack(memberDefault);
     packer.Pack(nullButValueType);
     packer.Pack(nullAndNullableValueType);
     packer.Pack(nullAndReferenceType);
     packer.Pack(prohibitReferenceType);
 }
Beispiel #32
0
        protected override bool ReadCore()
        {
            MessagePackObject value;
            var success = this.ReadSubtreeObject(out value);

            if (success)
            {
                this.InternalData = value;
                return(true);
            }
            // ReSharper disable once RedundantIfElseBlock
            else
            {
                return(false);
            }
        }
		private static void PackValuesAsArray(
			Packer packer,
			MessagePackObject memberDefault,
			MessagePackObject nullButValueType,
			MessagePackObject nullAndNullableValueType,
			MessagePackObject nullAndReferenceType,
			MessagePackObject prohibitReferenceType
		)
		{
			packer.PackArrayHeader( 5 );
			packer.Pack( memberDefault );
			packer.Pack( nullButValueType );
			packer.Pack( nullAndNullableValueType );
			packer.Pack( nullAndReferenceType );
			packer.Pack( prohibitReferenceType );
		}
Beispiel #34
0
        public RPC_Result RPC_SendRawTransaction(IList <MessagePackObject> _params)
        {
            var message = _params.First();
            var pubkey  = this.pubkey;
            var sign    = Helper_NEO.Sign(message.AsBinary(), this.prikey);

            var signdata = new TransactionSign();

            signdata.VScript = pubkey;
            signdata.IScript = sign;
            var data = SerializeHelper.SerializeToBinary(signdata);

            this.Tell_SendRaw(this._System.GetPipeline(this, "this/node"), message.AsBinary(), data);
            var result = new MessagePackObject(0);

            return(new RPC_Result(result));
        }
 /// <summary>
 /// </summary>
 /// <param name="self">
 /// </param>
 /// <param name="caller">
 /// </param>
 /// <param name="target">
 /// </param>
 /// <param name="arguments">
 /// </param>
 /// <returns>
 /// </returns>
 public override bool Execute(
     INamedEntity self,
     IEntity caller,
     IInstancedEntity target,
     MessagePackObject[] arguments)
 {
     string text = arguments[0].AsString();
     var message = new FormatFeedbackMessage()
                   {
                       Identity = self.Identity,
                       FormattedMessage = "~&!!!\":!!!)<s" + (char)(text.Length + 1),
                       Unknown1 = 0,
                       Unknown2 = 0,
                   };
     ((ICharacter)self).Send(message);
     return true;
 }
Beispiel #36
0
        // public int GetInstanceID()
        // {
        //     return this.m_InstanceID;
        // }

//        public override bool Equals(object o)
//        {
//            return Object.CompareBaseObjects(this, o as Object);
//        }

        // private static bool CompareBaseObjects(Object lhs, Object rhs)
        // {
        //     return lhs == rhs;
//            if (lhs == null && rhs == null)
//                return true;
//            if (lhs != null && rhs != null)
//                return lhs.m_InstanceID == rhs.m_InstanceID;
//
//            return false;
        // }



//        public static T DeepClone<T>(T obj)
//        {
//            using (var ms = new MemoryStream())
//            {
//                var formatter = new BinaryFormatter();
//                formatter.Serialize(ms, obj);
//                ms.Position = 0;
//
//                return (T) formatter.Deserialize(ms);
//            }
//        }

        public static Object Instantiate(Object original)
        {
            Object.CheckNullArgument((object)original, "The Object you want to instantiate is null.");

            var gameObject = original as GameObject;

            if (gameObject != null)
            {
                SceneManager.dontAddGameObject = true;
            }

            var serializer        = UnikonEngine.serializationContext.GetSerializer(original.GetType());
            MessagePackObject mpo = serializer.ToMessagePackObject(original);
            var clone             = serializer.FromMessagePackObject(mpo);

            if (gameObject != null)
            {
#if DEBUG_UNIKON
                Debug.Log("GameObject Instantiate");
                Debug.Log(mpo.ToString());


                foreach (var component in (clone as GameObject).components)
                {
                    Debug.Log(component.GetType().Name);
                }
#endif

                SceneManager.dontAddGameObject = false;
                SceneManager.AddGameObject(clone as GameObject);

//                gameObject.dontAwake = false;
//                foreach (var component in gameObject.components)
//                {
//                    var awakeMethod = component.GetType().GetMethod("Awake",
//                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
//                    if (awakeMethod != null)
//                    {
//                        Debug.Log("Invoke Awake " + component.GetType());
//                        awakeMethod.Invoke(component, BindingFlags.InvokeMethod, null, null, CultureInfo.CurrentCulture);
//                    }
//
//                }
            }
            return((Object)clone);
        }
        protected internal override object UnpackFromCore(Unpacker unpacker)
        {
            // ReSharper disable RedundantIfElseBlock
            if (unpacker.IsArrayHeader)
            {
                var result = new MessagePackObject[UnpackHelpers.GetItemsCount(unpacker)];
                for (int i = 0; i < result.Length; i++)
                {
                    if (!unpacker.ReadObject(out result[i]))
                    {
                        throw SerializationExceptions.NewUnexpectedEndOfStream();
                    }
                }

                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++)
                {
                    MessagePackObject key;
                    if (!unpacker.ReadObject(out key))
                    {
                        throw SerializationExceptions.NewUnexpectedEndOfStream();
                    }

                    MessagePackObject value;
                    if (!unpacker.ReadObject(out value))
                    {
                        throw SerializationExceptions.NewUnexpectedEndOfStream();
                    }

                    result.Add(key, value);
                }

                return(new MessagePackObject(result));
            }
            else
            {
                var result = unpacker.LastReadData;
                return(result.IsNil ? MessagePackObject.Nil : result);
            }
            // ReSharper restore RedundantIfElseBlock
        }
Beispiel #38
0
        public byte[] ToInitScript()
        {
            var dict = new MessagePackObjectDictionary();

            dict["magicstr"] = MagicStr;
            var array = new MessagePackObject[InitOwner.Length];

            dict["initowner"] = array;
            for (var i = 0; i < InitOwner.Length; i++)
            {
                array[i] = InitOwner[i];
            }

            var arr = MsgPack_Helper.Pack(new MessagePackObject(dict));

            return(arr.ToArray());
        }
        public void TestIssue269()
        {
            var input  = new MessagePackObject(Timestamp.UtcNow.Encode());
            var target = MessagePackSerializer.UnpackMessagePackObject(MessagePackSerializer.Get <MessagePackObject>().PackSingleObject(input));

            Assert.That(target.UnderlyingType, Is.EqualTo(typeof(MessagePackExtendedTypeObject)));
            Assert.That(target.IsTypeOf <byte[]>(), Is.False);
            Assert.That(target.IsTypeOf <MessagePackExtendedTypeObject>(), Is.True);

            var forBinary = Assert.Throws <InvalidOperationException>(() => target.AsBinary());

            Assert.That(forBinary.Message, Is.EqualTo("Do not convert MsgPack.MessagePackExtendedTypeObject MessagePackObject to System.Byte[]."));

            var forString = Assert.Throws <InvalidOperationException>(() => target.AsString());

            Assert.That(forString.Message, Is.EqualTo("Do not convert MsgPack.MessagePackExtendedTypeObject MessagePackObject to System.String."));
        }
    private void ReadVoxel(MessagePackObject voxelObj, VoxelArray voxelArray,
                           List <Material> materials, List <Material> overlays, List <Substance> substances)
    {
        var voxelList = voxelObj.AsList();

        if (voxelList.Count == 0)
        {
            return;
        }

        Vector3 position = ReadVector3(voxelList[0]);
        Voxel   voxel    = null;

        if (!editor)
        {
            // slightly faster -- doesn't add to octree
            voxel = voxelArray.InstantiateVoxel(position);
        }
        else
        {
            voxel = voxelArray.VoxelAt(position, true);
        }

        if (voxelList.Count >= 2)
        {
            foreach (var faceObj in voxelList[1].AsList())
            {
                ReadFace(faceObj, voxel, materials, overlays);
            }
        }

        if (voxelList.Count >= 3 && voxelList[2].AsInt32() != -1)
        {
            voxel.substance = substances[voxelList[2].AsInt32()];
        }

        if (voxelList.Count >= 4)
        {
            foreach (var edgeObj in voxelList[3].AsList())
            {
                ReadEdge(edgeObj, voxel);
            }
        }

        voxel.UpdateVoxel();
    }
Beispiel #41
0
        private string ReadReportBuffer(byte[] buffer, string room, UserId userId)
        {
            StringBuilder     builder            = new StringBuilder();
            MessagePackObject deserializedReport = MessagePackSerializer.UnpackMessagePackObject(buffer);

            builder.AppendLine();
            builder.AppendLine("PlayReport log:");

            if (!userId.IsNull)
            {
                builder.AppendLine($" UserId: {userId.ToString()}");
            }

            builder.AppendLine($" Room: {room}");
            builder.AppendLine($" Report: {MessagePackObjectFormatter.Format(deserializedReport)}");

            return(builder.ToString());
        }
 /// <summary>
 ///		Initialize new sintance with unpacked data.
 /// </summary>
 /// <param name="rpcError">
 ///		Metadata of error. If you specify null, <see cref="MsgPack.Rpc.RpcError.RemoteRuntimeError"/> is used.
 ///	</param>
 /// <param name="unpackedException">
 ///		Exception data from remote MessagePack-RPC server.
 ///	</param>
 /// <exception cref="SerializationException">
 ///		Cannot deserialize instance from <paramref name="unpackedException"/>.
 /// </exception>
 protected internal RpcException( RpcError rpcError, MessagePackObject unpackedException )
     : this(rpcError, GetString( unpackedException, MessageKeyUtf8, true ), GetString( unpackedException, DebugInformationKeyUtf8, false ))
 {
     IList<MessagePackObject> array;
     if ( MessagePackObjectDictionary.TryGetArray( unpackedException, _remoteExceptionsUtf8, null, out array ) )
     {
         try
         {
             this._remoteExceptions = new RemoteExceptionInformation[ array.Count ];
             for ( int i = 0; i < this._remoteExceptions.Length; i++ )
             {
                 this._remoteExceptions[ i ] = new RemoteExceptionInformation( array[ i ].AsList() );
             }
         }
         catch ( InvalidOperationException ex )
         {
             throw new SerializationException( "Failed to deserialize remote exception information", ex );
         }
     }
 }
Beispiel #43
0
		public void UnpackFromMessage( MessagePackObject messagePackObject )
		{
		
			if (! messagePackObject.IsTypeOf<IList<MessagePackObject>>().GetValueOrDefault() )
			{
				throw new ArgumentException(messagePackObject.UnderlyingType.ToString());
			}

			var asList = messagePackObject.AsList();
			if ( asList.Count != 5 )
			{
				throw new ArgumentException();
			}

			uri = asList[ 0 ].AsString();
			title = asList[ 1].AsString();
			width = asList[ 2 ].AsInt32();
			height = asList[ 3 ].AsInt32();
			size = asList[ 4 ].AsInt32();
		}
		private static void PackValuesAsMap(
			Packer packer,
			MessagePackObject memberDefault,
			MessagePackObject nullButValueType,
			MessagePackObject nullAndNullableValueType,
			MessagePackObject nullAndReferenceType,
			MessagePackObject prohibitReferenceType
		)
		{
			packer.PackMapHeader( 5 );
			packer.PackString( "MemberDefault" );
			packer.Pack( memberDefault );
			packer.PackString( "NullButValueType" );
			packer.Pack( nullButValueType );
			packer.PackString( "NullAndNullableValueType" );
			packer.Pack( nullAndNullableValueType );
			packer.PackString( "NullAndReferenceType" );
			packer.Pack( nullAndReferenceType );
			packer.PackString( "ProhibitReferenceType" );
			packer.Pack( prohibitReferenceType );
		}
Beispiel #45
0
		public void TestKnownErrors_Properties_ToException_ToString_GetHashCode_Success()
		{
			foreach ( var prop in typeof( RpcError ).GetProperties( BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic ).Where( item => item.PropertyType == typeof( RpcError ) ) )
			{
				var target = prop.GetValue( null, null ) as RpcError;

				Assert.That( target, Is.Not.Null, prop.Name );
				Assert.That( target.DefaultMessage, Is.Not.Null.And.Not.Empty, prop.Name );
				Assert.That( target.DefaultMessageInvariant, Is.Not.Null.And.Not.Empty, prop.Name );
				Assert.That( target.Identifier, Is.Not.Null.And.Not.Empty, prop.Name );
				Assert.That( target.GetHashCode(), Is.EqualTo( target.ErrorCode ), prop.Name );
				Assert.That(
					target.ToString(),
					Is.Not.Null
					.And.StringContaining( target.Identifier )
					.And.StringContaining( target.ErrorCode.ToString( CultureInfo.CurrentCulture ) )
					.And.StringContaining( target.DefaultMessage ),
					prop.Name
				);
				var message = Guid.NewGuid().ToString();
				var debugInformation = Guid.NewGuid().ToString();
				var detail =
					new MessagePackObject(
						new MessagePackObjectDictionary()
						{
							{ RpcException.MessageKeyUtf8, message },
							{ RpcException.DebugInformationKeyUtf8, debugInformation },
							{ RpcArgumentException.ParameterNameKeyUtf8, "test" },
							{ RpcMethodInvocationException.MethodNameKeyUtf8, "Test" },
							{ RpcTimeoutException.ClientTimeoutKeyUtf8, TimeSpan.FromSeconds( 15 ).Ticks }
						}
					);
				var exception = target.ToException( detail );

				Assert.That( exception, Is.Not.Null, prop.Name );
				Assert.That( exception.DebugInformation, Is.StringContaining( debugInformation ), prop.Name );
				Assert.That( exception.Message, Is.StringContaining( message ), prop.Name );
				Assert.That( exception.RpcError, Is.EqualTo( target ), prop.Name );
			}
		}
        /// <summary>
        /// </summary>
        /// <param name="self">
        /// </param>
        /// <param name="caller">
        /// </param>
        /// <param name="target">
        /// </param>
        /// <param name="arguments">
        /// </param>
        /// <returns>
        /// </returns>
        public override bool Execute(
            INamedEntity self,
            IEntity caller,
            IInstancedEntity target,
            MessagePackObject[] arguments)
        {
            if (arguments.Count() != 3)
            {
                return false;
            }

            uint arg1 = arguments[1].AsUInt32();
            int toPlayfield = arguments[2].AsInt32();

            byte destinationIndex = (byte)(arg1 >> 16);
            PlayfieldData pfd = PlayfieldLoader.PFData[toPlayfield];
            PlayfieldDestination pfDestination = pfd.Destinations[destinationIndex];

            float newX = (pfDestination.EndX - pfDestination.StartX) * 0.5f + pfDestination.StartX;
            float newZ = (pfDestination.EndZ - pfDestination.StartZ) * 0.5f + pfDestination.StartZ;
            float dist = WallCollision.Distance(
                pfDestination.StartX,
                pfDestination.StartZ,
                pfDestination.EndX,
                pfDestination.EndZ);
            float headDistX = (pfDestination.EndX - pfDestination.StartX) / dist;
            float headDistZ = (pfDestination.EndZ - pfDestination.StartZ) / dist;
            newX -= headDistZ * 4;
            newZ += headDistX * 4;

            Coordinate destCoordinate = new Coordinate(newX, pfDestination.EndY, newZ);

            ((ICharacter)self).Teleport(
                destCoordinate,
                ((ICharacter)self).Heading,
                new Identity() { Type = IdentityType.Playfield, Instance = toPlayfield });
            return true;
        }
        /// <summary>
        /// </summary>
        /// <param name="self">
        /// </param>
        /// <param name="caller">
        /// </param>
        /// <param name="target">
        /// </param>
        /// <param name="arguments">
        /// </param>
        /// <returns>
        /// </returns>
        public override bool Execute(
            INamedEntity self, 
            INamedEntity caller, 
            IInstancedEntity target, 
            MessagePackObject[] arguments)
        {
            var temp = new UploadedNano() { NanoId = arguments[0].AsInt32() };
            ((Character)self).UploadedNanos.Add(temp);
            UploadedNanosDao.WriteNano(((Character)self).Identity.Instance, temp);

            var message = new CharacterActionMessage()
                          {
                              Identity = self.Identity,
                              Action = CharacterActionType.UploadNano,
                              Target = self.Identity,
                              Parameter1 = (int)IdentityType.NanoProgram,
                              Parameter2 = temp.NanoId,
                              Unknown = 0
                          };
            ((Character)self).Client.SendCompressed(message);

            return true;
        }
 /// <summary>
 /// </summary>
 /// <param name="self">
 /// </param>
 /// <param name="caller">
 /// </param>
 /// <param name="target">
 /// </param>
 /// <param name="arguments">
 /// </param>
 /// <returns>
 /// </returns>
 public override bool Execute(
     INamedEntity self, 
     INamedEntity caller, 
     IInstancedEntity target, 
     MessagePackObject[] arguments)
 {
     string text = arguments[0].AsString();
     byte b = 0;
     var message = new FormatFeedbackMessage()
                   {
                       Identity = self.Identity,
                       Message = text + (char)b,
                       Unknown1 = 0,
                       DataLength = (short)(text.Length + 0xf),
                       Unknown2 = 0x7e26,
                       Unknown3 = 0x21212122,
                       Unknown4 = 0x3a212121,
                       Unknown5 = 0x293C,
                       Unknown6 = 0x73,
                       Unknown7 = 0
                   };
     ((ICharacter)self).Send(message);
     return true;
 }
        public void Reply( int? id, MessagePackObject message )
        {
            if ( id == null )
            {
                throw new ArgumentException( "id must be set.", "id" );
            }

            if ( this._context.AcceptSocket == null )
            {
                throw new InvalidOperationException();
            }

            using ( var buffer = GCChunkBuffer.CreateDefault() )
            {
                using ( RpcOutputBuffer rpcBuffer = SerializationUtility.SerializeResponse( id.Value, message ) )
                {
                    var bytesToSend = rpcBuffer.ReadBytes().ToArray();
                    this._context.AcceptSocket.Send( bytesToSend );
                }
            }
        }
		private static void TestEqualsCore( MessagePackObject left, MessagePackObject right, bool expected )
		{
			Assert.AreEqual( expected, left.Equals( right ), "{0}=={1}", left.DebugDump(), right.DebugDump() );
		}
		private static void AssertNotEquals( MessagePackObject left, MessagePackObject right )
		{
			TestEqualsCore( left, right, false );
		}
		public void TestEquals_EmptyMap_Null_False()
		{
			var target = new MessagePackObject( new MessagePackObjectDictionary( 0 ) );
			Assert.IsFalse( target.Equals( default( object ) ) );
		}
		public void TestEquals_Map_Raw_False()
		{
			var target = new MessagePackObject( new MessagePackObjectDictionary { { "A", "A" }, { "B", "B" }, { "C", "C" } } );
			var other = new MessagePackObject( "ABC" );
			Assert.IsFalse( target.Equals( other ) );
		}
		public void TestEquals_EmptyMap_Empty_True()
		{
			var target = new MessagePackObject( new MessagePackObjectDictionary( 0 ) );
			Assert.IsTrue( target.Equals( new MessagePackObjectDictionary( 0 ) ) );
		}
		public void TestEquals_Map_Null_False()
		{
			var target = new MessagePackObject( new MessagePackObjectDictionary() { { "A", 1 }, { "B", 2 }, { "C", 3 } } );
			Assert.IsFalse( target.Equals( default( object ) ) );
		}
        public override bool Execute(
            INamedEntity self,
            IEntity caller,
            IInstancedEntity target,
            MessagePackObject[] arguments)
        {
            uint externalDoorInstance = self.Stats[StatIds.externaldoorinstance].BaseValue;
            int externalPlayfieldId = self.Stats[StatIds.externalplayfieldinstance].Value;

            StatelData door =
                PlayfieldLoader.PFData[externalPlayfieldId].Statels.FirstOrDefault(
                    x =>
                        (uint)x.Identity.Instance == externalDoorInstance
                        && (x.Identity.Type == IdentityType.Door /*|| x.Identity.Type==IdentityType.MissionEntrance*/));
            if (door != null)
            {
                Vector3 v = new Vector3(door.X, door.Y, door.Z);

                Quaternion q = new Quaternion(door.HeadingX, door.HeadingY, door.HeadingZ, door.HeadingW);

                Quaternion.Normalize(q);
                Vector3 n = (Vector3)q.RotateVector3(Vector3.AxisZ);

                v.x += n.x * 2.5;
                v.z += n.z * 2.5;
                self.Playfield.Teleport(
                    (Dynel)self,
                    new Coordinate(v),
                    q,
                    new Identity() { Type = IdentityType.Playfield, Instance = externalPlayfieldId });
            }
            return door != null;
        }
 public override bool Execute(
     INamedEntity self,
     IEntity caller,
     IInstancedEntity target,
     MessagePackObject[] arguments)
 {
     Vendor temp = caller as Vendor;
     if (temp != null)
     {
         if (temp.BaseInventory.Pages[temp.BaseInventory.StandardPage].List().Count == 0)
         {
             if (temp.OriginalIdentity.Equals(Identity.None))
             {
             }
             else
             {
                 int id = temp.Playfield.Identity.Instance << 16
                          | ((temp.OriginalIdentity.Instance >> 16) & 0xff);
                 ((ICharacter)self).Playfield.Publish(
                     ChatTextMessageHandler.Default.CreateIM(
                         ((ICharacter)self),
                         "This shop has no entry in the database yet. Please enter a new entry with the id "
                         + id.ToString() + "."));
             }
         }
         else
         {
             ShopUpdateMessageHandler.Default.Send((ICharacter)self, caller, ((Vendor)caller).BaseInventory.Pages[((Vendor)caller).BaseInventory.StandardPage]);
         }
     }
     return true;
 }
 /// <summary>
 /// </summary>
 /// <param name="self">
 /// </param>
 /// <param name="caller">
 /// </param>
 /// <param name="target">
 /// </param>
 /// <param name="arguments">
 /// </param>
 /// <returns>
 /// </returns>
 public override bool Execute(
     INamedEntity self,
     IEntity caller,
     IInstancedEntity target,
     MessagePackObject[] arguments)
 {
     BankMessageHandler.Default.Send((ICharacter)self);
     return true;
 }
Beispiel #59
-1
 /// <summary>
 /// </summary>
 /// <param name="self">
 /// </param>
 /// <param name="caller">
 /// </param>
 /// <param name="target">
 /// </param>
 /// <param name="arguments">
 /// </param>
 /// <returns>
 /// </returns>
 public override bool Execute(
     INamedEntity self, 
     INamedEntity caller, 
     IInstancedEntity target, 
     MessagePackObject[] arguments)
 {
     IZoneClient client = ((ICharacter)self).Client;
     BankMessage bankmessage = OpenBank.Create(client);
     client.Character.Send(bankmessage);
     return true;
 }
 /// <summary>
 /// </summary>
 /// <param name="self">
 /// </param>
 /// <param name="caller">
 /// </param>
 /// <param name="target">
 /// </param>
 /// <param name="arguments">
 /// </param>
 /// <returns>
 /// </returns>
 public override bool Execute(
     INamedEntity self, 
     INamedEntity caller, 
     IInstancedEntity target, 
     MessagePackObject[] arguments)
 {
     lock (target)
     {
         return this.FunctionExecute(self, caller, target, arguments);
     }
 }