public void GetOrderbook(UpbitAPI _U, string _coinCode)
        {
            // 시세 호가 정보(Orderbook) 조회
            //Console.WriteLine(_U.GetOrderbook("KRW-COSM"));
            var orders = MessagePackSerializer.Typeless.Deserialize(MessagePackSerializer.FromJson(_U.GetOrderbook(_coinCode)));

            foreach (var o in orders as object[])
            {
                Dictionary <object, object> d = o as Dictionary <object, object>;
                Console.WriteLine(d["market"]);
                Console.WriteLine(d["orderbook_units"]);
                foreach (var o2 in d["orderbook_units"] as object[])
                {
                    Dictionary <object, object> d2 = o2 as Dictionary <object, object>;
                    Console.WriteLine(d2["ask_price"]);
                    Console.WriteLine(d2["bid_price"]);
                    Console.WriteLine(d2["ask_size"]);
                    Console.WriteLine(d2["bid_size"]);
                }
                //if ((string)d["ask_price"] == _coinCode && (string)d["side"] == "bid")
                //{
                //	Console.WriteLine(_U.CancelOrder((string)d["uuid"]));
                //}
            }
        }
Beispiel #2
0
        /// <inheritdoc />
        public async Task <Schematic <TState, TInput> > RetrieveSchematicAsync(string schematicName,
                                                                               CancellationToken cancellationToken = default)
        {
            if (schematicName == null)
            {
                throw new ArgumentNullException(nameof(schematicName));
            }

            Schematic result;

            try
            {
                result = await DbContext.Schematics.SingleAsync(
                    schematicRecord => schematicRecord.SchematicName == schematicName,
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception)
            {
                throw new SchematicDoesNotExistException(schematicName);
            }

            var schematic = MessagePackSerializer.Deserialize <Schematic <TState, TInput> >(
                bytes: MessagePackSerializer.FromJson(result.SchematicJson),
                resolver: ContractlessStandardResolver.Instance);

            return(schematic);
        }
Beispiel #3
0
        public static T DeserializeJson <T>(string json)
        {
            var data = MessagePackSerializer.FromJson(json);

            File.WriteAllBytes("test2.bin", data);
            return(MessagePackSerializer.Deserialize <T>(data));
        }
Beispiel #4
0
    // Use this for initialization
    void Start()
    {
        animator = GetComponent <Animator>();
        rg       = GetComponent <Rigidbody2D>();

        this.UpdateAsObservable()
        .Where(x => Input.GetKeyDown(KeyCode.Z))
        .Subscribe(x =>
        {
            animator.SetTrigger("Action");
            rg.velocity = new Vector2(4f, rg.velocity.y);
        });

        var mc = new MyClass
        {
            FirstName = "hoge",
            LastName  = "fuga"
        };

        var bytes = MessagePackSerializer.Serialize(mc);
        var mc2   = MessagePackSerializer.Deserialize <MyClass>(bytes);

        print(bytes);
        var json = MessagePackSerializer.ToJson(bytes);

        var d = MessagePackSerializer.Deserialize <MyClass>(MessagePackSerializer.FromJson(@"{""hoge"":""foo"",""huga"":2000}"));

        print(d);
    }
Beispiel #5
0
    void Awake()
    {
        // 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突


        object[] obj = luaEnv.DoString(FileUtils.ReadFileContent(luaScript), luaScript);
        if (obj != null && obj.Length > 0)
        {
            scriptEnv = obj[0] as LuaTable;
        }

        if (scriptEnv == null)
        {
            return;
        }
        print(obj.Length);
        var data = scriptEnv.GetInPath <LuaTable>("data");

        var result = LuaConvert.ConvertToObject(data);
        var ret    = MessagePackSerializer.ToJson(result);

        print(ret);

        var body = MessagePackSerializer.FromJson(ret);

        LogTool.Instance.ToStringAll(body);
        //            Action luaAwake = scriptEnv.Get<Action>("awake");
        scriptEnv.Get("start", out luaStart);
        scriptEnv.Get("update", out luaUpdate);
        scriptEnv.Get("ondestroy", out luaOnDestroy);
    }
Beispiel #6
0
        static Textures()
        {
            using (TextReader reader = new StreamReader(Game1.RootDirectory + TextureListPath))
            {
                var text             = reader.ReadToEnd();
                var bytes            = MessagePackSerializer.FromJson(text);
                var textureAtlasList = MessagePackSerializer.Deserialize <Dictionary <string, Dictionary <string, Texture> > >(bytes);

                foreach (var list in textureAtlasList)
                {
                    var textureAtlas = new TextureAtlas(list.Key);

                    if (list.Key == "floor_textures")
                    {
                        ushort identifier = 0;
                        foreach (var texture in list.Value)
                        {
                            FloorTextureIdentifiers.Add(identifier++, texture.Key);
                            textureAtlas.TextureList.Add(texture.Key, texture.Value);
                        }
                    }
                    else
                    {
                        foreach (var texture in list.Value)
                        {
                            textureAtlas.TextureList.Add(texture.Key, texture.Value);
                        }
                    }

                    GenerateTextureAtlas(textureAtlas);

                    AtlasList.Add(list.Key, textureAtlas);
                }
            }
        }
        //U
        //KRW		> KRW
        //KRW-COSM	> COSM
        public decimal GetMyInfo(UpbitAPI _U, string _coinCode)
        {
            string _currency   = _coinCode;
            string _headerWord = "KRW-";
            int    _headLenght = _headerWord.Length;

            //Console.WriteLine(_currency + " > " + _currency.IndexOf("KRW-") + ":" + _currency.Length);
            if (_currency.IndexOf("KRW-") >= 0)
            {
                _currency = _currency.Substring(_headLenght, _currency.Length - _headLenght);
            }
            //Console.WriteLine(_currency + " > " + _currency.IndexOf("KRW-"));

            //Console.WriteLine("\n\n\n================");
            //Console.WriteLine("개인:"+ _U.GetAccount());
            var orders = MessagePackSerializer.Typeless.Deserialize(MessagePackSerializer.FromJson(_U.GetAccount()));

            foreach (var o in orders as object[])
            {
                Dictionary <object, object> d = o as Dictionary <object, object>;
                //Console.WriteLine((string)d["currency"] + ":" + (string)d["balance"] + ":" + (string)d["locked"]);
                if ((string)d["currency"] == _currency)
                {
                    return(GetDicimal(d["balance"]));
                }
            }
            return(0m);
        }
Beispiel #8
0
 private void ProcessMessage(MessageEventArgs e)
 {
     System.Console.WriteLine(e.Data.Truncate(100));
     System.Threading.Tasks.Task.Run(() =>
     {
         try
         {
             var data = MessagePackSerializer.Deserialize <MessageData>(MessagePackSerializer.FromJson(e.Data));
             if (ClientComands.ContainsKey(data.Type))
             {
                 data = new ClientMessageData()
                 {
                     Type = data.Type,
                     data = System.Convert.FromBase64String(data.Data)
                 };
                 ClientComands[data.Type].Execute(data);
             }
             else
             {
                 if (WaitingResponse.TryRemove(data.mId, out MessageData original))
                 {
                     original.SendBack(data);
                 }
                 else
                 {
                     dev.Logger.Instance.Log($"received command with no request {data.Type}");
                 }
             }
         }
         catch (Exception ex)
         {
             dev.Logger.Instance.Error($"Could not execute client command {ex.Message} \n {ex.StackTrace} \n{ex.InnerException?.Message} {ex.InnerException?.StackTrace}");
         }
     }).ConfigureAwait(false);
 }
Beispiel #9
0
        public void Test_JsonToBytes()
        {
            MessagePackSerializer.SetDefaultResolver(MessagePack.Resolvers.ContractlessStandardResolver.Instance);
            var json  = FileUtil.Read("D:\\iTestRunner_R1.txt");
            var bytes = MessagePackSerializer.FromJson(json);

            FileUtil.Write("D:\\compression_result.txt", bytes);
        }
        private static SocketMessageData ParseData(string body)
        {
            var data = MessagePackSerializer.Deserialize <SocketMessageData>(MessagePackSerializer.FromJson(body));

            if (data.Data != null)
            {
                data.Data = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(data.Data));
            }
            return(data);
        }
Beispiel #11
0
 public byte[] GetBytes(object obj)
 {
     try
     {
         var json = JsonConvert.SerializeObject(obj);
         return(MessagePackSerializer.FromJson(json));
     }
     catch
     {
         return(null);
     }
 }
Beispiel #12
0
        public void DoSerialize()
        {
            // [10,20]
            Console.WriteLine(MessagePackSerializer.ToJson(new Sample1 {
                Foo = 10, Bar = 20
            }));

            // {"foo":10,"bar":20}
            Console.WriteLine(MessagePackSerializer.ToJson(new Sample2 {
                Foo = 10, Bar = 20
            }));
            var data = new Sample2 {
                Foo = 10, Bar = 20
            };
            var bin = MessagePackSerializer.Serialize(data);

            // バイナリから型にデシリアライズ
            var classObject = MessagePackSerializer.Deserialize <Sample2>(bin);
            // バイナリからdynamicにデシリアライズ
            var dynamicObject = MessagePackSerializer.Deserialize <dynamic>(bin);

            // {"Foo":10}
            // 文字列の方がコストかかるけれど、色がつく
            Console.WriteLine(MessagePackSerializer.ToJson(new Sample3 {
                Foo = 10, Bar = 20
            }));

            // Jsonからクラスにデシリアライズする。
            // Json生成
            var json = MessagePackSerializer.ToJson(new Sample2 {
                Foo = 10, Bar = 20
            });
            // こちらではエラー
//			var jsonByte = MessagePackSerializer.Serialize(json);
            // FromJsonでbyteを作る必要がある。
            var jsonByte            = MessagePackSerializer.FromJson(json);
            var classObjectFromJson = MessagePackSerializer.Deserialize <Sample2>(jsonByte);

            // attributeが文字列ではなく数字の場合
            var json2 = MessagePackSerializer.ToJson(new Sample1 {
                Foo = 10, Bar = 20
            });
            // 生成されるbyteが半分
            var jsonByte2            = MessagePackSerializer.FromJson(json2);
            var classObjectFromJson2 = MessagePackSerializer.Deserialize <Sample1>(jsonByte2);



            // 番外編 キーで指定した個所に保持されてしまう。
            // [null,null,null,0,null,null,null,null,null,null,0]
            Console.WriteLine(MessagePackSerializer.ToJson(new IntKeySample()));
        }
Beispiel #13
0
        // Creates and adds entity to EntityManager from input text
        public static T Deserialize <T>(string input) where T : Entity
        {
            var lines      = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var entityLine = lines[0];

            var entity = MessagePackSerializer.Deserialize <T>(MessagePackSerializer.FromJson(entityLine));

            Global.EntityManager.AddEntity(entity);

            lines.RemoveAt(0);
            SharedDeserializeLogic(entity, lines.ToArray());
            return(entity);
        }
Beispiel #14
0
            public override bool TryGet <TValue>(string key, out TValue obj)
            {
                obj = default(TValue);
                if (!_data.TryGetValue(key, out var val))
                {
                    return(false);
                }

                var bytes = MessagePackSerializer.FromJson(val);

                obj = MessagePackSerializer.Deserialize <TValue>(bytes);
                return(true);
            }
Beispiel #15
0
        static Fonts()
        {
            using (TextReader reader = new StreamReader(Game1.RootDirectory + FontListPath))
            {
                var text  = reader.ReadToEnd();
                var bytes = MessagePackSerializer.FromJson(text);

                FontList = MessagePackSerializer.Deserialize <Dictionary <string, Dictionary <string, Font> > >(bytes);

                foreach (var fonts in FontList)
                {
                    Console.WriteLine("Retrieved " + fonts.Value.Count + " Fonts from " + FontListPath + ":" + fonts.Key);
                }
            }
        }
Beispiel #16
0
 /// <summary>
 /// 序列化json字符串为Byte[]
 /// </summary>
 /// <param name="jsonStr"></param>
 /// <returns></returns>
 public byte[] SerializesJsonString(string jsonStr)
 {
     if (jsonStr == null)
     {
         return(default(byte[]));
     }
     try
     {
         return(MessagePackSerializer.FromJson(jsonStr));
     }
     catch (Exception e)
     {
         _logger.LogError($"序列化对象失败:{e.Message}");
     }
     return(default(byte[]));
 }
Beispiel #17
0
        /// <inheritdoc />
        public async Task <MachineStatus <TState, TInput> > GetMachineStatusAsync(
            string machineId,
            CancellationToken cancellationToken = default)
        {
            if (machineId == null)
            {
                throw new ArgumentNullException(nameof(machineId));
            }

            var machineRecord = await DbContext.Machines
                                .Include(machine => machine.MetadataEntries)
                                .Include(machine => machine.StateBagEntries)
                                .SingleOrDefaultAsync(
                status => status.MachineId == machineId,
                cancellationToken).ConfigureAwait(false);

            if (machineRecord == null)
            {
                throw new MachineDoesNotExistException(machineId);
            }

            var schematic = LZ4MessagePackSerializer.Deserialize <Schematic <TState, TInput> >(
                bytes: machineRecord.SchematicBytes,
                resolver: ContractlessStandardResolver.Instance);

            var state = MessagePackSerializer.Deserialize <TState>(
                bytes: MessagePackSerializer.FromJson(machineRecord.StateJson),
                resolver: ContractlessStandardResolver.Instance);

            var metadata = machineRecord.MetadataEntries
                           .ToDictionary(entry => entry.Key, entry => entry.Value);

            var stateBag = machineRecord.StateBagEntries
                           .ToDictionary(entry => entry.Key, entry => entry.Value);

            return(new MachineStatus <TState, TInput>
            {
                MachineId = machineId,
                Schematic = schematic,
                State = state,
                Metadata = metadata,
                CommitNumber = machineRecord.CommitNumber,
                UpdatedTime = machineRecord.UpdatedTime,
                StateBag = stateBag
            });
        }
Beispiel #18
0
        /// <summary>
        /// Retrieves the record for a Machine Status.
        /// </summary>
        /// <param name="machineId">The Id of the Machine</param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="machineId"/> is null.</exception>
        /// <exception cref="MachineDoesNotExistException">Thrown when no matching MachineId was found.</exception>
        public async Task <MachineStatus <TState, TInput> > GetMachineStatusAsync(
            string machineId,
            CancellationToken cancellationToken = default)
        {
            if (machineId == null)
            {
                throw new ArgumentNullException(nameof(machineId));
            }

            var machineRecord = await DbContext.Machines
                                .SingleOrDefaultAsync(
                status => status.MachineId == machineId,
                cancellationToken).ConfigureAwait(false);

            if (machineRecord == null)
            {
                throw new MachineDoesNotExistException(machineId);
            }

            var schematic = MessagePackSerializer.Deserialize <Schematic <TState, TInput> >(
                bytes: MessagePackSerializer.FromJson(machineRecord.SchematicJson),
                resolver: ContractlessStandardResolver.Instance);

            var state = MessagePackSerializer.Deserialize <TState>(
                bytes: MessagePackSerializer.FromJson(machineRecord.StateJson),
                resolver: ContractlessStandardResolver.Instance);

            IDictionary <string, string> metadata = null;

            if (machineRecord.MetadataJson != null)
            {
                metadata = MessagePackSerializer.Deserialize <IDictionary <string, string> >(
                    bytes: MessagePackSerializer.FromJson(machineRecord.MetadataJson));
            }

            return(new MachineStatus <TState, TInput>
            {
                MachineId = machineId,
                Schematic = schematic,
                State = state,
                Metadata = metadata,
                CommitNumber = machineRecord.CommitNumber,
                UpdatedTime = machineRecord.UpdatedTime
            });
        }
Beispiel #19
0
            public override Task SendBack(MessageData data, bool cache = true)
            {
                try
                {
                    if (source.TrySetResult(MessagePackSerializer.Deserialize<TRes>(MessagePackSerializer.FromJson(data.Data))))
                    { /* nothing to do, already set */ }
                }
                catch (Exception)
                {
                    // thrown excpetion, looks like it isn't messagepack
                    if (source.TrySetResult(JsonConvert.DeserializeObject<TRes>(data.Data)))
                    { /* nothing to do, already set */ }
                }

                if (cache)
                    CacheService.Instance.Save(this, data, 0);
                return Task.CompletedTask;
            }
Beispiel #20
0
        public static void init()
        {
            Dir.create(Application.dataPath + _filename);
            _save_file.reset(_filename, "");

            var str = _save_file.read();

            Debug.Log("PlayerPrefsAlt.init() : str.Length : " + str.Length.ToString());
            Debug.Log("PlayerPrefsAlt.init() : str : " + str);

            if (0 < str.Length)
            {
                //_save_data = JsonUtility.FromJson<Dictionary<string, string>>(str);
                _save_data = MessagePackSerializer.Deserialize <Dictionary <string, string> >(
                    MessagePackSerializer.FromJson(str)
                    );
            }
        }
        public void OrderCancel(UpbitAPI _U, string _coinCode, OrderKind _orderKind = OrderKind.BuyCancel)
        {
            //특정코인만 주문취소하기...
            //string coinCode = "KRW-TT";
            //string orderkind = "bid";//bid : 매수, ask : 매도

            var orders = MessagePackSerializer.Typeless.Deserialize(MessagePackSerializer.FromJson(_U.GetAllOrder()));

            switch (_orderKind)
            {
            case OrderKind.BuyCancel:
                foreach (var o in orders as object[])
                {
                    Dictionary <object, object> d = o as Dictionary <object, object>;
                    if ((string)d["market"] == _coinCode && (string)d["side"] == "bid")
                    {
                        Console.WriteLine(_U.CancelOrder((string)d["uuid"]));
                    }
                }
                break;

            case OrderKind.SellCancel:
                foreach (var o in orders as object[])
                {
                    Dictionary <object, object> d = o as Dictionary <object, object>;
                    if ((string)d["market"] == _coinCode && (string)d["side"] == "ask")
                    {
                        Console.WriteLine(_U.CancelOrder((string)d["uuid"]));
                    }
                }
                break;

            case OrderKind.AllCancel:
                foreach (var o in orders as object[])
                {
                    Dictionary <object, object> d = o as Dictionary <object, object>;
                    if ((string)d["market"] == _coinCode)
                    {
                        Console.WriteLine(_U.CancelOrder((string)d["uuid"]));
                    }
                }
                break;
            }
        }
Beispiel #22
0
 public virtual T GetAs <T>()
 {
     if (String.IsNullOrEmpty(Data))
     {
         return(default(T));
     }
     try
     {
         return(MessagePackSerializer.Deserialize <T>(MessagePackSerializer.FromJson(Data)));
     }
     catch (Exception)
     {
         if (typeof(T) == typeof(string))
         {
             return((T)(object)Convert.ToBase64String(Encoding.UTF8.GetBytes(Data)));
         }
         throw;
     }
 }
Beispiel #23
0
            public override bool Load()
            {
                string path = _config.FilePath;

                if (!File.Exists(path))
                {
                    return(false);
                }
                string content = File.ReadAllText(path);

                if (string.IsNullOrEmpty(content))
                {
                    return(false);
                }
                var bytes = MessagePackSerializer.FromJson(content);
                var data  = MessagePackSerializer.Deserialize <object>(bytes) as Dictionary <object, object>;

                _data = data.ToDictionary(x => x.Key.ToString(), x => x.Value.ToString());

                return(true);
            }
        /// <summary>
        /// APIキーを使用したGoogleスプレッドシートの取得
        /// </summary>
        public static IEnumerator LoadCoroutine()
        {
            _isLoading = true;
            _isSuccess = false;

            var api = "https://sheets.googleapis.com/v4/spreadsheets/" + Settings.SheetId + "/values/" + Settings.Range + "?key=" +
                      Settings.ApiKey;

            using (var request = UnityWebRequest.Get(api))
            {
                yield return(request.SendWebRequest());

                if (request.isHttpError)
                {
                    Debug.LogErrorFormat("【HTTP Error】");
                    Debug.LogErrorFormat("{0}", request.downloadHandler.text);
                    _isLoading = false;
                    _isSuccess = false;
                    yield break;
                }

                if (request.isNetworkError)
                {
                    Debug.LogErrorFormat("【Network Error】");
                    Debug.LogErrorFormat("{0}", request.downloadHandler.text);
                    _isLoading = false;
                    _isSuccess = false;
                    yield break;
                }

                var json  = request.downloadHandler.text; // Googleスプレッドシートから取得してきたJSON
                var bytes = MessagePackSerializer.FromJson(json);
                _sheet      = MessagePackSerializer.Deserialize <SpreadSheet>(bytes);
                _dictionary = _sheet.Values.ToDictionary(item => item[0], item => item); // 左のセルをキーとするDictionaryを作成

                _isLoading = false;
                _isSuccess = true;
            }
        }
Beispiel #25
0
        // Restores components in this entity from string, make sure entity is added to EntityManager
        private void DeserializeComponents(string[] componentLines)
        {
            int lineCount = 0;

            if (HasComponent <TransformComponent>())
            {
                Transform = MessagePackSerializer.Deserialize <TransformComponent>(MessagePackSerializer.FromJson(componentLines[lineCount++]));
            }
            if (HasComponent <PhysicsComponent>())
            {
                Physics = MessagePackSerializer.Deserialize <PhysicsComponent>(MessagePackSerializer.FromJson(componentLines[lineCount++]));
            }
            if (HasComponent <CollisionComponent>())
            {
                Collision = MessagePackSerializer.Deserialize <CollisionComponent>(MessagePackSerializer.FromJson(componentLines[lineCount++]));
            }
            if (HasComponent <MeshComponent>())
            {
                Mesh = MessagePackSerializer.Deserialize <MeshComponent>(MessagePackSerializer.FromJson(componentLines[lineCount++]));
            }

            // Try set component to default after deserializing to initialize properties that have to be initialized
            Mesh.TrySetDefaults();
        }
Beispiel #26
0
 public static TState ToState <TState>(this string stateRepresentation)
 {
     return(MessagePackSerializer.Deserialize <TState>(
                MessagePackSerializer.FromJson(stateRepresentation),
                ContractlessStandardResolver.Instance));
 }
Beispiel #27
0
 public static byte[] SerializeMsgPackViaJson(Type t, object value) =>
 MessagePackSerializer.FromJson(JsonConvert.SerializeObject(value, t,
                                                            TFCustomContractResolver.SerializationSettings));
Beispiel #28
0
        public static Entity Deserialize(string input)
        {
            var lines = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

            Type type;

            try
            {
                var typeLine = lines[0];
                type = Type.GetType(typeLine);
            }
            catch (Exception)
            {
                Logger.Error("Could not determine type from string:\n" + lines[0]);
                return(null);
            }

            var    entityLine = lines[1];
            Entity entity     = (Entity)MessagePackSerializer.NonGeneric.Deserialize(type, MessagePackSerializer.FromJson(entityLine));

            Global.EntityManager.AddEntity(entity);

            lines.RemoveAt(0);
            lines.RemoveAt(0);
            SharedDeserializeLogic(entity, lines.ToArray());
            return(entity);
        }
 string JsonConvert(string json)
 {
     return(MessagePackSerializer.ToJson(MessagePackSerializer.FromJson(json)));
 }
Beispiel #30
0
        // Creates and adds entity to EntityManager from input type and text
        public static Entity Deserialize(Type type, string input)
        {
            var lines      = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var entityLine = lines[0];

            Entity entity = (Entity)MessagePackSerializer.NonGeneric.Deserialize(type, MessagePackSerializer.FromJson(entityLine));

            Global.EntityManager.AddEntity(entity);

            lines.RemoveAt(0);
            SharedDeserializeLogic(entity, lines.ToArray());
            return(entity);
        }