public void Init(SimpleJson.JsonObject o)
    {
        this.id = Convert.ToInt32(o ["id"]);
        this.name = Convert.ToString(o ["name"]);
        this.level = Convert.ToInt32(o ["level"]);
        this.limitId = Convert.ToInt32(o ["limitId"]);
        this.limitTimes = Convert.ToInt32(o ["limitTimes"]);
        this.start = Convert.ToInt32(o ["start"]);
        this.end = Convert.ToInt32(o ["end"]);
        this.mechanism = (TaskMechanism)Convert.ToInt32(o ["mechanism"]);
        this.groupId = Convert.ToInt32(o ["groupId"]);
        this.cmpType = Convert.ToInt32(o ["type"]);
        this.objective = Convert.ToInt32(o ["objective"]);
        this.seekId1 = Convert.ToInt32(o ["seekId1"]);
        this.seekId2 = Convert.ToInt32(o ["seekId2"]);
        this.seekId3 = Convert.ToInt32(o ["seekId3"]);

        this.next = Convert.ToInt32(o ["continue"]);

        this.amount = Convert.ToInt32(o ["amount"]);
        this.depict = Convert.ToString(o ["depict"]);
        this.desc = Convert.ToString(o ["desc"]);
        this.exp = Convert.ToInt32(o ["exp"]);
        this.armorExp = Convert.ToInt32(o["armorExp"]);
        this.money = Convert.ToInt32(o ["money"]);
        this.props = Convert.ToInt32(o ["props"]);

        this.chapterGroup = Convert.ToInt32(o ["section"]);
        this.dungeon = Convert.ToInt32(o ["dungeon"]);
        //this.giveup = Convert.ToInt32(o["giveup"]);
    }
 public void Init(SimpleJson.JsonObject o)
 {
     this.id = Convert.ToInt32(o["id"]);
     this.uiId = Convert.ToInt32(o["uiId"]);
     this.uiName = Convert.ToString(o["uiName"]);
     this.uiLevel = Convert.ToInt32(o["uiLevel"]);
 }
	public void Init (SimpleJson.JsonObject obj)
	{
		direction = Convert.ToSingle (obj ["direction"]);
		id = Convert.ToInt32 (obj ["id"]);
		posType = Convert.ToInt32 (obj ["posType"]);
		pos = Utility.GetMapObjectPos ((string)obj ["posValue"]);
        
		monsterId = Convert.ToInt32 (obj ["monsterId"]);
		name = Convert.ToString (obj ["name"]);
		levelType = Convert.ToInt32 (obj ["levelType"]);
		minLevel = Convert.ToInt32 (obj ["minLevel"]);
		maxLevel = Convert.ToInt32 (obj ["maxLevel"]);
		liveTime = Convert.ToInt32 (obj ["liveTime"]);
		mapId = Convert.ToInt32 (obj ["mapId"]);
		skinId = Convert.ToInt32 (obj ["skinId"]);
		mkId = Convert.ToInt32 (obj ["mkId"]);
		signId = Convert.ToInt32 (obj ["signId"]);
		minRetime = Convert.ToInt32 (obj ["minRetime"]);
		maxRetime = Convert.ToInt32 (obj ["maxRetime"]);
		refreshType = (MonsterRefreshType)Convert.ToInt32 (obj ["refreshType"]);
		refreshRadius = Convert.ToInt32 (obj ["refreshRadius"]);
		refreshId = Convert.ToInt32 (obj ["refreshId"]);
		script = Convert.ToInt32 (obj ["script"]);   
		obstruct = Convert.ToInt32 (obj ["obstruct"]);
		runaway = Convert.ToInt32 (obj ["runaway"]);
	}
Example #4
0
 public SimpleJson GetJSON()
 {
     SimpleJson json = new SimpleJson()
         .Add("parent", this.ProvinceId)
         .Add("type", "c")
         .Add("id", this.CityId)
         .Add("code", this.CityCode)
         .Add("name", this.Name)
         .Add("desc", this);
     return json;
 }
Example #5
0
 public static SimpleJson GetJSON(ISession session, int id)
 {
     City city = City.Retrieve(session, id);
     if (city == null) return new SimpleJson().HandleError(string.Format("城市{0}不存在", id));
     SimpleJson json = new SimpleJson()
         .Add("parent", city.ProvinceId)
         .Add("type", "c")
         .Add("id", city.CityId)
         .Add("code", city.CityCode)
         .Add("name", city.Name)
         .Add("desc", city);
     return json;
 }
Example #6
0
 public static SimpleJson GetJSON(ISession session, int id)
 {
     Province pro = Province.Retrieve(session, id);
     if (pro == null) return new SimpleJson().HandleError(string.Format("省份{0}不存在", id));
     SimpleJson json = new SimpleJson()
         .Add("parent", "")
         .Add("type", "p")
         .Add("id", pro.ProvinceId)
         .Add("code", pro.Code)
         .Add("name", pro.Name)
         .Add("alias", pro.Alias)
         .Add("desc", pro);
     return json;
 }
	public override void Init (SimpleJson.JsonObject o)
	{
        base.Init(o);
        this.id = Convert.ToInt32(o["id"]);   
		this.type = Convert.ToInt32 (o ["type"]);        
        this.priority = Convert.ToInt32 (o ["priority"]);
		this.wholisten = Convert.ToInt32 (o ["wholisten"]);
		this.limit = Convert.ToInt32 (o ["limit"]);
		this.volume = Convert.ToInt32 (o ["volume"]) / 100f;
		this.resId = Convert.ToString (o ["resId"]);
		this.ifCircle = Convert.ToInt32 (o ["ifCircle"]) == 1;
		this.time = Convert.ToInt32 (o ["time"]) / 1000f;
		this.interval = Convert.ToInt32 (o ["interval"]) / 1000f;
	}
    public void ProcessRequest(HttpContext context)
    {
        if (!Magic.Security.SecuritySession.Authenticated())
        {
            context.Response.Write((new SimpleJson().HandleError("您还没有登陆或者登陆已经过期,请登陆系统!")).ToJsonString("yyyy-MM-dd HH:mm"));
            return;
        }

        string type = WebUtil.Param("type").Trim();
        if (type.ToLower() == "1002") //execute the ascx control and return the response html
            try
            {
                context.Server.Execute("AjaxControlsHandler.aspx",context.Response.Output, true);
                return;
            }
            catch (Exception error)
            {
                logger.Error("ExecuteControl", error);
                context.Response.Write(error.Message);
                return;
            }

        if (type.ToLower() == "1001")
        {
            try
            {
                string result = MagicAjax.InvokeAjaxCall2String();
                context.Response.Write(result);
                return;
            }
            catch (Exception error)
            {
                context.Response.Write(error.Message);
                return;
            }
        }

        //return json object
        SimpleJson json = new SimpleJson();
        try
        {
            SimpleJson j = MagicAjax.InvokeAjaxCall2Json();
            if (j != null) json = j;
        }
        catch (Exception error)
        {
            json.HandleError(error.Message);
        }
        context.Response.Write(json.ToJsonString("yyyy-MM-dd HH:mm"));
    }
 public ServerInfo(SimpleJson.JsonObject obj)
 {
     id = Convert.ToInt32(obj ["id"]);
     name = Convert.ToString(obj ["name"]);
     address = Convert.ToString(obj ["address"]);
     port = Convert.ToInt32(obj ["port"]);       
     if (obj.ContainsKey("status"))
     {
         status = Convert.ToInt32(obj ["status"]);
     }
     if (obj.ContainsKey("content"))
     {
         recommond = Convert.ToString(obj ["content"]);
     }
 }
Example #10
0
 public SimpleJson GetJSON()
 {
     SimpleJson json = new SimpleJson()
         .Add("parent", this.AreaCode)
         .Add("type", "s")
         .Add("code", this.SectionCode)
         .Add("status", (int)this.Status)
         .Add("desc", this.Text)
         .Add("cap", this.SectionCapacity)
         .Add("allowdelete", "1")
         .Add("allowchild", "0")
         .Add("parentType", "a")
         .Add("text", this.ToString());
     return json;
 }
Example #11
0
 public static SimpleJson GetJSON(ISession session, string areaCode, string sectionCode)
 {
     WHSection section = WHSection.Retrieve(session, areaCode, sectionCode);
     if (section == null) return new SimpleJson().HandleError(string.Format("�洢����{0}�еĻ���{1}������", areaCode, sectionCode));
     SimpleJson json = new SimpleJson()
         .Add("parent", section.AreaCode)
         .Add("type", "s")
         .Add("code", section.SectionCode)
         .Add("status", (int)section.Status)
         .Add("desc", section.Text)
         .Add("cap", section.SectionCapacity)
         .Add("allowdelete", "1")
         .Add("allowchild", "0")
         .Add("parentType", "a")
         .Add("text", section.ToString());
     return json;
 }
Example #12
0
 public SimpleJson GetJSON()
 {
     SimpleJson json = new SimpleJson()
         .Add("parent", "")
         .Add("type", "l")
         .Add("code", this.LocationCode)
         .Add("status", (int)this.Status)
         .Add("name", this.Name)
         .Add("desc", this.Text)
         .Add("addr", this.Address)
         .Add("zipcode", this.ZipCode)
         .Add("contact", this.Contact)
         .Add("phone", this.Phone)
         .Add("fax", this.FaxNumber)
         .Add("allowdelete", "1")
         .Add("allowchild", "1")
         .Add("parentType", "")
         .Add("text", this.ToString())
         .Add("comp", this.CompanyID);
     return json;
 }
Example #13
0
        public static SimpleJson GetWHInfo(ISession session, string area, string section)
        {
            if (string.IsNullOrEmpty(area) || area.Trim().Length <= 0)
                return new SimpleJson().HandleError("��û��ѡ���λ");

            string a = area.Trim().ToUpper();
            string sec = string.IsNullOrEmpty(section) ? "" : section.Trim().ToUpper();
            SimpleJson json = new SimpleJson().Add("area", area).Add("section", sec);

            if (sec.Length <= 0)
            {
                //���ؿ�λ��Ϣ
                WHArea whArea = WHArea.Retrieve(session, a);
                if (whArea == null) return json.HandleError("��λ" + a + "������");
                json.Add("capacity", Cast.Int(whArea.AreaCapacity));
                int stoQty = Cast.Int(session.CreateObjectQuery(@"select sum(StockQty) from StockDetail where AreaCode=?area group by AreaCode")
                    .Attach(typeof(StockDetail))
                    .SetValue("?area", a, "AreaCode")
                    .Scalar());
                json.Add("stored", stoQty);
            }
            else
            {
                //���ػ�����Ϣ
                WHSection whSection = WHSection.Retrieve(session, a, sec);
                if (whSection == null) return json.HandleError("��λ" + a + "�в����ڻ��ܺ�" + sec);
                json.Add("capacity", Cast.Int(whSection.SectionCapacity));
                int stoQty = Cast.Int(session.CreateObjectQuery(@"
            select sum(StockQty) from StockDetail
            where AreaCode=?area and SectionCode=?section
            group by AreaCode")
                    .Attach(typeof(StockDetail))
                    .SetValue("?area", a, "AreaCode")
                    .SetValue("?section", sec, "SectionCode")
                    .Scalar());
                json.Add("stored", stoQty);
            }
            return json;
        }
Example #14
0
 public static SimpleJson GetJSON(ISession session, string locationCode)
 {
     WHLocation location = WHLocation.Retrieve(session, locationCode);
     if (location == null) return new SimpleJson().HandleError(string.Format("�ִ���{0}������", locationCode));
     SimpleJson json = new SimpleJson()
         .Add("parent", "")
         .Add("type", "l")
         .Add("code", location.LocationCode)
         .Add("name", location.Name)
         .Add("status", (int)location.Status)
         .Add("desc", location.Text)
         .Add("addr", location.Address)
         .Add("zipcode", location.ZipCode)
         .Add("contact", location.Contact)
         .Add("phone", location.Phone)
         .Add("fax", location.FaxNumber)
         .Add("allowdelete", "1")
         .Add("allowchild", "1")
         .Add("parentType", "")
         .Add("text", location.ToString())
         .Add("comp", location.CompanyID);
     return json;
 }
	public void Init (SimpleJson.JsonObject o)
	{
		this.id = Convert.ToInt32 (o ["id"]);
		this.career = (CareerType)Convert.ToInt32 (o ["class"]);
		this.name = Convert.ToInt32 (o ["name"]);
		this.level = Convert.ToInt32 (o ["level"]);
		this.type = Convert.ToInt32 (o ["class"]);
		this.modelId = Convert.ToInt32 (o ["modelId"]);
		this.weaponId = Convert.ToInt32 (o ["weaponID"]);
		this.head = Convert.ToInt32 (o ["head"]);
		this.map = Convert.ToInt32 (o ["map"]);
		this.task = Convert.ToInt32 (o ["task"]);
		this.direction = Convert.ToSingle (o ["direction"]);
		string[] coors = ((string)o ["coordinate"]).Split (',');
		this.coordinate = new Vector3 (Convert.ToSingle (coors [0]), Convert.ToSingle (coors [1]), Convert.ToSingle (coors [2]));
		this.radius1 = Convert.ToInt32 (o ["radius1"]) / 100f;
		this.radius2 = Convert.ToInt32 (o ["radius2"]) / 100f;
		this.moveSpd = Convert.ToInt32 (o ["moveSpd"]) / 100f;
		this.estEquip = Convert.ToString (o ["estEquip"]);
		this.estSkill = Convert.ToInt32 (o ["estSkill"]);
		this.estPro = Convert.ToInt32 (o ["estPro"]);
		this.estText = Convert.ToInt32 (o ["estText"]);
	}
Example #16
0
 public static SimpleJson GetJSON(ISession session, string areaCode)
 {
     WHArea area = WHArea.Retrieve(session, areaCode);
     if (area == null) return new SimpleJson().HandleError(string.Format("�洢����{0}������", areaCode));
     SimpleJson json = new SimpleJson()
         .Add("type", "a")
         .Add("code", area.AreaCode)
         .Add("status", (int)area.Status)
         .Add("name", area.Name)
         .Add("desc", area.Text)
         .Add("cap", area.AreaCapacity)
         .Add("hassec", area.HasSection)
         .Add("isqc", area.IsQC)
         .Add("isnonformal", area.IsNonFormal)
         .Add("isscrap", area.IsScrap)
         .Add("allowdelete", area.AllowDelete)
         .Add("allowchild", area.AllowChild)
         .Add("text", area.ToString());
     if (!string.IsNullOrEmpty(area.ParentArea) && area.ParentArea.Trim().Length > 0)
         json.Add("parentType", "a").Add("parent", area.ParentArea.Trim());
     else
         json.Add("parentType", "l").Add("parent", area.LocationCode.Trim());
     return json;
 }
Example #17
0
        private void httpd_ExternalMethod(object sender, SimpleHttpd.ExternalMethodArgs e)
        {
            try
            {

                SimpleJson response = new SimpleJson();

                byte[] byCardID = new byte[10];
                IntPtr length = new IntPtr();
                String strID = "";

                // ICを読取ります
                if (GetCardID(ref byCardID[0], ref length) == 0)
                {
                    // 読取り成功時にICのIDを1バイトごと読み出します
                    for (int i = 0; i < length.ToInt32(); ++i)
                    {
                        strID += byCardID[i].ToString("X2");
                    }
                    response.elements["error"] = "false";
                }
                else
                {
                    // 読取り失敗時にメッセージを表示します
                    response.elements["error"] = "true";
                    strID = "read error";
                }
                // 結果表示します
                response.elements["IDm"] = strID;
                e.response = response.CreateJsonP("readTag");
            }
            catch (Exception ex)
            {
                label1.Text = "Read Error";
            }
        }
 /// <summary>
 /// Deserialize JSON
 /// </summary>
 /// <param name="input">JSON representation</param>
 /// <returns>An object representing <paramref name="input"/></returns>
 public object DeserializeObject(string input)
 {
     return(SimpleJson.DeserializeObject(input, null, this.serializerStrategy));
 }
Example #19
0
 public static IDictionary <string, object> ParseFooterJson(string signedMessage) =>
 SimpleJson.DeserializeObject(ParseFooter(signedMessage)) as IDictionary <string, object>;
Example #20
0
 private void GeneratorJsWebApi(string entity, int i, int count)
 {
     if (GeneratorJson.usetypescriptdeclaration == "true")
     {
         var fileTypeScriptDeclaration = $"{CurrentDirectory}\\{GeneratorJson.rootfolder}\\{entity}.d.ts";
         var lines       = File.ReadAllLines(fileTypeScriptDeclaration);
         var json        = lines[lines.Length - 1];
         var comment     = SimpleJson.DeserializeObject <CommentIntellisense>(json.Substring("//".Length).Replace("'", "\""));
         var parts       = GeneratorJson.rootnamespace.Split(".".ToCharArray());
         var projectName = parts.Length > 1 ? parts[1] : parts[0];
         var jsWebApi    = new JsWebApi(CrmServiceClient.OrganizationServiceProxy, projectName, entity, comment.IsDebugWebApi, comment.JsForm, comment.IsDebugForm);
         jsWebApi.GeneratorCode();
         var old  = File.ReadAllText(fileTypeScriptDeclaration).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         var @new = jsWebApi.WebApiCodeTypeScriptDeclaration.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         if (old != @new)
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": Processing ", CliLog.ColorGreen, entity, ".d.ts");
             if (Utility.CanWriteAllText(fileTypeScriptDeclaration))
             {
                 File.WriteAllText(fileTypeScriptDeclaration, jsWebApi.WebApiCodeTypeScriptDeclaration, System.Text.Encoding.UTF8);
             }
         }
         else
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": No change ", CliLog.ColorGreen, entity, ".d.ts");
         }
         var fileWebApi = $"{CurrentDirectory}\\{GeneratorJson.rootfolder}\\{entity}.webapi.js";
         old  = File.ReadAllText(fileWebApi).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         @new = jsWebApi.WebApiCode.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         if (old != @new)
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": Processing ", CliLog.ColorGreen, entity, ".webapi.js");
             if (Utility.CanWriteAllText(fileWebApi))
             {
                 File.WriteAllText(fileWebApi, jsWebApi.WebApiCode, System.Text.Encoding.UTF8);
             }
         }
         else
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": No change ", CliLog.ColorGreen, entity, ".webapi.js");
         }
     }
     else
     {
         var fileIntellisense = $"{CurrentDirectory}\\{GeneratorJson.rootfolder}\\{entity}.intellisense.js";
         var lines            = File.ReadAllLines(fileIntellisense);
         var json             = lines[lines.Length - 1];
         var comment          = SimpleJson.DeserializeObject <CommentIntellisense>(json.Substring("//".Length).Replace("'", "\""));
         var parts            = GeneratorJson.rootnamespace.Split(".".ToCharArray());
         var projectName      = parts.Length > 1 ? parts[1] : parts[0];
         var jsWebApi         = new JsWebApi(CrmServiceClient.OrganizationServiceProxy, projectName, entity, comment.IsDebugWebApi, comment.JsForm, comment.IsDebugForm);
         jsWebApi.GeneratorCode();
         var old  = File.ReadAllText(fileIntellisense).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         var @new = jsWebApi.WebApiCodeIntellisense.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         if (old != @new)
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": Processing ", CliLog.ColorGreen, entity, ".intellisense.js");
             if (Utility.CanWriteAllText(fileIntellisense))
             {
                 File.WriteAllText(fileIntellisense, jsWebApi.WebApiCodeIntellisense, System.Text.Encoding.UTF8);
             }
         }
         else
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": No change ", CliLog.ColorGreen, entity, ".intellisense.js");
         }
         var fileWebApi = $"{CurrentDirectory}\\{GeneratorJson.rootfolder}\\{entity}.webapi.js";
         old  = File.ReadAllText(fileWebApi).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         @new = jsWebApi.WebApiCode.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
         if (old != @new)
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": Processing ", CliLog.ColorGreen, entity, ".webapi.js");
             if (Utility.CanWriteAllText(fileWebApi))
             {
                 File.WriteAllText(fileWebApi, jsWebApi.WebApiCode, System.Text.Encoding.UTF8);
             }
         }
         else
         {
             CliLog.WriteLine(CliLog.ColorCyan, string.Format("{0,0}|{1," + count.ToString().Length + "}", "", i) + ": No change ", CliLog.ColorGreen, entity, ".webapi.js");
         }
     }
 }
Example #21
0
        private void SendCore(PulseEventBatch batch)
        {
            if (_sessionId == null)
            {
                SendPulseSessionEvent(RaygunPulseSessionEventType.SessionStart);
            }

            string version   = GetVersion();
            string os        = UIDevice.CurrentDevice.SystemName;
            string osVersion = UIDevice.CurrentDevice.SystemVersion;
            string platform  = Mindscape.Raygun4Net.Builders.RaygunEnvironmentMessageBuilder.GetStringSysCtl("hw.machine");

            string machineName = null;

            try {
                machineName = UIDevice.CurrentDevice.Name;
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine("Exception getting device name {0}", e.Message);
            }

            RaygunIdentifierMessage user = BuildRaygunIdentifierMessage(machineName);

            RaygunPulseMessage message = new RaygunPulseMessage();

            Debug.WriteLine("BatchSize: " + batch.PendingEventCount);

            RaygunPulseDataMessage [] eventMessages = new RaygunPulseDataMessage[batch.PendingEventCount];
            int index = 0;

            foreach (PendingEvent pendingEvent in batch.PendingEvents)
            {
                RaygunPulseDataMessage dataMessage = new RaygunPulseDataMessage();
                dataMessage.SessionId = pendingEvent.SessionId;
                dataMessage.Timestamp = pendingEvent.Timestamp;
                dataMessage.Version   = version;
                dataMessage.OS        = os;
                dataMessage.OSVersion = osVersion;
                dataMessage.Platform  = platform;
                dataMessage.Type      = "mobile_event_timing";
                dataMessage.User      = user;

                string type = pendingEvent.EventType == RaygunPulseEventType.ViewLoaded ? "p" : "n";

                RaygunPulseData data = new RaygunPulseData()
                {
                    Name = pendingEvent.Name, Timing = new RaygunPulseTimingMessage()
                    {
                        Type = type, Duration = pendingEvent.Duration
                    }
                };
                RaygunPulseData [] dataArray = { data };
                string             dataStr   = SimpleJson.SerializeObject(dataArray);
                dataMessage.Data = dataStr;

                eventMessages [index] = dataMessage;
                index++;
            }
            message.EventData = eventMessages;

            Send(message);
        }
        protected override async Task <SetStreamMetadataResult> SetStreamMetadataInternal(
            string streamId,
            int expectedStreamMetadataVersion,
            int?maxAge,
            int?maxCount,
            string metadataJson,
            CancellationToken cancellationToken)
        {
            var metadata = new MetadataMessage
            {
                StreamId = streamId,
                MaxAge   = maxAge,
                MaxCount = maxCount,
                MetaJson = metadataJson
            };

            var metadataMessageJsonData = SimpleJson.SerializeObject(metadata);

            var streamIdInfo = new StreamIdInfo(streamId);

            var currentVersion = Parameters.CurrentVersion();

            try
            {
                using (var connection = await OpenConnection(cancellationToken))
                    using (var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false))
                        using (var command = BuildStoredProcedureCall(
                                   _schema.SetStreamMetadata,
                                   transaction,
                                   Parameters.StreamId(streamIdInfo.MySqlStreamId),
                                   Parameters.MetadataStreamId(streamIdInfo.MetadataMySqlStreamId),
                                   Parameters.MetadataStreamIdOriginal(streamIdInfo.MetadataMySqlStreamId),
                                   Parameters.OptionalMaxAge(metadata.MaxAge),
                                   Parameters.OptionalMaxCount(metadata.MaxCount),
                                   Parameters.ExpectedVersion(expectedStreamMetadataVersion),
                                   Parameters.CreatedUtc(_settings.GetUtcNow?.Invoke()),
                                   Parameters.MetadataMessageMessageId(
                                       streamIdInfo.MetadataMySqlStreamId,
                                       expectedStreamMetadataVersion,
                                       metadataMessageJsonData),
                                   Parameters.MetadataMessageType(),
                                   Parameters.MetadataMessageJsonData(metadataMessageJsonData),
                                   currentVersion,
                                   Parameters.CurrentPosition()))
                        {
                            await command.ExecuteNonQueryAsync(cancellationToken).NotOnCapturedContext();

                            await transaction.CommitAsync(cancellationToken).NotOnCapturedContext();
                        }

                await TryScavenge(streamIdInfo, cancellationToken);

                return(new SetStreamMetadataResult((int)currentVersion.Value));
            }
            catch (MySqlException ex) when(ex.IsWrongExpectedVersion())
            {
                throw new WrongExpectedVersionException(
                          ErrorMessages.AppendFailedWrongExpectedVersion(
                              streamIdInfo.MetadataMySqlStreamId.IdOriginal,
                              expectedStreamMetadataVersion),
                          streamIdInfo.MetadataMySqlStreamId.IdOriginal,
                          ExpectedVersion.Any,
                          ex);
            }
        }
        async Task ProcessMessage(Message receivedMessage, CancellationToken token)
        {
            try
            {
                byte[]           messageBody      = null;
                TransportMessage transportMessage = null;
                Exception        exception        = null;
                var    nativeMessageId            = receivedMessage.MessageId;
                string messageId       = null;
                var    isPoisonMessage = false;

                try
                {
                    if (receivedMessage.MessageAttributes.TryGetValue(Headers.MessageId, out var messageIdAttribute))
                    {
                        messageId = messageIdAttribute.StringValue;
                    }
                    else
                    {
                        messageId = nativeMessageId;
                    }

                    transportMessage = SimpleJson.DeserializeObject <TransportMessage>(receivedMessage.Body);
                    messageBody      = await transportMessage.RetrieveBody(s3Client, configuration, token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // shutting down
                    return;
                }
                catch (Exception ex)
                {
                    // Can't deserialize. This is a poison message
                    exception       = ex;
                    isPoisonMessage = true;
                }

                if (isPoisonMessage || messageBody == null || transportMessage == null)
                {
                    var logMessage = $"Treating message with {messageId} as a poison message. Moving to error queue.";

                    if (exception != null)
                    {
                        Logger.Warn(logMessage, exception);
                    }
                    else
                    {
                        Logger.Warn(logMessage);
                    }

                    await MovePoisonMessageToErrorQueue(receivedMessage, messageId).ConfigureAwait(false);

                    return;
                }

                if (!IsMessageExpired(receivedMessage, transportMessage.Headers, messageId, CorrectClockSkew.GetClockCorrectionForEndpoint(awsEndpointUrl)))
                {
                    // here we also want to use the native message id because the core demands it like that
                    await ProcessMessageWithInMemoryRetries(transportMessage.Headers, nativeMessageId, messageBody, token).ConfigureAwait(false);
                }

                // Always delete the message from the queue.
                // If processing failed, the onError handler will have moved the message
                // to a retry queue.
                await DeleteMessage(receivedMessage, transportMessage.S3BodyKey).ConfigureAwait(false);
            }
            finally
            {
                maxConcurrencySemaphore.Release();
            }
        }
        private async Task <Tuple <int?, int> > AppendToStreamExpectedVersion(
            SqlConnection connection,
            SqlTransaction transaction,
            SqlStreamId sqlStreamId,
            int expectedVersion,
            NewStreamMessage[] messages,
            CancellationToken cancellationToken)
        {
            var sqlDataRecords = CreateSqlDataRecords(messages);

            using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersion, connection, transaction))
            {
                command.Parameters.AddWithValue("streamId", sqlStreamId.Id);
                command.Parameters.AddWithValue("expectedStreamVersion", expectedVersion);
                var eventsParam = CreateNewMessagesSqlParameter(sqlDataRecords);
                command.Parameters.Add(eventsParam);

                try
                {
                    using (var reader = await command
                                        .ExecuteReaderAsync(cancellationToken)
                                        .NotOnCapturedContext())
                    {
                        await reader.ReadAsync(cancellationToken).NotOnCapturedContext();

                        var currentVersion = reader.GetInt32(0);
                        int?maxCount       = null;

                        await reader.NextResultAsync(cancellationToken);

                        if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext())
                        {
                            var jsonData        = reader.GetString(0);
                            var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData);
                            maxCount = metadataMessage.MaxCount;
                        }

                        return(new Tuple <int?, int>(maxCount, currentVersion));
                    }
                }
                catch (SqlException ex)
                {
                    if (ex.Errors.Count == 1)
                    {
                        var sqlError = ex.Errors[0];
                        if (sqlError.Message == "WrongExpectedVersion")
                        {
                            // Idempotency handling. Check if the Messages have already been written.

                            var page = await ReadStreamInternal(
                                sqlStreamId,
                                expectedVersion + 1,
                                // when reading for already written Messages, it's from the one after the expected
                                messages.Length,
                                ReadDirection.Forward,
                                false,
                                null,
                                connection,
                                cancellationToken);

                            if (messages.Length > page.Messages.Length)
                            {
                                throw new WrongExpectedVersionException(
                                          ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion),
                                          ex);
                            }

                            // Iterate all messages an check to see if all message ids match
                            for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++)
                            {
                                if (messages[i].MessageId != page.Messages[i].MessageId)
                                {
                                    throw new WrongExpectedVersionException(
                                              ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion),
                                              ex);
                                }
                            }

                            return(NullAppendResult);
                        }
                    }
                    if (ex.IsUniqueConstraintViolation())
                    {
                        throw new WrongExpectedVersionException(
                                  ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion),
                                  ex);
                    }
                    throw;
                }
                return(NullAppendResult);
            }
        }
 public void ParseIncompleteArray()
 {
     var o = SimpleJson.DeserializeObject("[1");
 }
Example #26
0
        public void GetEnterpriseServerMeta(Action <GitHubHostMeta> onSuccess, Action <Exception> onError = null)
        {
            Guard.ArgumentNotNull(onSuccess, nameof(onSuccess));
            new FuncTask <GitHubHostMeta>(taskManager.Token, () =>
            {
                var octorunTask = new OctorunTask(taskManager.Token, environment, "meta -h " + HostAddress.ApiUri.Host)
                                  .Configure(processManager);

                var ret = octorunTask.RunSynchronously();
                if (ret.IsSuccess)
                {
                    var deserializeObject = SimpleJson.DeserializeObject <Dictionary <string, object> >(ret.Output[0]);

                    return(new GitHubHostMeta
                    {
                        InstalledVersion = (string)deserializeObject["installed_version"],
                        GithubServicesSha = (string)deserializeObject["github_services_sha"],
                        VerifiablePasswordAuthentication = (bool)deserializeObject["verifiable_password_authentication"]
                    });
                }

                var message = ret.GetApiErrorMessage();

                logger.Trace("Message: {0}", message);

                if (message != null)
                {
                    if (message.Contains("ETIMEDOUT", StringComparison.InvariantCulture))
                    {
                        message = "Connection timed out.";
                    }
                    else if (message.Contains("ECONNREFUSED", StringComparison.InvariantCulture))
                    {
                        message = "Connection refused.";
                    }
                    else if (message.Contains("ENOTFOUND", StringComparison.InvariantCulture))
                    {
                        message = "Address not found.";
                    }
                    else
                    {
                        int httpStatusCode;
                        if (int.TryParse(message, out httpStatusCode))
                        {
                            var httpStatus = ((HttpStatusCode)httpStatusCode).ToString();
                            message        = httpStatusErrorRegex.Replace(httpStatus, " $1");
                        }
                    }
                }
                else
                {
                    message = "Error getting server meta";
                }

                throw new ApiClientException(message);
            })
            .FinallyInUI((success, ex, meta) =>
            {
                if (success)
                {
                    onSuccess(meta);
                }
                else
                {
                    logger.Error(ex, "Error getting server meta");
                    onError?.Invoke(ex);
                }
            })
            .Start();
        }
        private async Task <Tuple <int?, int> > AppendToStreamExpectedVersionNoStream(
            SqlConnection connection,
            SqlTransaction transaction,
            SqlStreamId sqlStreamId,
            NewStreamMessage[] messages,
            CancellationToken cancellationToken)
        {
            using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersionNoStream, connection, transaction))
            {
                command.Parameters.AddWithValue("streamId", sqlStreamId.Id);
                command.Parameters.AddWithValue("streamIdOriginal", sqlStreamId.IdOriginal);

                if (messages.Any())
                {
                    var sqlDataRecords = CreateSqlDataRecords(messages);
                    var eventsParam    = CreateNewMessagesSqlParameter(sqlDataRecords);
                    command.Parameters.Add(eventsParam);
                }
                else
                {
                    // Must use a null value for the table-valued param if there are no records
                    var eventsParam = CreateNewMessagesSqlParameter(null);
                    command.Parameters.Add(eventsParam);
                }

                try
                {
                    using (var reader = await command
                                        .ExecuteReaderAsync(cancellationToken)
                                        .NotOnCapturedContext())
                    {
                        await reader.ReadAsync(cancellationToken).NotOnCapturedContext();

                        var currentVersion = reader.GetInt32(0);
                        int?maxCount       = null;

                        if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext())
                        {
                            var jsonData        = reader.GetString(0);
                            var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData);
                            maxCount = metadataMessage.MaxCount;
                        }

                        return(new Tuple <int?, int>(maxCount, currentVersion));
                    }
                }
                catch (SqlException ex)
                {
                    // Check for unique constraint violation on
                    // https://technet.microsoft.com/en-us/library/aa258747%28v=sql.80%29.aspx
                    if (ex.IsUniqueConstraintViolationOnIndex("IX_Streams_Id"))
                    {
                        // Idempotency handling. Check if the Messages have already been written.
                        var page = await ReadStreamInternal(
                            sqlStreamId,
                            StreamVersion.Start,
                            messages.Length,
                            ReadDirection.Forward,
                            false,
                            null,
                            connection,
                            cancellationToken)
                                   .NotOnCapturedContext();

                        if (messages.Length > page.Messages.Length)
                        {
                            throw new WrongExpectedVersionException(
                                      ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal,
                                                                                     ExpectedVersion.NoStream),
                                      ex);
                        }

                        for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++)
                        {
                            if (messages[i].MessageId != page.Messages[i].MessageId)
                            {
                                throw new WrongExpectedVersionException(
                                          ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal,
                                                                                         ExpectedVersion.NoStream),
                                          ex);
                            }
                        }

                        return(NullAppendResult);
                    }

                    if (ex.IsUniqueConstraintViolation())
                    {
                        throw new WrongExpectedVersionException(
                                  ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal,
                                                                                 ExpectedVersion.NoStream),
                                  ex);
                    }

                    throw;
                }
                return(NullAppendResult);
            }
        }
Example #28
0
        public static string registrarCliente(string sessionId, string routeId, string urlSL, ClienteBean cliente, bool isLocEnabled)
        {
            string res = string.Empty;

            try
            {
                if (isLocEnabled)
                {
                    var document = transformBusinessPartner(cliente);
                    if (document != null)
                    {
                        File.WriteAllText(Util.castURL(MainProcess.mConn.pathJSONLog, "\\") + "CLIENTE_" + cliente.ClaveMovil
                                          + ".json",
                                          SimpleJson.SerializeObject(document));
                        IRestResponse response = makeRequest(Util.castURL(urlSL, "/") + Constant.BUSINESS_PARTNERS, Method.POST, sessionId, routeId, document);
                        if (response.StatusCode == System.Net.HttpStatusCode.Created)
                        {
                            JObject jObject = JObject.Parse(response.Content.ToString());
                            res = jObject["CardCode"].ToString().Trim();
                        }
                        else
                        {
                            res = string.Empty;
                            MainProcess.log.Error("ClienteDAO > registrarCliente() > Document BusinessPartner " +
                                                  cliente.ClaveMovil + " > " + response.Content);
                            actualizarPropiedades(cliente.ClaveMovil,
                                                  MainProcess.mConn.urlPatchSocioNegocio +
                                                  "?empId=" + cliente.EMPRESA +
                                                  "&bpId=" + cliente.ClaveMovil,
                                                  "{\"Migrado\":\"N\", \"MENSAJE\": \"" + Util.replaceEscChar(response.Content) + "\"}");
                        }
                    }
                }
                else
                {
                    var document = transformBusinessPartnerNoLoc(cliente);
                    if (document != null)
                    {
                        File.WriteAllText(Util.castURL(MainProcess.mConn.pathJSONLog, "\\") + "CLIENTE_" + cliente.ClaveMovil
                                          + ".json",
                                          SimpleJson.SerializeObject(document));
                        IRestResponse response = makeRequest(Util.castURL(urlSL, "/") + Constant.BUSINESS_PARTNERS, Method.POST, sessionId, routeId, document);
                        if (response.StatusCode == System.Net.HttpStatusCode.Created)
                        {
                            JObject jObject = JObject.Parse(response.Content.ToString());
                            res = jObject["CardCode"].ToString().Trim();
                        }
                        else
                        {
                            res = string.Empty;
                            MainProcess.log.Error("ClienteDAO > registrarCliente() > Document BusinessPartner " +
                                                  cliente.ClaveMovil + " > " + response.Content);
                            actualizarPropiedades(cliente.ClaveMovil,
                                                  MainProcess.mConn.urlPatchSocioNegocio +
                                                  "?empId=" + cliente.EMPRESA +
                                                  "&bpId=" + cliente.ClaveMovil,
                                                  "{\"Migrado\":\"N\", \"MENSAJE\": \"" + Util.replaceEscChar(response.Content) + "\"}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res = string.Empty;
                MainProcess.log.Error("ClienteDAO > registrarCliente() > " + ex.Message);
            }

            return(res);
        }
Example #29
0
 /// <summary>
 /// Returns a valid JSON representation of
 /// the model, according to the Swagger schema.
 /// </summary>
 /// <returns>A valid JSON representation of the model.</returns>
 public string ToJson()
 {
     return(SimpleJson.SerializeObject(this, SerializerStrategy));
 }
Example #30
0
 public static string Encrypt(byte[] symmetricKey, PasetoInstance payload, byte[] nonce = null) =>
 EncryptBytes(symmetricKey, Encoding.UTF8.GetBytes(SimpleJson.SerializeObject(payload.ToDictionary())), SimpleJson.SerializeObject(payload.Footer), nonce);
 /// <summary>
 /// Deserialize JSON
 /// </summary>
 /// <param name="input">JSON representation</param>
 /// <typeparam name="T">The <see cref="Type"/> to deserialize into</typeparam>
 /// <returns>An instance of type <typeparamref name="T"/> representing <paramref name="input"/> as an object</returns>
 public T Deserialize <T>(string input)
 {
     return(SimpleJson.DeserializeObject <T>(input, this.serializerStrategy));
 }
Example #32
0
 public string Write(Dump value)
 {
     return(JsonHelper.FormatJson(SimpleJson.SerializeObject(WriteJsonObjects(value))));
 }
        public void ReadHexidecimalWithAllLetters()
        {
            string json = @"{""text"":0xabcdef12345}";

            var o = SimpleJson.DeserializeObject(json);
        }
Example #34
0
        /// <summary>
        /// TODO: Extend an SSO token daily. This should be an internal method
        /// </summary>
        /// <returns></returns>
        public async static Task CheckAndExtendTokenIfNeeded()
        {
            // get the existing token
            if (String.IsNullOrEmpty(ActiveSession.CurrentAccessTokenData.AccessToken))
            {
                // If there is no token, do nothing
                return;
            }

            // check if its issue date is over 24 hours and if so, renew it
            if (DateTime.UtcNow - ActiveSession.CurrentAccessTokenData.Issued > TimeSpan.FromHours(24)) // one day
            {
                var    client         = new HttpClient();
                String tokenExtendUri = "https://graph.facebook.com/v2.1";
                client.BaseAddress = new Uri(tokenExtendUri);

                var request = new HttpRequestMessage();

                var mfdc   = new MultipartFormDataContent();
                var _appId = Session.AppId;

                mfdc.Add(new StringContent(_appId), name: "batch_app_id");

                String extensionString = "[{\"method\":\"GET\",\"relative_url\":\"oauth\\/access_token?grant_type=fb_extend_sso_token&access_token=" + ActiveSession.CurrentAccessTokenData.AccessToken + "\"}]";
                mfdc.Add(new StringContent(extensionString), name: "batch");

                HttpResponseMessage response = await client.PostAsync(tokenExtendUri, mfdc);

                String resultContent = await response.Content.ReadAsStringAsync();

                var result = SimpleJson.DeserializeObject(resultContent);

                // extract the access token and save it in the session
                var data = (List <object>)result;

                var dictionary = (IDictionary <string, object>)data[0];
                var code       = (long)dictionary["code"];
                if (code == 200)
                {
                    // the API succeeded
                    var body         = (IDictionary <string, object>)SimpleJson.DeserializeObject((string)dictionary["body"]);
                    var access_token = (string)body["access_token"];
                    var expires_at   = (long)body["expires_at"];

                    var accessTokenData = new AccessTokenData();
                    // token extension failed...
                    accessTokenData.AccessToken = access_token;

                    // parse out other types
                    long expiresInValue;
                    var  now = DateTime.UtcNow;
                    accessTokenData.Expires = now + TimeSpan.FromSeconds(expires_at);
                    accessTokenData.Issued  = now - (TimeSpan.FromDays(60) - TimeSpan.FromSeconds(expires_at));
                    accessTokenData.AppId   = _appId;

                    // Assign the accessTokenData object over, this saves it to the disk as well.
                    ActiveSession.CurrentAccessTokenData = accessTokenData;
                }
                else
                {
                    // return an error?? Since this is token extension, maybe we should wait until the token is finally expired before throwing an error.
                }
            }
        }
 public void DeserializeInvaildEscapedSurrogatePair()
 {
     string json = "\"\\uD867\\u0000 is Arabesque greenling(fish)\"";
     var    o    = SimpleJson.DeserializeObject(json);
 }
	public void Init (SimpleJson.JsonObject o)
	{
		id = Convert.ToInt32 (o ["id"]);
		modelId = Convert.ToInt32 (o ["modelId"]);
		name = Convert.ToString (o ["name"]);
		action = (ActionType)Convert.ToInt32 (o ["type1"]);
		weapon = (WeaponType)Convert.ToInt32 (o ["type2"]);

		attack = Convert.ToInt32 (o ["attack"]);
		hit = Convert.ToInt32 (o ["hit"]);
		die = Convert.ToInt32 (o ["die"]);
		move = Convert.ToInt32 (o ["move"]);
		effect = Convert.ToInt32 (o ["effect"]);
		bornArt = Convert.ToInt32 (o ["bornArt"]);
		deathArt = Convert.ToInt32 (o ["deathArt"]);
		hitArt = Convert.ToInt32 (o ["hitArt"]);
		armorHitArt = Convert.ToInt32 (o ["armorHitArt"]);
		noArmorArt = Convert.ToInt32 (o ["noArmorArt"]);
	}
Example #37
0
 public string Serialize <T>(T value)
 {
     return(SimpleJson.SerializeObject(value));
 }
 public LocaleConfig(SimpleJson.JsonObject o)
 {
     Init(o);
 }
Example #39
0
        /**
         * Connects to the hub. Errors if there is already a hub connection.
         * Will cancel a pending reconnection if there is one. This method is
         * not guaranteed to connect on first try.
         */
        public async void Connect()
        {
            if (hubConnectionHandler != null)
            {
                throw new Exception("Already connected.");
            }
            if (!league.IsConnected)
            {
                return;
            }

            try
            {
                DebugLogger.Global.WriteMessage("Connecting to Rift...");

                // Cancel pending reconnect if there is one.
                if (reconnectCancellationTokenSource != null)
                {
                    DebugLogger.Global.WriteMessage($"Canceling older reconnect to Rift.");
                    reconnectCancellationTokenSource.Cancel();
                    reconnectCancellationTokenSource = null;
                }

                // Ensure that our token is still valid...
                bool valid = false; // in case first startup and hub token is empty
                if (!Persistence.GetHubToken().IsNullOrEmpty())
                {
                    DebugLogger.Global.WriteMessage("Requesting hub token..");
                    var response = await httpClient.GetStringAsync(Program.HUB + "/check?token=" + Persistence.GetHubToken());

                    valid = response == "true";
                    DebugLogger.Global.WriteMessage($"Hub token validity: {(valid ? "valid" : "invalid")}.");
                }

                // ... and request a new one if it isn't.
                if (!valid)
                {
                    DebugLogger.Global.WriteMessage($"Requesting hub token..");
                    var payload      = "{\"pubkey\":\"" + CryptoHelpers.ExportPublicKey() + "\"}";
                    var responseBlob = await httpClient.PostAsync(Program.HUB + "/register", new StringContent(payload, Encoding.UTF8, "application/json"));

                    var response = SimpleJson.DeserializeObject <dynamic>(await responseBlob.Content.ReadAsStringAsync());
                    if (!response["ok"])
                    {
                        throw new Exception("Could not receive JWT from Rift");
                    }

                    Persistence.SetHubToken(response["token"]);
                    DebugLogger.Global.WriteMessage($"Hub token: {response["token"]}.");
                }

                // Connect to hub. Will error if token is invalid or server is down, which will prompt a reconnection.
                hubConnectionHandler          = new HubConnectionHandler(league);
                hubConnectionHandler.OnClose += CloseAndReconnect;

                // We assume to be connected.
                if (isNewLaunch)
                {
                    DebugLogger.Global.WriteMessage($"Creating New Launch popup.");
                    app.ShowNotification("Connected to League. Click here for instructions on how to control your League client from your phone.");
                    isNewLaunch = false;
                }

                hasTriedImmediateReconnect = false;
            }
            catch (Exception e)
            {
                DebugLogger.Global.WriteError($"Connection to Rift failed, an exception occurred: {e.ToString()}");
                // Something happened that we didn't anticipate for.
                // Just try again in a bit.
                CloseAndReconnect();
            }
        }
Example #40
0
 public SimpleJson GetJSON()
 {
     SimpleJson json = new SimpleJson()
         .Add("type", "a")
         .Add("code", this.AreaCode)
         .Add("status", (int)this.Status)
         .Add("name", this.Name)
         .Add("desc", this.Text)
         .Add("cap", this.AreaCapacity)
         .Add("hassec", this.HasSection)
         .Add("isqc", this.IsQC)
         .Add("isnonformal", this.IsNonFormal)
         .Add("isscrap", this.IsScrap)
         .Add("allowdelete", this.AllowDelete)
         .Add("allowchild", this.AllowChild)
         .Add("text", this.ToString());
     if (!string.IsNullOrEmpty(this.ParentArea) && this.ParentArea.Trim().Length > 0)
         json.Add("parentType", "a").Add("parent", this.ParentArea.Trim());
     else
         json.Add("parentType", "l").Add("parent", this.LocationCode.Trim());
     return json;
 }
 public UIRuleConfig(SimpleJson.JsonObject o){Init(o);}
 public TaskConfig(SimpleJson.JsonObject o)
 {
     Init(o);
 }
Example #43
0
        public static SimpleJson GetOrgJSON(ISession session, Org org)
        {
            SimpleJson json = new SimpleJson();
            if (org == null)
            {
                json.HandleError("Org is null");
                return json;
            }

            json.Add("id", org.OrgId)
                .Add("parent", org.ParentId)
                .Add("root", org.IsRoot)
                .Add("virtual", org.IsVirtual)
                .Add("seq", org.OrgSeq)
                .Add("code", org.OrgCode)
                .Add("name", org.OrgName)
                .Add("remark", org.Description)
                .Add("desc", org);

            if (org.CreateBy > 0)
            {
                User createBy = User.Retrieve(session, org.CreateBy);
                if (createBy != null)
                    json.Add("createBy", string.IsNullOrEmpty(createBy.FullName) ? createBy.UserName : createBy.FullName);
                else
                    Log.Warn<Org>("User {0} (CreateBy) not found when loading org {1}:{2}", org.CreateBy, org.OrgId, org.OrgCode);
            }
            else
                json.Add("createBy", "");
            json.Add("createTime", org.CreateDate);

            if (org.ModifyBy > 0)
            {
                User modefyBy = User.Retrieve(session, org.ModifyBy);
                if (modefyBy != null)
                    json.Add("modifyBy", string.IsNullOrEmpty(modefyBy.FullName) ? modefyBy.UserName : modefyBy.FullName);
                else
                    Log.Warn<Org>("User {0} (ModifyBy) not found when loading org {1}:{2}", org.ModifyBy, org.OrgId, org.OrgCode);
            }
            else
                json.Add("modifyBy", "");
            json.Add("modifyTime", org.ModifyDate);

            User manager = null;
            if (org.Manager > 0)
            {
                manager = User.Retrieve(session, org.Manager);
                if (manager == null)
                    Log.Warn<Org>("User {0} (Manager) not found when loading org {1}:{2}", org.Manager, org.OrgId, org.OrgCode);
            }
            if (manager != null)
                json.Add("managerId", manager.UserId)
                    .Add("manager", string.IsNullOrEmpty(manager.FullName) ? manager.UserName : manager.FullName);
            else
                json.Add("managerId", -1)
                    .Add("manager", "");

            if (OrgTypeRegistry.HasExtAttr(org.OrgType) && org.ExtAttr != null)
            {
                Type type = OrgTypeRegistry.ExtAttrType(org.OrgType);
                org.ExtAttr.Json(session, json);
            }

            return json;
        }
Example #44
0
 public string Serialize(object obj)
 {
     return(SimpleJson.SerializeObject(obj, new RabbitJsonSerializerStrategy()));
 }
 public MapConfig(SimpleJson.JsonObject o)
 {
     Init(o);
 } 
Example #46
0
 public static string Sign(byte[] publicKey, byte[] privateKey, PasetoInstance claims)
 {
     return(SignBytes(publicKey, privateKey, Encoding.UTF8.GetBytes(SimpleJson.SerializeObject(claims.ToDictionary())), SimpleJson.SerializeObject(claims.Footer)));
 }
Example #47
0
 public SimpleJson ToJSON()
 {
     SimpleJson json = new SimpleJson();
     json.Add("id", this.GroupId);
     json.Add("name", this.Name);
     json.Add("desc", this.Description);
     json.Add("parent", this.ParentId);
     json.Add("type", this.GroupType);
     return json;
 }
 public void UnexpectedEndWhenParsingUnquotedProperty()
 {
     var result = SimpleJson.DeserializeObject(@"{aww");
 }
	public SoundConfig (SimpleJson.JsonObject o)
	{
		Init (o);
	}
        public void ReadOcatalNumber()
        {
            var json = @"[0372, 0xFA, 0XFA]";

            var o = SimpleJson.DeserializeObject(json);
        }
Example #51
0
 public Dump Read(string input)
 {
     return(ReadJsonObject(SimpleJson.DeserializeObject <JsonObject>(input)));
 }
 /// <summary>
 /// Serialize an object to JSON
 /// </summary>
 /// <param name="obj">The object to serialize</param>
 /// <returns>A JSON string representation of <paramref name="obj"/></returns>
 public string Serialize(object obj)
 {
     return(SimpleJson.SerializeObject(obj, this.serializerStrategy));
 }
Example #53
0
 public SimpleJson ToJSON()
 {
     SimpleJson json = new SimpleJson();
     json.Add("id", this.OperationId);
     json.Add("name", this.Name);
     json.Add("desc", this.Description);
     json.Add("parent", this.ParentId);
     json.Add("type", this.Type.ToString());
     json.Add("level", this.Level);
     json.Add("image", this.Image);
     json.Add("seq", this.SeqNo);
     json.Add("entry", this.Entry);
     json.Add("status", this.Status);
     return json;
 }
 public void UnexpectedEndOfString()
 {
     var result = SimpleJson.DeserializeObject("hi");
 }
Example #55
0
 public SimpleJson ToJSon(ISession session)
 {
     SimpleJson json = new SimpleJson()
         .Add("orderNumber", this.OrderNumber)
         .Add("saleOrder", this.SaleOrderNumber)
         .Add("memberId", this.MemberID);
     string memberName = " ";
     if (this.MemberID > 0)
     {
         Magic.Basis.Member member = Magic.Basis.Member.Retrieve(session, this.MemberID);
         if (member != null) memberName = member.Name;
     }
     json.Add("member", memberName);
     json.Add("contact", this.Contact)
         .Add("phone", this.Phone)
         .Add("mobile", this.Mobile)
         .Add("address", this.Address)
         .Add("district", this.Province + " " + this.City)
         .Add("shippingNumber", this.ShippingNumber)
         .Add("isInvoice", this.IsInvoice)
         .Add("invoice", Cast.String(this.InvoiceNumber, "").Trim())
         .Add("packageWeight", this.PackageWeight)
         .Add("logistics", this.LogisticsID)
         .Add("packageCount", this.PackageCount <= 0 ? 1 : this.PackageCount);
     string paymentMethod = " ";
     if (this.PaymentMethod > 0)
     {
         CRM.PaymentMethod pm = CRM.PaymentMethod.Retrieve(session, this.PaymentMethod);
         if (pm != null)
             paymentMethod = pm.Name;
     }
     json.Add("paymentMethod", paymentMethod);
     string deliverType = " ";
     if (this.DeliveryType > 0)
     {
         CRM.DeliverType dt = CRM.DeliverType.Retrieve(session, this.DeliveryType);
         if (dt != null) deliverType = dt.Name;
     }
     json.Add("deliverType", deliverType);
     string logisName = " ";
     if (this.LogisticsID > 0)
     {
         Logistics logis = Logistics.Retrieve(session, this.LogisticsID);
         if (logis != null) logisName = logis.ShortName;
     }
     json.Add("logisticsName", logisName);
     string packageType = " ";
     if (this.PackageType > 0)
     {
         CRM.PackageType pt = CRM.PackageType.Retrieve(session, this.PackageType);
         if (pt != null) packageType = pt.Name;
     }
     json.Add("packageType", packageType)
         .Add("note", string.IsNullOrEmpty(this.Remark) ? " " : this.Remark.Replace("</br>", " "));
     json.Add("packageUser", string.IsNullOrEmpty(this.PackagePerson) ? " " : this.PackagePerson);
     return json;
 }
        public void ReadNullTerminiatorString()
        {
            var result = SimpleJson.DeserializeObject("\"h\0i\"");

            Assert.AreEqual("h\0i", result);
        }
 public void Init(SimpleJson.JsonObject o)
 {
     this.id = Convert.ToInt32(o ["id"]);
     this.content = Convert.ToString(o["content"]).Replace("\\n", "\n");
 }
 public void UnexpectedEndOfHex()
 {
     var result = SimpleJson.DeserializeObject(@"'h\u006");
 }
	public override void Init (SimpleJson.JsonObject o)
	{
		id = Convert.ToInt32 (o ["mapId"]);
		name = Convert.ToString (o ["name"]);
		levelLimit = Convert.ToInt32 (o ["levelLimit"]);
		levelMax = Convert.ToInt32 (o ["levelMax"]);
		condition = Convert.ToInt32 (o ["condition"]);
		safeType = Convert.ToInt32 (o ["safeType"]);
		mapType = (MapType)Convert.ToInt32 (o ["mapType"]);
		ui = (MapUIType)Convert.ToInt32 (o ["interface"]);
		mapGroup = Convert.ToInt32 (o ["mapGroup"]);
		dungeonType = Convert.ToInt32 (o ["dungeonType"]);
		moduleId = Convert.ToInt32 (o ["moduleId"]);
		inPos = Convert.ToInt32 (o ["inPos"]);
		relivePos = Convert.ToInt32 (o ["relivePos"]);
		reliveLimit = Convert.ToInt32 (o ["reliveLimit"]);
		reliveTimes = Convert.ToInt32 (o ["reliveTimes"]);
		reliveGroup = Convert.ToInt32 (o ["reliveGroup"]);
		recoverLimit = Convert.ToInt32 (o ["recoverLimit"]);
		liveTime = Convert.ToInt32 (o ["liveTime"]);
		playerMax = Convert.ToInt32 (o ["playerMax"]);
		inCond = Convert.ToInt32 (o ["inCond"]);
		inFunct = Convert.ToInt32 (o ["inFunct"]);
		outCond = Convert.ToInt32 (o ["outCond"]);
		outFunct = Convert.ToInt32 (o ["outFunct"]);
		scriptId = Convert.ToInt32 (o ["scriptId"]);   
		this.subType = Convert.ToInt32 (o ["subType"]);
		this.ifAuto = Convert.ToInt32 (o ["ifAuto"]) == 1;
		this.ifSync = Convert.ToInt32 (o ["ifSync"]) == 1;
	    showMinimap = Convert.ToInt32(o["showMinimap"]) == 1;
		this.music = Convert.ToInt32(o["music"]);
        this.seekId = Convert.ToInt32(o["seekId"]);
        this.loadingUI = Convert.ToString (o ["loadingUi"]);
        this.action = Convert.ToString(o["action"]);
	}
 public void UnexpectedEndOfControlCharacter()
 {
     var result = SimpleJson.DeserializeObject(@"'h\");
 }