Ejemplo n.º 1
0
        public IActionResult GetModel([FromBody] JsonDict jsonDict)
        {
            string modelId = jsonDict["modelId"].ToString();
            var    model   = eqService.GetModel(modelId);

            return(Json(model.SaveToJsonDict()));
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Provides the handler for AJAX calls. Pass this to a <see cref="UrlMapping"/>.</summary>
        /// <param name="req">
        ///     The incoming HTTP POST request to be handled, containing the API function name and parameters.</param>
        /// <param name="api">
        ///     The API object on which the API function is to be invoked.</param>
        public HttpResponse Handle(HttpRequest req, TApi api)
        {
            if (_options == AjaxHandlerOptions.PropagateExceptions)
            {
                return(callApiFunction(req, api));
            }

            try
            {
                return(callApiFunction(req, api));
            }
            catch (Exception e)
            {
                while (e is TargetInvocationException)
                {
                    e = e.InnerException;
                }

                var error = new JsonDict {
                    { "status", "error" }
                };
                if (_options == AjaxHandlerOptions.ReturnExceptionsWithMessages)
                {
                    error.Add("message", "{0} ({1})".Fmt(e.Message, e.GetType().Name));
                }
                return(HttpResponse.Json(error));
            }
        }
Ejemplo n.º 3
0
        public static HairStyle CreateFromSavedJson(JSONNode aJson)
        {
            HairStyle newHair = null;

            if (aJson["savedByPlugin"].Value == HairStylist.pluginName)
            {
                newHair = new HairStyle();

                foreach (JSONClass storableNode in aJson["storables"].AsArray)
                {
                    string   saveGroup = storableNode["storableName"];
                    JsonDict groupDict = new JsonDict();
                    foreach (JSONClass paramNode in storableNode["params"].AsArray)
                    {
                        groupDict.Add(paramNode["id"], paramNode.AsObject);
                    }
                    newHair._savedJson[saveGroup] = groupDict;
                }
            }
            else
            {
                SuperController.LogError("Saved file was not created by HairStylist");
            }
            return(newHair);
        }
Ejemplo n.º 4
0
        public override HttpResponse Handle(HttpRequest req)
        {
            if (req.Headers.ContainsKey("SIMPLEDBADD"))
            {
                if (req.Headers["SIMPLEDBADD"] == "TRUE")
                {
                    count++;
                }
            }

            if (req.Headers.ContainsKey("SIMPLEDBSUB"))
            {
                if (req.Headers["SIMPLEDBSUB"] == "TRUE")
                {
                    count--;
                }
            }
            if (count < 0)
            {
                count = 0;
            }

            var dict = new JsonDict();

            dict.Add("Count", JsonNumber.Create(count));
            return(HttpResponse.Json(dict));
        }
Ejemplo n.º 5
0
        public JsonDict ToJson()
        {
            var dict = new JsonDict();

            // Strings
            if (HumanReadable != null)
            {
                dict["HumanReadable"] = HumanReadable;
            }
            if (Icon != null)
            {
                dict["Icon"] = Icon;
            }
            if (PropName != null)
            {
                dict["PropName"] = PropName;
            }

            // Functions
            if (UrlFunction != null)
            {
                dict["UrlFunction"] = new JsonRaw(UrlFunction);
            }
            if (ShowIconFunction != null)
            {
                dict["ShowIconFunction"] = new JsonRaw(ShowIconFunction);
            }

            return(dict);
        }
Ejemplo n.º 6
0
        public WdTurret(string id, JsonDict turret, WdData data)
        {
            Raw  = turret;
            Id   = id;
            Name = data.ResolveString(turret["userString"].WdString());

            Level          = turret["level"].WdInt();
            Price          = turret["price"].WdInt();
            Mass           = turret["weight"].WdInt();
            HitPoints      = turret["maxHealth"].WdInt();
            RotationSpeed  = turret["rotationSpeed"].WdDecimal();
            VisionDistance = turret["circularVisionRadius"].WdDecimal();

            try
            {
                var armor = turret["primaryArmor"].WdString().Split(' ').Select(s => turret["armor"][s].WdDecimal()).ToArray();
                ArmorThicknessFront = armor[0];
                ArmorThicknessSide  = armor[1];
                ArmorThicknessBack  = armor[2];
            }
            catch
            {
                ArmorThicknessFront = ArmorThicknessSide = ArmorThicknessBack = 0;
            }

            Guns = new List <WdGun>();
        }
Ejemplo n.º 7
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SignUp, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ArraySegmentWrapper segmentWrapper = null;
            ResultInfo <User>   result         = null;

            try
            {
                //解析Json字符串
                var    json  = JsonDict.Parse(content);
                string name  = json["Name"];
                string email = json["Email"];
                string pwd   = json["Pwd"];
                //数据库验证
                result = BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SignUp(name, email, pwd);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <User>(ex);
            }

            //发送注册响应消息
            segmentWrapper = new ArraySegmentWrapper(Constants.SIGNUP_RESPONSE_KEY, JConverter.SerializeToBytes(result));
            session.SendData(session, segmentWrapper.Wrapper());
        }
Ejemplo n.º 8
0
        public override TypeHandler Serialize(Lexicon input)
        {
            var data   = new JsonDict();
            var keys   = new JsonList();
            var values = new JsonList();

            foreach (var kvp in input.Select(x => new KeyValuePair <object, object>(serializer.Serialize(x.Key), serializer.Serialize(x.Value))))
            {
                if (kvp.Key is string)
                {
                    data[(string)kvp.Key] = kvp.Value;
                }
                else
                {
                    keys.Add(kvp.Key);
                    values.Add(kvp.Value);
                }
            }
            this["data"]   = data;
            this["keys"]   = keys;
            this["values"] = values;
            if ((BooleanValue)input.GetSuffix("CASESENSITIVE").Value)
            {
                this["sensitive"] = true;
            }
            else
            {
                this.Remove("sensitive");
            }
            return(this);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="session"></param>
        /// <param name="segment"></param>
        internal void SendData(ChatSession session, ArraySegment <byte> segment)
        {
            try
            {
                int count            = segment.Count;
                int maxRequestLength = AppConfiger.AppCfg.CurrCC_Cfg.MaxRequestLength;
                if (count > maxRequestLength)
                {
                    int offset = 0;
                    while (offset < count)
                    {
                        session.Send(segment.Array, offset, Math.Min(maxRequestLength, count - offset));

                        offset += maxRequestLength;
                    }
                }
                else
                {
                    session.Send(segment);
                }
            }
            catch (Exception ex)
            {
                var json = new JsonDict();
                json.Add("SessionID", session.SessionID);
                json.Add("Msg", string.Format("{0} 发送数据异常,异常信息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message));
                ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.ERROR_RESPONSE_KEY, json.ToBytes());
                session.Send(segmentWrapper.Wrapper());
            }
        }
Ejemplo n.º 10
0
        public WdChassis(string id, JsonDict chassis, WdData data)
        {
            Raw  = chassis;
            Id   = id;
            Name = data.ResolveString(chassis["userString"].WdString());

            Level         = chassis["level"].WdInt();
            Price         = chassis["price"].WdInt();
            Mass          = chassis["weight"].WdInt();
            HitPoints     = chassis["maxHealth"].WdInt();
            MaxLoad       = chassis["maxLoad"].WdInt();
            MaxClimbAngle = chassis["maxClimbAngle"].WdInt();
            RotationSpeed = chassis["rotationSpeed"].WdInt();

            var leftTrack  = chassis["armor"]["leftTrack"].WdInt();
            var rightTrack = chassis["armor"]["rightTrack"].WdInt();

            TrackArmorThickness = Math.Max(leftTrack, rightTrack);

            var terr = chassis["terrainResistance"].WdString().Split(' ').Select(s => decimal.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture)).ToList();

            TerrainResistanceFirm   = terr[0];
            TerrainResistanceMedium = terr[1];
            TerrainResistanceSoft   = terr[2];
        }
Ejemplo n.º 11
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SaveContacts, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo result = null;

            try
            {
                //解析Json字符串
                var    json       = JsonDict.Parse(content);
                long   oUserId    = json.GetLong("OUserId");
                long   cUserId    = json.GetLong("CUserId");
                string customName = json["CustomName"];

                result = BizManager.AutofacBootstrapper.Resolve <IContactsBiz>().Save(oUserId, cUserId, customName);
            }
            catch (Exception ex)
            {
                result = new ResultInfo(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SAVE_CONTACTS_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Ejemplo n.º 12
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SearchUser, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <IEnumerable <User> > result = null;

            try
            {
                //解析Json字符串
                var    json    = JsonDict.Parse(content);
                string account = json["Account"];

                result = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().SearchUser(account);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <IEnumerable <User> >(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SEARCH_USER_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Ejemplo n.º 13
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: GetContacts, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <IEnumerable <Contacts> > result = null;

            try
            {
                //解析Json字符串
                var    json     = JsonDict.Parse(content);
                long   oUserId  = json.GetLong("OUserId");
                string keyword  = json["Keyword"];
                int    pageNum  = json.GetInt("PageNum");
                int    pageSize = json.GetInt("PageSize");

                result = BizManager.AutofacBootstrapper.Resolve <IContactsBiz>().GetDatas(oUserId, keyword, keyword, keyword, keyword, keyword, pageNum, pageSize);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <IEnumerable <Contacts> >(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.GET_CONTACTS_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Ejemplo n.º 14
0
        public static JsonDict GetDictAndRemove(this JsonDict json, string key)
        {
            var result = json[key].GetDict();

            json.Remove(key);
            return(result);
        }
Ejemplo n.º 15
0
        public static bool GetBoolAndRemove(this JsonDict json, string key)
        {
            var result = json[key].GetBool();

            json.Remove(key);
            return(result);
        }
Ejemplo n.º 16
0
 public static void EnsureEmpty(this JsonDict json)
 {
     if (json.Count > 0)
     {
         throw new Exception();
     }
 }
Ejemplo n.º 17
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: Talk, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <Message> result = null;
            long toUId = 0L;

            try
            {
                //解析Json字符串
                var  json    = JsonDict.Parse(content);
                long fromUId = json.GetLong("FromUId");
                toUId = json.GetLong("ToUId");
                string msg = json["Content"];

                result = BizManager.AutofacBootstrapper.Resolve <IMessageBiz>().Save(fromUId, toUId, msg);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <Message>(ex);
            }

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.TALK_RESPONSE_KEY, JConverter.SerializeToBytes(result));
            var s = session.AppServer.GetSessions(o => o.User?.Id == toUId).FirstOrDefault();

            session.SendData(s, segmentWrapper.Wrapper());
        }
        /// <summary>
        /// Gets the list of saved queries
        /// </summary>
        /// <param name="jsonDict">The JsonDict object which contains request parameters</param>
        /// <returns>IActionResult object</returns>
        public JsonResult GetQueryList([FromBody] JsonDict jsonDict)
        {
            string modelId = jsonDict["modelId"].ToString();
            var    queries = eqService.GetQueryList(modelId);

            return(Json(queries));
        }
Ejemplo n.º 19
0
        internal Game(JsonDict json, SummonerInfo summoner)
        {
            Summoner = summoner;
            Id       = json["gameId"].GetLong().ToString();
            Queue    = Queues.GetInfo(json["queueId"].GetInt());
            if (Queue.Id != 0 /* Custom */) // this is the only queue type for which the map can't be inferred from the queue, but we don't care about those games when computing personal stats
            {
                Ut.Assert((int)Queue.Map == json["mapId"].GetInt());
            }
            DetailsUrl = "http://matchhistory.{0}.leagueoflegends.com/en/#match-details/{1}/{2}/{3}".Fmt(summoner.Region.ToLower(), summoner.RegionServer, Id, summoner.AccountId);
            DateUtc    = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + TimeSpan.FromSeconds(json["gameCreation"].GetLong() / 1000.0);
            Duration   = TimeSpan.FromSeconds(json["gameDuration"].GetInt());

            var teams =
                (from team in json["teams"].GetList()
                 let participants = json["participants"].GetList().Where(p => p["teamId"].GetInt() == team["teamId"].GetInt()).ToDictionary(p => p["participantId"].GetInt())
                                    let identities = json["participantIdentities"].GetList().Where(pi => participants.ContainsKey(pi["participantId"].GetInt())).ToDictionary(pi => pi["participantId"].GetInt())
                                                     select new Team(team, participants, identities, this)
                ).ToList();

            Ut.Assert(teams.Count == 2);

            Ally  = teams.Single(t => t.Players.Any(p => p.SummonerId == summoner.SummonerId));
            Enemy = teams.Single(t => t != Ally);
        }
Ejemplo n.º 20
0
        private void assertDictParseFail(string json)
        {
            Assert.Throws <JsonParseException>(() => JsonDict.Parse(json));
            JsonDict val;

            Assert.IsFalse(JsonDict.TryParse(json, out val));
            Assert.IsNull(val);
        }
Ejemplo n.º 21
0
 private void assertHasParticipantIdentities(JsonDict json)
 {
     if (!json["participantIdentities"].GetList().All(id => id.ContainsKey("participantId") && id.ContainsKey("player") && id["player"].ContainsKey("summonerName") &&
                                                      (id["player"].ContainsKey("summonerId") || id["player"].Safe["accountId"].GetIntSafe() == 0)))
     {
         throw new Exception("Match history JSON does not contain all participant identities.");
     }
 }
Ejemplo n.º 22
0
        public IActionResult NewQuery([FromBody] JsonDict jsonDict)
        {
            string   queryName = jsonDict["queryName"].ToString();
            JsonDict Temp      = new JsonDict();
            var      query     = eqService.SaveQueryDict(Temp, queryName);

            return(Json(query.SaveToJsonDict()));
        }
Ejemplo n.º 23
0
 public SucoEnvironment DecodeValues(string variablesJson)
 {
     if (_valuesCache == null || _valuesCacheVariables != variablesJson)
     {
         _valuesCacheVariables = variablesJson;
         _valuesCache          = ZingaUtil.ConvertVariableValues(JsonDict.Parse(variablesJson), JsonDict.Parse(ValuesJson));
     }
     return(_valuesCache);
 }
Ejemplo n.º 24
0
        private void assertDictParseSucc(string json, JsonDict expected)
        {
            JsonDict t = null;

            Assert.DoesNotThrow(() => { t = JsonDict.Parse(json); });
            Assert.IsTrue(expected.Equals(t));
            Assert.IsTrue(JsonDict.TryParse(json, out t));
            Assert.IsTrue(expected.Equals(t));
        }
Ejemplo n.º 25
0
        public WdCountry(string name, WdData data, JsonDict tanks, JsonDict engines, JsonDict guns, JsonDict radios, JsonDict shells)
        {
            Name = name;

            Engines = new Dictionary <string, WdEngine>();
            foreach (var kvp in engines["shared"].GetDict())
            {
                var engine = new WdEngine(kvp.Key, kvp.Value.GetDict(), data);
                Engines.Add(kvp.Key, engine);
            }

            Radios = new Dictionary <string, WdRadio>();
            foreach (var kvp in radios["shared"].GetDict())
            {
                var radio = new WdRadio(kvp.Key, kvp.Value.GetDict(), data);
                Radios.Add(kvp.Key, radio);
            }

            Shells = new Dictionary <string, WdShell>();
            foreach (var kvp in shells.GetDict())
            {
                if (kvp.Key == "icons")
                {
                    continue;
                }
                var shell = new WdShell(kvp.Key, kvp.Value.GetDict(), data);
                Shells.Add(kvp.Key, shell);
            }

            Guns = new Dictionary <string, WdGun>();
            foreach (var kvp in guns["shared"].GetDict())
            {
                try
                {
                    var gun = new WdGun(kvp.Key, kvp.Value.GetDict(), data, this);
                    Guns.Add(kvp.Key, gun);
                }
                catch
                {
                    data.Warnings.Add("Could not load gun data for gun “{0}”".Fmt(kvp.Key));
                }
            }

            Tanks   = new Dictionary <string, WdTank>();
            Chassis = new Dictionary <string, WdChassis>();
            Turrets = new Dictionary <string, WdTurret>();
            foreach (var kvp in tanks.GetDict())
            {
                if (Name == "usa" && kvp.Key == "Sexton_I")
                {
                    continue; // this tank is weird; it's the only one which has non-"shared" modules with identical keys to another tank. Ignore it.
                }
                var tank = new WdTank(kvp.Key, kvp.Value.GetDict(), this, data);
                Tanks.Add(tank.RawId, tank);
            }
        }
Ejemplo n.º 26
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: DownloadAvatar, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <Tuple <long, byte[]> > result = null;

            try
            {
                //解析Json字符串
                var  json   = JsonDict.Parse(content);
                long userId = json.GetLong("UserId");

                var result2 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().FindById(userId);
                if (result2.Success)
                {
                    if (!string.IsNullOrEmpty(result2.RData.Avatar))
                    {
                        byte[] data = null;
                        using (FileStream fs = new FileStream(result2.RData.Avatar, FileMode.Open))
                        {
                            data = new byte[fs.Length];
                            fs.Read(data, 0, data.Length);
                        }
                        result = new ResultInfo <Tuple <long, byte[]> >()
                        {
                            RMsg = "下载用户头像成功", RData = new Tuple <long, byte[]>(userId, data)
                        };
                    }
                    else
                    {
                        result = new ResultInfo <Tuple <long, byte[]> >()
                        {
                            RCode = "1001", RMsg = "用户尚未设置头像", Success = false
                        };
                    }
                }
                else
                {
                    result = new ResultInfo <Tuple <long, byte[]> >()
                    {
                        RCode = "1002", RMsg = "用户不存在,下载用户头像失败", Success = false
                    };
                }
            }
            catch (Exception ex)
            {
                result = new ResultInfo <Tuple <long, byte[]> >(ex);
            }

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.DOWNLOAD_AVATAR_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Ejemplo n.º 27
0
        private void ensureModuleInfoCache()
        {
            if (_moduleInfoCache == null)
            {
                lock (this)
                    if (_moduleInfoCache == null)
                    {
                        const int cols = 20; // number of icons per row
                        const int w    = 32; // width of an icon in pixels
                        const int h    = 32; // height of an icon in pixels

                        var iconFiles = new DirectoryInfo(_config.ModIconDir).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray();
                        var rows      = (iconFiles.Length + cols - 1) / cols;
                        var coords    = new Dictionary <string, (int x, int y)>();

                        using (var bmp = new Bitmap(w * cols, h * rows))
                        {
                            using (var g = Graphics.FromImage(bmp))
                            {
                                for (int i = 0; i < iconFiles.Length; i++)
                                {
                                    using (var icon = new Bitmap(iconFiles[i].FullName))
                                        g.DrawImage(icon, w * (i % cols), h * (i / cols));
                                    coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols));
                                }
                            }
                            using (var mem = new MemoryStream())
                            {
                                bmp.Save(mem, ImageFormat.Png);
                                _moduleInfoCache = new ModuleInfoCache {
                                    IconSpritePng = mem.ToArray()
                                };
                                _moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(_moduleInfoCache.IconSpritePng).ToHex();

                                var modules = new DirectoryInfo(_config.ModJsonDir)
                                              .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly)
                                              .ParallelSelect(4, file =>
                                {
                                    try
                                    {
                                        var origFile = File.ReadAllText(file.FullName);
                                        var modJson  = JsonDict.Parse(origFile);
                                        var mod      = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson);

#if DEBUG
                                        var newJson    = (JsonDict)ClassifyJson.Serialize(mod);
                                        var newJsonStr = newJson.ToStringIndented();
                                        if (newJsonStr != origFile)
                                        {
                                            File.WriteAllText(file.FullName, newJsonStr);
                                        }
                                        modJson = newJson;
#endif

                                        return((modJson, mod, file.LastWriteTimeUtc).Nullable());
                                    }
Ejemplo n.º 28
0
        public void DownloadAvatar(long userId)
        {
            var json = new JsonDict();

            json.AddLong("UserId", userId);

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.DOWNLOAD_AVATAR_REQUEST_KEY, JConverter.SerializeToBytes(json));

            this.Send(segmentWrapper);
        }
Ejemplo n.º 29
0
        public void SearchUser(string account)
        {
            var json = new JsonDict();

            json.Add("Account", account);

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SEARCH_USER_REQUEST_KEY, json.ToBytes());

            this.Send(segmentWrapper);
        }
Ejemplo n.º 30
0
        public static SucoEnvironment ConvertVariableValues(JsonDict variablesJson, JsonDict valuesJson)
        {
            var list = new List <(string name, object value)>();

            foreach (var(varName, varType) in variablesJson)
            {
                list.Add((varName, convertVariableValue(SucoType.Parse(varType.GetString()), valuesJson[varName])));
            }
            return(new SucoEnvironment(list));
        }
Ejemplo n.º 31
0
 private void assertDictParseSucc(string json, JsonDict expected)
 {
     JsonDict t = null;
     Assert.DoesNotThrow(() => { t = JsonDict.Parse(json); });
     Assert.IsTrue(expected.Equals(t));
     Assert.IsTrue(JsonDict.TryParse(json, out t));
     Assert.IsTrue(expected.Equals(t));
 }
Ejemplo n.º 32
0
        public void TestJsonComplexAndToString()
        {
            var constructed = new JsonDict
            {
                { "thingy", 47 },
                { "stuff", 47.1 },
                { "bla", null },
                { "sub", new JsonDict
                {
                    { "wah", "gah" },
                    { "em", new JsonList { } },
                    { "fu", new JsonList { 1, null, new JsonDict { { "wow", new JsonDict { } } }, "2" } }
                } },
                { "more", true }
            };

            JsonValue parsed = null;
            Assert.DoesNotThrow(() => { parsed = JsonValue.Parse("{  \"bla\": null, \"stuff\": 47.1, \"more\": true, \"sub\": { \"em\": [], \"fu\": [1, null, { \"wow\": {} }, \"2\"], \"wah\": \"gah\" }, \"thingy\": 47 }"); });
            Assert.IsNotNull(parsed);

            JsonValue reparsed = null;
            Assert.DoesNotThrow(() => { reparsed = JsonValue.Parse(parsed.ToString()); });
            Assert.IsNotNull(reparsed);

            JsonValue reparsed2 = null;
            Assert.DoesNotThrow(() => { reparsed2 = JsonValue.Parse(constructed.ToString()); });
            Assert.IsNotNull(reparsed2);

            Assert.IsTrue(parsed.Equals(constructed));
            Assert.IsTrue(parsed.Equals(reparsed));
            Assert.IsTrue(constructed.Equals(reparsed2));
        }