Beispiel #1
0
        public async Task<string> Search(string search)
        {
            using (AutoResetEvent handle = new AutoResetEvent(false))
            {
                JsonObject message = new JsonObject();
                message.Add("method", JsonValue.CreateStringValue("core.library.search"));

                JsonObject queryObject = new JsonObject();
                queryObject.Add("track_name", JsonValue.CreateStringValue(search));

                JsonArray urisArray = new JsonArray();
                urisArray.Add(JsonValue.CreateStringValue("spotify:"));

                JsonObject paramsObject = new JsonObject();
                paramsObject.Add("query", queryObject);
                paramsObject.Add("uris", urisArray);

                message.Add("params", paramsObject);

                string result = null;
                await Send(message, searchResult =>
                {
                    JsonArray tracks = searchResult.GetNamedArray("result")[0].GetObject().GetNamedArray("tracks");
                    result = tracks.First().GetObject().GetNamedString("uri");

                    handle.Set();
                });

                handle.WaitOne(TimeSpan.FromSeconds(30));
                return result;
            }
        }
Beispiel #2
0
 private async void OnClick(object sender, RoutedEventArgs e)
 {
     Button btn = sender as Button;
     MessageDialog msgBox = new MessageDialog("请输入姓名、城市和年龄。");
     if(txtName.Text == "" || txtCity.Text == "" || txtAge.Text == "")
     {
         await msgBox.ShowAsync();
         return;
     }
     btn.IsEnabled = false;
     // 获取文档库目录
     StorageFolder doclib = KnownFolders.DocumentsLibrary;
     // 将输入的内容转化为 json 对象
     JsonObject json = new JsonObject();
     json.Add("name", JsonValue.CreateStringValue(txtName.Text));
     json.Add("city", JsonValue.CreateStringValue(txtCity.Text));
     json.Add("age", JsonValue.CreateNumberValue(Convert.ToDouble(txtAge.Text)));
     // 提取出 json 字符串
     string jsonStr = json.Stringify();
     // 在文档库中创建新文件
     string fileName = DateTime.Now.ToString("yyyy-M-d-HHmmss") + ".mydoc";
     StorageFile newFile = await doclib.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
     // 将 json 字符串写入文件
     await FileIO.WriteTextAsync(newFile, jsonStr);
     btn.IsEnabled = true;
     msgBox.Content = "保存成功";
     await msgBox.ShowAsync();
 }
        internal static JsonObject Generate(Comment comment, ServerInfo serverInfo)
        {
            var json = new JsonObject();

            if (comment.Body != null)
            {
                json.Add("body", comment.Body);
            }

            if (comment.Visibility != null)
            {
                if (serverInfo.BuildNumber >= ServerVersionConstants.BuildNumberJira43)
                {
                    var visibilityJson = new JsonObject();
                    var commentVisibilityType = comment.Visibility.Type == Visibility.VisibilityType.Group ? "group" : "role";

                    if (serverInfo.BuildNumber < ServerVersionConstants.BuildNumberJira5)
                    {
                        commentVisibilityType = commentVisibilityType.ToUpper();
                    }

                    visibilityJson.Add("type", commentVisibilityType);
                    visibilityJson.Add("value", comment.Visibility.Value);
                    json.Add("visibility", visibilityJson.ToJson());
                }
                else
                {
                    json.Add(comment.Visibility.Type == Visibility.VisibilityType.Role ? "role" : "group", comment.Visibility.Value);
                }
            }

            return json;
        }
 private async void LoadAboutData(string hash)
 {
     var httpclient = new Windows.Web.Http.HttpClient();
     TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
     var time = Convert.ToInt64(ts.TotalMilliseconds).ToString();
     var key = Class.MD5.GetMd5String("1005Ilwieks28dk2k092lksi2UIkp8150" + time);
     var postobj = new JsonObject();
     postobj.Add("appid", JsonValue.CreateStringValue("1005"));
     postobj.Add("mid", JsonValue.CreateStringValue(""));
     postobj.Add("clientver", JsonValue.CreateStringValue("8150"));
     postobj.Add("clienttime", JsonValue.CreateStringValue("1469035332000"));
     postobj.Add("key", JsonValue.CreateStringValue("27b498a7d890373fadb673baa1dabf7e"));
     var array = new JsonArray();
     var videodata = new JsonObject();
     videodata.Add("video_hash", JsonValue.CreateStringValue(hash));
     videodata.Add("video_id", JsonValue.CreateNumberValue(0));
     array.Add(videodata);
     postobj.Add("data", array);
     var postdata = new Windows.Web.Http.HttpStringContent(postobj.ToString());
     var result= await httpclient.PostAsync(new Uri("http://kmr.service.kugou.com/v1/video/related"), postdata);
     var json = await result.Content.ReadAsStringAsync();
     json = json.Replace("{size}", "150");
     var obj = JsonObject.Parse(json);
     AboutMVListView.ItemsSource = Class.data.DataContractJsonDeSerialize<List<AboutMVdata>>(obj.GetNamedArray("data")[0].GetArray().ToString());
 }
        public static JsonObject ToJson(Dominion.GameDescription gameDescription, int starRating)
        {
            JsonObject root = new Windows.Data.Json.JsonObject();

            root.Add(jsonNameDeck, ToJson(gameDescription));

            JsonArray expansionArray = new JsonArray();
            Dominion.Expansion[] presentExpansions;
            Dominion.Expansion[] missingExpansions;
            gameDescription.GetRequiredExpansions(out presentExpansions, out missingExpansions);

            foreach (var expansion in presentExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(true));
                expansionArray.Add(expansionObject);
            }

            foreach (var expansion in missingExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(false));
                expansionArray.Add(expansionObject);
            }

            root.Add(jsonNameRequiredExpansions, expansionArray);

            root.Add(jsonNameRating, JsonValue.CreateNumberValue(starRating));

            return root;
        }
Beispiel #6
0
 protected override void SuccessCallback(MessageStructure writer, MessageHead head)
 {
     int type = writer.ReadInt();
     if (type == 1)
     {
         int recordCount = writer.ReadInt();
         JsonObject jsonContainer = new JsonObject();
         List<JsonObject> jsonList = new List<JsonObject>();
         for (int i = 0; i < recordCount; i++)
         {
             writer.RecordStart();
             var item = new JsonObject();
             item.Add("NoticeID", writer.ReadString());
             item.Add("Title",  writer.ReadString());
             item.Add("Content", writer.ReadString());
             item.Add("IsBroadcast", writer.ReadInt());
             item.Add("IsTop", writer.ReadInt());
             item.Add("Creater", writer.ReadString());
             item.Add("CreateDate", writer.ReadString());
             item.Add("ExpiryDate", writer.ReadString());
             jsonList.Add(item);
             writer.RecordEnd();
         }
         jsonContainer.Add("total", recordCount);
         jsonContainer.Add("rows", jsonList.ToArray());
         WriteTableJson(jsonContainer);
     }
 }
Beispiel #7
0
        private static JsonObject serializeObject(object obj)
        {
            PropertyInfo[] propInfo = obj.GetType().GetProperties();
            string propertyName;
            object propertyValue;
            JsonValueType type;

            JsonObject o = new JsonObject(propInfo.Length);
            foreach (var p in propInfo)
            {
                propertyName = p.Name;
                propertyValue = p.GetValue(obj);
                type = JsonValue.GetPrimitiveType(p.PropertyType);
                if (type == JsonValueType.Object)
                {
                    JsonObject o2 = serializeObject(propertyValue);
                    o.Add(propertyName, o2);
                    continue;
                }
                else if (type == JsonValueType.Array)
                {
                    JsonArray a = serializeArray((IEnumerable)propertyValue);
                    o.Add(propertyName, a);
                    continue;
                }
                else
                {
                    string value = propertyValue.ToString();
                    JsonPrimitive primitive = new JsonPrimitive(value, type);
                    o.Add(propertyName, primitive);
                }
            }
            return o;
        }
Beispiel #8
0
    public static void Main()
    {
        // Create a request using a URL that can receive a post.
        WebRequest request = WebRequest.Create ("http://api.chronojump.org:8080/ping");

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json";

        // Creates the json object
        JsonObject json = new JsonObject();
        json.Add("os_version", "Linux");
        json.Add("cj_version", "0.99");

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream = request.GetRequestStream ();
        dataStream.Write (Encoding.UTF8.GetBytes(js), 0, js.Length);

        dataStream.Close ();

        // Get the response.
        WebResponse response = request.GetResponse ();

        // Display the status (will be 201, CREATED)
        Console.WriteLine (((HttpWebResponse)response).StatusDescription);

        // Clean up the streams.
        dataStream.Close ();
        response.Close ();
    }
        internal static JsonObject Generate(WorklogInput worklogInput)
        {
            var json = new JsonObject
            {
                { "self", worklogInput.Self.ToString() },
                { "comment", worklogInput.Comment },
                { "started", worklogInput.StartDate.ToRestString() },
                { "timeSpent", worklogInput.MinutesSpent.ToString() }
            };

            if (worklogInput.Visibility != null)
            {
                json.Add("visibility", VisibilityJsonGenerator.Generate(worklogInput.Visibility).ToJson());
            }

            if (worklogInput.Author != null)
            {
                json.Add("author", BasicUserJsonGenerator.Generate(worklogInput.Author).ToJson());
            }

            if (worklogInput.UpdateAuthor != null)
            {
                //json.Add("updateAuthor", BasicUserJsonGenerator.Generate(worklogInput.UpdateAuthor).ToString());
               json.Add("updateAuthor",  worklogInput.UpdateAuthor.ToJson());
            }

            return json;
        }
Beispiel #10
0
 public JsonObject ToJSON()
 {
     JsonObject temp = new JsonObject();
     temp.Add("name", JsonValue.CreateStringValue(Name));
     temp.Add("keyid", JsonValue.CreateStringValue(KeyID));
     temp.Add("vcode", JsonValue.CreateStringValue(VCode));
     return temp;
 }
Beispiel #11
0
		public void sendLoginRequest(string username, string password, Action<string> successful, Action<string> failure)
		{
			JsonObject jsonRequest = new JsonObject ();
			jsonRequest.Add (Constants.pUserName, CoreSystem.Utils.Encrypt (username));
			jsonRequest.Add (Constants.pPassword, CoreSystem.Utils.Encrypt (password));

			TCServices.sendLogin (jsonRequest, successful, failure);
		}
        internal override JsonObject ToJson(out JsonObject properties)
        {
            var json = base.ToJson(out properties);

            properties.Add("articleBody", JsonValue.CreateStringValue(ArticleBody ?? String.Empty));
            properties.Add("articleSection", JsonValue.CreateStringValue(ArticleSection ?? String.Empty));
            properties.Add("wordCount", JsonValue.CreateNumberValue(WordCount));
            return json;
        }
Beispiel #13
0
        public JsonObject Secured()
        {
            var response = new JsonObject();

            response.Add("UserId", AuthenticatedUserId.ToString());
            response.Add("UserName", AuthenticatedUser.Identity.Name);

            return response;
        }
        protected void ConfigureInputArgs(JsonObject data)
        {
            // all the requests need an API key...
            data.Add("apiKey", ApiKey);

            // are we logged on?
            if (StreetFooRuntime.HasLogonToken)
                data.Add("logonToken", StreetFooRuntime.LogonToken);
        }
Beispiel #15
0
 private static JsonObject BuildJsonObject(String fileName, String fileDescription, String fileContent)
 {
     var file = new JsonObject();
     file.Add(fileName, new{content = fileContent});
     var jsonObject = new JsonObject();
     jsonObject.Add("description", fileDescription);
     jsonObject.Add("files", file);
     jsonObject.Add("public", true);
     return jsonObject;
 }
        internal override JsonObject ToJson(out JsonObject properties)
        {
            var json = base.ToJson(out properties);

            properties.Add("elevation", JsonValue.CreateStringValue(Elevation));
            properties.Add("latitude", JsonValue.CreateStringValue(Latitude));
            properties.Add("longitude", JsonValue.CreateStringValue(Longitude));

            return json;
        }
Beispiel #17
0
    public void ShouldReturnObjectMembers() {
      var obj = new JsonObject();
      var member = new JsonObject.JsonMember("name", "value");
      obj.Add(member);
      obj.Add(member);

      var members = obj.Value;
      Assert.That(members.Length, Is.EqualTo(2));
      Assert.That(members[0], Is.EqualTo(member));
    }
        internal override JsonObject ToJson(out JsonObject properties)
        {
            var json = base.ToJson(out properties);

            properties.Add("contactType", JsonValue.CreateStringValue(ContactType));
            properties.Add("email", JsonValue.CreateStringValue(Email));
            properties.Add("faxNumber", JsonValue.CreateStringValue(FaxNumber));
            properties.Add("telephone", JsonValue.CreateStringValue(Telephone));

            return json;
        }
    public void POSTToDataBase()
    {
        JsonObject newUser = new JsonObject();
        newUser.Add( "email", emailInputField.text);
        newUser.Add( "password", passwordInputField.text );

        _Rester.PostJSON( url + "register", newUser, ( err, result ) => {
            Debug.LogWarning( "Error: " + err );
            Debug.LogWarning( "Result: " + result );
        });
    }
Beispiel #20
0
 //Entry chat application.
 void Entry()
 {
     JsonObject userMessage = new JsonObject();
     userMessage.Add("username", userName);
     userMessage.Add("rid", channel);
     if (pclient != null) {
         pclient.request("connector.entryHandler.enter", userMessage, (data)=>{
             users = data;
             Application.LoadLevel(Application.loadedLevel + 1);
         });
     }
 }
Beispiel #21
0
		public void sendTalkNowRequest(Guid specialistID, Guid customerID, string strEnquiry, int itype, bool isCustomerTalkNow, Guid bookingId, Action<string> successful, Action<string> failure)
		{
			JsonObject jsonRequest = new JsonObject ();

			jsonRequest.Add (Constants.pSpecialistID, specialistID);
			jsonRequest.Add (Constants.pCustomerID, customerID);
			jsonRequest.Add (Constants.pEnquiry, strEnquiry);
			jsonRequest.Add (Constants.pIsTalkNow, isCustomerTalkNow);
			jsonRequest.Add (Constants.pBookingId, bookingId);

			TCServices.sendTakNowRequest (jsonRequest, successful, failure);
		}
Beispiel #22
0
 void chat(string target, string content)
 {
     JsonObject message = new JsonObject();
         message.Add("rid", LoginGUI.channel);
         message.Add("content", content);
         message.Add("from", LoginGUI.userName);
         message.Add("target", target);
         pclient.request("chat.chatHandler.send", message, (data) => {
             if (target != "*" && target != LoginGUI.userName){
                 chatRecords.Add(new ChatRecord(LoginGUI.userName, content));
             }
         });
 }
Beispiel #23
0
    public void ShouldSerializeAsJsonObject() {
      var obj = new JsonObject();
      var member = new JsonObject.JsonMember("name", new JsonString("value"));

      Assert.That(obj.AsJson(), Is.EqualTo("{}"));

      obj.Add(member);
      Assert.That(obj.AsJson(),
        Is.EqualTo("{\"name\":\"value\"}"));

      obj.Add(member);
      Assert.That(obj.AsJson(),
        Is.EqualTo("{\"name\":\"value\",\"name\":\"value\"}"));
    }
Beispiel #24
0
        protected override void DoAction()
        {
            int projectId = Convert.ToInt32(GetParam("deployId"));
            int pageSize;
            if (!int.TryParse(GetParam("pageSize"), out pageSize))
            {
                pageSize = 10;
            }
            List<DepProjectAction> projectList = SvnProcesser.DeployLog(projectId, pageSize);

            JsonObject jsonContainer = new JsonObject();

            List<JsonObject> jsonList = new List<JsonObject>();
            foreach (var item in projectList)
            {
                JsonObject jItem = new JsonObject();
                jItem.Add("Id", item.Id);
                jItem.Add("Ip", item.Ip);
                jItem.Add("DepId", item.DepId);
                jItem.Add("Type", item.Type);
                jItem.Add("Revision", item.Revision);
                jItem.Add("Status", item.Status);
                jItem.Add("ErrorMsg", FormatJson(item.ErrorMsg));
                jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                jsonList.Add(jItem);
            }
            jsonContainer.Add("rows", jsonList.ToArray());
            string comboJson = jsonContainer.ToJson();

            _context.Response.Write(comboJson);
        }
Beispiel #25
0
        protected override void DoAction()
        {
            List<DepProject> projectList = SvnProcesser.ProjectList();

            JsonObject jsonContainer = new JsonObject();

            List<JsonObject> jsonList = new List<JsonObject>();
            foreach (var item in projectList)
            {
                JsonObject jItem = new JsonObject();
                jItem.Add("SlnId", item.Id);
                jItem.Add("SlnName", item.Name);
                jItem.Add("Ip", item.Ip);
                jItem.Add("SvnPath", item.SvnPath);
                jItem.Add("SharePath", item.SharePath);
                jItem.Add("ExcludeFile", item.ExcludeFile);
                jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                jItem.Add("GameId", item.GameId);
                jsonList.Add(jItem);
            }
            jsonContainer.Add("rows", jsonList.ToArray());
            string comboJson = jsonContainer.ToJson();

            _context.Response.Write(comboJson);
        }
Beispiel #26
0
        private static void CreateFromScratch()
        {
            rootObject = new JsonObject();

            questionsCollection = new JsonObject();
            rootObject.Add(QuestionsKey, questionsCollection);
        }
Beispiel #27
0
        protected override void DoAction()
        {
            if (hasDoAction)
            {
                return;
            }
            int projectId = Convert.ToInt32(GetParam("deployId"));
            List<DepProjectItem> projectList = SvnProcesser.ProjectItemList(projectId);

            JsonObject jsonContainer = new JsonObject();

            List<JsonObject> jsonList = new List<JsonObject>();
            foreach (var item in projectList)
            {
                JsonObject jItem = new JsonObject();
                jItem.Add("Id", item.Id);
                jItem.Add("Name", item.Name);
                jItem.Add("WebSite", item.WebSite);
                jItem.Add("DeployPath", item.DeployPath);
                jItem.Add("ExcludeFile", item.ExcludeFile);
                jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                jItem.Add("ServerId", item.ServerId);
                jsonList.Add(jItem);
            }
            jsonContainer.Add("rows", jsonList.ToArray());
            string comboJson = jsonContainer.ToJson();

            _context.Response.Write(comboJson);
        }
            // Strip null values from serialized JSON.
            protected override bool TrySerializeUnknownTypes(object input, out object output)
            {
                var result = new JsonObject();

                var getters = GetCache[input.GetType()].Where(x => x.Value != null);

                foreach (var getter in getters)
                {
                    var value = getter.Value(input);
                    if (value == null)
                    {
                        continue;
                    }

                    var dictionary = value as IDictionary;
                    if (dictionary != null)
                    {
                        value = ToObject(dictionary);
                    }

                    var fieldName = MapClrMemberNameToJsonFieldName(getter.Key);

                    result.Add(fieldName, value);
                }

                output = result;
                return true;
            }
 public void OnSendMsgBtn()
 {
     string szRoute = "connector.entryHandler.notify";
     JsonObject jsonMessage = new JsonObject();
     jsonMessage.Add("key", "OnSendMsgBtn");
     m_PomeloClient.notify(szRoute, jsonMessage);
 }
Beispiel #30
0
        public void GetDataList()
        {
            _pageSize       = UrlHelper.ReqIntByGetOrPost("pagesize", _pageSize);
            _total          = UrlHelper.ReqLongByGetOrPost("total");
            _selectTypeName = UrlHelper.ReqStrByGetOrPost("selecttypename");
            _page           = UrlHelper.ReqIntByGetOrPost("page");
            _minid          = UrlHelper.ReqStrByGetOrPost("minid");
            _maxid          = UrlHelper.ReqStrByGetOrPost("maxid");
            _descOrder      = UrlHelper.ReqBoolByGetOrPost("descorder", true);

            bool IsGetTotal = UrlHelper.ReqBoolByGetOrPost("isgettotal", true);


            string[] fieldArr = new string[] {
                "[ID]"

                , "[KeyCode]"

                , "[SetupValue]"

                , "[SetupType]"

                , "[Remark]"
            };
            int pageSize   = UrlHelper.ReqIntByGetOrPost("pageSize");
            int pageNumber = UrlHelper.ReqIntByGetOrPost("pageNumber");


            string condition = MakeConditionString <DBControl.DBInfo.Tables.SystemSetup>(HttpContext.Current, "s_");

            try
            {
                JsonObject  jsonData = JsonResult(false, enumReturnTitle.GetData, "数据获取失败。");
                IDataReader idr      = null;
                if (string.IsNullOrWhiteSpace(_selectTypeName))
                {
                    throw new Exception("请指定加载页面数据的类型,如首页selecttypename=firstpage等");
                }
                enumSelectType selectType = (enumSelectType)Enum.Parse(typeof(enumSelectType), _selectTypeName, true);

                switch (selectType)
                {
                case enumSelectType.FirstPage:
                    idr = DBControl.Base.DBAccess.GetFirstPageDataIDR <DBControl.DBInfo.Tables.SystemSetup>(fieldArr.ToString(","), _descOrder, _pageSize, condition);
                    break;

                case enumSelectType.LastPage:
                    idr = DBControl.Base.DBAccess.GetLastPageDataIDR <DBControl.DBInfo.Tables.SystemSetup>(fieldArr.ToString(","), _descOrder, _pageSize, condition);
                    break;

                case enumSelectType.PrevPage:
                    idr = DBControl.Base.DBAccess.GetPrevPageDataIDR <DBControl.DBInfo.Tables.SystemSetup>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition);
                    break;

                case enumSelectType.NextPage:
                    idr = DBControl.Base.DBAccess.GetNextPageDataIDR <DBControl.DBInfo.Tables.SystemSetup>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition);
                    break;

                case enumSelectType.GoToPage:
                    idr = DBControl.Base.DBAccess.GetPageDataIDR <DBControl.DBInfo.Tables.SystemSetup>(fieldArr.ToString(","), _descOrder, _pageSize, _page, condition);
                    break;
                }

                JsonArray jArray = DataListToJson(idr, tableInfo.PKey, _descOrder, ref _minid, ref _maxid, fieldArr);

                if (jArray.Count > 0)
                {
                    jsonData = JsonResult(true, enumReturnTitle.GetData, "数据获取成功。");

                    jsonData.Add("rowsccount", jArray.Count);
                    if (IsGetTotal)
                    {
                        _total = DBControl.Base.DBAccess.Count <DBControl.DBInfo.Tables.SystemSetup>(condition);
                    }
                    jsonData.Add("total", _total);

                    jsonData.Add("minid", _minid);
                    jsonData.Add("maxid", _maxid);
                    jsonData.Add("rows", jArray);
                }
                else
                {
                    jsonData = JsonResult(false, enumReturnTitle.GetData, "没数据。");
                }

                JsonWriter jWriter = new JsonWriter();
                jsonData.Write(jWriter);
                CurrentContext.Response.Write(jWriter.ToString());
            }
            catch (Exception ex)
            {
                ReturnMsg(false, enumReturnTitle.GetData, string.Format("获取数据失败:{0}", ex.Message));
            }
        }
Beispiel #31
0
        public static void Main(string[] args)
        {
            JsonWsp.Client cli = new JsonWsp.Client("http://10.1.5.160/service/AccessService/jsonwsp/description");
            cli.SetViaProxy(true);
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: jsontest.exe <session_id>");
                return;
            }
            Console.WriteLine("Call listPermissions");
            Console.WriteLine("--------------------");
            // Build arguments
            JsonObject args_dict = new JsonObject();

            args_dict.Add("session_id", args[0]);
            // Call method
            JsonObject result = CommonCall(cli, "listPermissions", args_dict);

            if (result != null)
            {
                Jayrock.Json.JsonArray perm = (Jayrock.Json.JsonArray)result["access_identifiers"];
                foreach (string i in perm)
                {
                    Console.WriteLine(i);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Call hasPermissions");
            Console.WriteLine("-------------------");
            // Build arguments
            JsonObject args_dict2 = new JsonObject();

            args_dict2.Add("session_id", args[0]);
            args_dict2.Add("access_identifier", "product.web.10finger");
            // Call method
            result = CommonCall(cli, "hasPermission", args_dict2);
            // Print
            if (result != null)
            {
                bool access = (bool)result["has_permission"];
                if (access)
                {
                    Console.WriteLine("Access Granted");
                }
                else
                {
                    Console.WriteLine("Access Denied");
                }
            }

            Console.WriteLine();
            Console.WriteLine("Call getUserInfo");
            Console.WriteLine("----------------");
            cli    = new JsonWsp.Client("http://10.1.5.160/service/UserService/jsonwsp/description");
            result = CommonCall(cli, "getUserInfo", args_dict);

            if (result != null)
            {
                JsonObject user_info = (JsonObject)result["user_info"];
                Console.WriteLine("Org-name:    " + user_info["org_name"]);
                Console.WriteLine("Org-domain:  " + user_info["org_domain"]);
                Console.WriteLine("Org-code:    " + user_info["org_code"]);
                Console.WriteLine("Org-type:    " + user_info["org_type"]);
                Console.WriteLine("Given Name:  " + user_info["given_name"]);
                Console.WriteLine("Surname:     " + user_info["surname"]);
                Console.WriteLine("Uid:         " + user_info["uid"]);
                Console.WriteLine("Common-name: " + user_info["common_name"]);
            }
        }
        public async Task <dynamic> UpsertCommerceTierPriceEntryAsync(long commerceTierPriceEntryId, long commercePriceEntryId, string externalReferenceCode, IDictionary <string, object> price, int minQuantity, bool bulkPricing, bool discountDiscovery, IDictionary <string, object> discountLevel1, IDictionary <string, object> discountLevel2, IDictionary <string, object> discountLevel3, IDictionary <string, object> discountLevel4, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour, int displayDateMinute, int expirationDateMonth, int expirationDateDay, int expirationDateYear, int expirationDateHour, int expirationDateMinute, bool neverExpire, string priceEntryExternalReferenceCode, JsonObjectWrapper serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("commerceTierPriceEntryId", commerceTierPriceEntryId);
            _parameters.Add("commercePriceEntryId", commercePriceEntryId);
            _parameters.Add("externalReferenceCode", externalReferenceCode);
            _parameters.Add("price", price);
            _parameters.Add("minQuantity", minQuantity);
            _parameters.Add("bulkPricing", bulkPricing);
            _parameters.Add("discountDiscovery", discountDiscovery);
            _parameters.Add("discountLevel1", discountLevel1);
            _parameters.Add("discountLevel2", discountLevel2);
            _parameters.Add("discountLevel3", discountLevel3);
            _parameters.Add("discountLevel4", discountLevel4);
            _parameters.Add("displayDateMonth", displayDateMonth);
            _parameters.Add("displayDateDay", displayDateDay);
            _parameters.Add("displayDateYear", displayDateYear);
            _parameters.Add("displayDateHour", displayDateHour);
            _parameters.Add("displayDateMinute", displayDateMinute);
            _parameters.Add("expirationDateMonth", expirationDateMonth);
            _parameters.Add("expirationDateDay", expirationDateDay);
            _parameters.Add("expirationDateYear", expirationDateYear);
            _parameters.Add("expirationDateHour", expirationDateHour);
            _parameters.Add("expirationDateMinute", expirationDateMinute);
            _parameters.Add("neverExpire", neverExpire);
            _parameters.Add("priceEntryExternalReferenceCode", priceEntryExternalReferenceCode);
            this.MangleWrapper(_parameters, "serviceContext", "$languageUtil.getJSONWrapperClassName($parameter.type)", serviceContext);

            var _command = new JsonObject()
            {
                { "/commerce.commercetierpriceentry/upsert-commerce-tier-price-entry", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
Beispiel #33
0
        private static JsonValue CreateFromDynamic(object value)
        {
            JsonObject    parent = null;
            DynamicObject dynObj = value as DynamicObject;

            if (dynObj != null)
            {
                parent = new JsonObject();
                Stack <CreateFromTypeStackInfo> infoStack = new Stack <CreateFromTypeStackInfo>();
                IEnumerator <string>            keys      = null;

                do
                {
                    if (keys == null)
                    {
                        keys = dynObj.GetDynamicMemberNames().GetEnumerator();
                    }

                    while (keys.MoveNext())
                    {
                        JsonValue             child  = null;
                        string                key    = keys.Current;
                        SimpleGetMemberBinder binder = new SimpleGetMemberBinder(key);

                        if (dynObj.TryGetMember(binder, out value))
                        {
                            DynamicObject childDynObj = value as DynamicObject;

                            if (childDynObj != null)
                            {
                                child = new JsonObject();
                                parent.Add(key, child);

                                infoStack.Push(new CreateFromTypeStackInfo(parent, dynObj, keys));

                                parent = child as JsonObject;
                                dynObj = childDynObj;
                                keys   = null;

                                break;
                            }
                            else
                            {
                                if (value != null)
                                {
                                    child = value as JsonValue;

                                    if (child == null)
                                    {
                                        child = JsonValueExtensions.CreatePrimitive(value);

                                        if (child == null)
                                        {
                                            child = JsonValueExtensions.CreateFromComplex(value);
                                        }
                                    }
                                }

                                parent.Add(key, child);
                            }
                        }
                    }

                    if (infoStack.Count > 0 && keys != null)
                    {
                        CreateFromTypeStackInfo info = infoStack.Pop();

                        parent = info.JsonObject;
                        dynObj = info.DynamicObject;
                        keys   = info.Keys;
                    }
                }while (infoStack.Count > 0);
            }

            return(parent);
        }
Beispiel #34
0
        public async Task <dynamic> AddCommerceAddressAsync(string className, long classPK, string name, string description, string street1, string street2, string street3, string city, string zip, long commerceRegionId, long commerceCountryId, string phoneNumber, int type, JsonObjectWrapper serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("className", className);
            _parameters.Add("classPK", classPK);
            _parameters.Add("name", name);
            _parameters.Add("description", description);
            _parameters.Add("street1", street1);
            _parameters.Add("street2", street2);
            _parameters.Add("street3", street3);
            _parameters.Add("city", city);
            _parameters.Add("zip", zip);
            _parameters.Add("commerceRegionId", commerceRegionId);
            _parameters.Add("commerceCountryId", commerceCountryId);
            _parameters.Add("phoneNumber", phoneNumber);
            _parameters.Add("type", type);
            this.MangleWrapper(_parameters, "serviceContext", "$languageUtil.getJSONWrapperClassName($parameter.type)", serviceContext);

            var _command = new JsonObject()
            {
                { "/commerce.commerceaddress/add-commerce-address", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
        public async Task <string> GetPagesRssAsync(long companyId, long nodeId, string title, int max, string type, double version, string displayStyle, string feedURL, string entryURL, string attachmentURLPrefix, string locale)
        {
            var _parameters = new JsonObject();

            _parameters.Add("companyId", companyId);
            _parameters.Add("nodeId", nodeId);
            _parameters.Add("title", title);
            _parameters.Add("max", max);
            _parameters.Add("type", type);
            _parameters.Add("version", version);
            _parameters.Add("displayStyle", displayStyle);
            _parameters.Add("feedURL", feedURL);
            _parameters.Add("entryURL", entryURL);
            _parameters.Add("attachmentURLPrefix", attachmentURLPrefix);
            _parameters.Add("locale", locale);

            var _command = new JsonObject()
            {
                { "/wikipage/get-pages-rss", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((string)_obj);
        }
Beispiel #36
0
        public static void TestNumerics()
        {
            var jsonObject = new JsonObject();

            jsonObject.Add("byte", byte.MaxValue);
            Assert.Equal(byte.MaxValue, ((JsonNumber)jsonObject["byte"]).GetByte());

            jsonObject.Add("short", short.MaxValue);
            Assert.Equal(short.MaxValue, ((JsonNumber)jsonObject["short"]).GetInt16());

            jsonObject.Add("int", int.MaxValue);
            Assert.Equal(int.MaxValue, ((JsonNumber)jsonObject["int"]).GetInt32());

            jsonObject.Add("long", long.MaxValue);
            Assert.Equal(long.MaxValue, ((JsonNumber)jsonObject["long"]).GetInt64());

            jsonObject.Add("float", 3.14f);
            Assert.Equal(3.14f, ((JsonNumber)jsonObject["float"]).GetSingle());

            jsonObject.Add("double", 3.14);
            Assert.Equal(3.14, ((JsonNumber)jsonObject["double"]).GetDouble());

            jsonObject.Add("sbyte", sbyte.MaxValue);
            Assert.Equal(sbyte.MaxValue, ((JsonNumber)jsonObject["sbyte"]).GetSByte());

            jsonObject.Add("ushort", ushort.MaxValue);
            Assert.Equal(ushort.MaxValue, ((JsonNumber)jsonObject["ushort"]).GetUInt16());

            jsonObject.Add("uint", uint.MaxValue);
            Assert.Equal(uint.MaxValue, ((JsonNumber)jsonObject["uint"]).GetUInt32());

            jsonObject.Add("ulong", ulong.MaxValue);
            Assert.Equal(ulong.MaxValue, ((JsonNumber)jsonObject["ulong"]).GetUInt64());

            jsonObject.Add("decimal", decimal.One);
            Assert.Equal(decimal.One, ((JsonNumber)jsonObject["decimal"]).GetDecimal());
        }
        public void SetArray(String fieldName, IMessage[] value)
        {
            if (String.IsNullOrEmpty(fieldName))
                throw new System.ArgumentException("field name is null or empty");

            data.Remove(fieldName);

            if (value != null)
            {
                JsonArray arr = new JsonArray();

                for (int i = 0, max = value.Length; i < max; i++)
                {
                    arr.Add(JsonValue.Parse(((JSONMessage)value[i]).data.ToString()));
                }

                data.Add(fieldName, arr);
            }
        }
        public async Task <dynamic> UpdateOrderAsync(long groupId, long orderId, string billingFirstName, string billingLastName, string billingEmailAddress, string billingCompany, string billingStreet, string billingCity, string billingState, string billingZip, string billingCountry, string billingPhone, bool shipToBilling, string shippingFirstName, string shippingLastName, string shippingEmailAddress, string shippingCompany, string shippingStreet, string shippingCity, string shippingState, string shippingZip, string shippingCountry, string shippingPhone, string ccName, string ccType, string ccNumber, int ccExpMonth, int ccExpYear, string ccVerNumber, string comments)
        {
            var _parameters = new JsonObject();

            _parameters.Add("groupId", groupId);
            _parameters.Add("orderId", orderId);
            _parameters.Add("billingFirstName", billingFirstName);
            _parameters.Add("billingLastName", billingLastName);
            _parameters.Add("billingEmailAddress", billingEmailAddress);
            _parameters.Add("billingCompany", billingCompany);
            _parameters.Add("billingStreet", billingStreet);
            _parameters.Add("billingCity", billingCity);
            _parameters.Add("billingState", billingState);
            _parameters.Add("billingZip", billingZip);
            _parameters.Add("billingCountry", billingCountry);
            _parameters.Add("billingPhone", billingPhone);
            _parameters.Add("shipToBilling", shipToBilling);
            _parameters.Add("shippingFirstName", shippingFirstName);
            _parameters.Add("shippingLastName", shippingLastName);
            _parameters.Add("shippingEmailAddress", shippingEmailAddress);
            _parameters.Add("shippingCompany", shippingCompany);
            _parameters.Add("shippingStreet", shippingStreet);
            _parameters.Add("shippingCity", shippingCity);
            _parameters.Add("shippingState", shippingState);
            _parameters.Add("shippingZip", shippingZip);
            _parameters.Add("shippingCountry", shippingCountry);
            _parameters.Add("shippingPhone", shippingPhone);
            _parameters.Add("ccName", ccName);
            _parameters.Add("ccType", ccType);
            _parameters.Add("ccNumber", ccNumber);
            _parameters.Add("ccExpMonth", ccExpMonth);
            _parameters.Add("ccExpYear", ccExpYear);
            _parameters.Add("ccVerNumber", ccVerNumber);
            _parameters.Add("comments", comments);

            var _command = new JsonObject()
            {
                { "/shoppingorder/update-order", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
 public static void Add(this JsonObject json, string key, bool value)
 {
     json.Add(key, JsonValue.CreateBooleanValue(value));
 }
        public static void ListToDictionaryConversions(JsonObject jObject, int count)
        {
            Assert.Equal(count, jObject.Count);

            int i;

            for (i = 0; i < count; i++)
            {
                Assert.Equal(i, jObject[i.ToString()].GetValue<int>());
            }

            i = 0;
            foreach (KeyValuePair<string, JsonNode?> kvp in jObject)
            {
                Assert.Equal(i.ToString(), kvp.Key);
                Assert.Equal(i, kvp.Value.GetValue<int>());
                i++;
            }

            i = 0;
            foreach (object o in (IEnumerable)jObject)
            {
                var kvp = (KeyValuePair<string, JsonNode?>)o;
                Assert.Equal(i.ToString(), kvp.Key);
                Assert.Equal(i, kvp.Value.GetValue<int>());
                i++;
            }

            var dictionary = (IDictionary<string, JsonNode?>)jObject;

            i = 0;
            foreach (string propertyName in dictionary.Keys)
            {
                Assert.Equal(i.ToString(), propertyName);
                i++;
            }

            i = 0;
            foreach (JsonNode? node in dictionary.Values)
            {
                Assert.Equal(i, node.GetValue<int>());
                i++;
            }

            string expectedJson = jObject.ToJsonString();

            // Use indexers to replace items.
            for (i = 0; i < count; i++)
            {
                string key = i.ToString();

                // Contains does a reference comparison on JsonNode so it needs to be done before modifying.
                Assert.True(jObject.Contains(new KeyValuePair<string, JsonNode?>(key, jObject[key])));

                jObject[key] = JsonValue.Create(i);
                jObject[key] = jObject[key]; // Should have no effect.

                Assert.False(jObject.Contains(new KeyValuePair<string, JsonNode?>("MISSING", jObject[key])));
                Assert.True(jObject.ContainsKey(key));

                // Remove() should not affect result when missing.
                bool success = jObject.Remove("MISSING");
                Assert.False(success);
            }

            // JSON shouldn't change.
            Assert.Equal(expectedJson, jObject.ToJsonString());

            // Remove every other entry.
            for (i = 0; i < count; i += 2)
            {
                bool success = dictionary.Remove(i.ToString());
                Assert.True(success);
            }

            Assert.Equal(count / 2, jObject.Count);

            // The new JSON contains half the entries.
            expectedJson = jObject.ToJsonString();

            // Add back every other entry (to the end)
            for (i = 0; i < count; i += 2)
            {
                jObject.Add(i.ToString(), JsonValue.Create(i));
            }
            Assert.Equal(count, jObject.Count);

            // The beginning part of the JSON should be the same.
            string json = jObject.ToJsonString();
            Assert.Contains(expectedJson.TrimEnd('}'), json);

            const int ItemsToAdd = 10;
            for (i = 10000; i < 10000 + ItemsToAdd; i++)
            {
                jObject.Add(i.ToString(), i);
            }

            // Original items should still be in front.
            json = jObject.ToJsonString();
            Assert.Contains(expectedJson.TrimEnd('}'), json);

            Assert.Equal(count + ItemsToAdd, jObject.Count);
        }
        public async Task <IDictionary <string, object> > AddStructureAsync(long userId, long groupId, string parentStructureKey, long classNameId, string structureKey, IDictionary <string, string> nameMap, IDictionary <string, string> descriptionMap, string xsd, string storageType, int type, IDictionary <string, object> serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("userId", userId);
            _parameters.Add("groupId", groupId);
            _parameters.Add("parentStructureKey", parentStructureKey);
            _parameters.Add("classNameId", classNameId);
            _parameters.Add("structureKey", structureKey);
            _parameters.Add("nameMap", nameMap);
            _parameters.Add("descriptionMap", descriptionMap);
            _parameters.Add("xsd", xsd);
            _parameters.Add("storageType", storageType);
            _parameters.Add("type", type);
            _parameters.Add("serviceContext", serviceContext);

            var _command = new JsonObject()
            {
                { "/ddmstructure/add-structure", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((IDictionary <string, object>)_obj);
        }
        public async Task <IDictionary <string, object> > SearchAsync(long companyId, IEnumerable <long> groupIds, IEnumerable <long> classNameIds, string name, string description, string storageType, int type, bool andOperator, int start, int end, IDictionary <string, object> orderByComparator)
        {
            var _parameters = new JsonObject();

            _parameters.Add("companyId", companyId);
            _parameters.Add("groupIds", groupIds);
            _parameters.Add("classNameIds", classNameIds);
            _parameters.Add("name", name);
            _parameters.Add("description", description);
            _parameters.Add("storageType", storageType);
            _parameters.Add("type", type);
            _parameters.Add("andOperator", andOperator);
            _parameters.Add("start", start);
            _parameters.Add("end", end);
            _parameters.Add("orderByComparator", orderByComparator);

            var _command = new JsonObject()
            {
                { "/ddmstructure/search", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((IDictionary <string, object>)_obj);
        }
 public static void Add(this JsonObject json, string key, double value)
 {
     json.Add(key, JsonValue.CreateNumberValue(value));
 }
Beispiel #44
0
        private void SendChanges(string subscriberId)
        {
            using (SQLiteConnection conn = new SQLiteConnection(this.connString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection = conn;
                    conn.Open();

                    SQLiteHelper sh = new SQLiteHelper(cmd);

                    DataTable tables = sh.Select("select tbl_Name from sqlite_master where type='table' and sql like '%RowId%';");

                    StringBuilder sqlitesync_SyncDataToSend = new StringBuilder();
                    sqlitesync_SyncDataToSend.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><SyncData xmlns=\"urn:sync-schema\">");

                    foreach (DataRow table in tables.Rows)
                    {
                        string tableName = table["tbl_Name"].ToString();
                        if (tableName.ToLower() != "MergeDelete".ToLower())
                        {
                            try
                            {
                                sqlitesync_SyncDataToSend.Append("<tab n=\"" + tableName + "\">");

                                #region new records
                                DataTable newRecords = sh.Select("select * from " + tableName + " where RowId is null;");
                                sqlitesync_SyncDataToSend.Append("<ins>");
                                foreach (DataRow record in newRecords.Rows)
                                {
                                    sqlitesync_SyncDataToSend.Append("<r>");
                                    foreach (DataColumn column in newRecords.Columns)
                                    {
                                        if (column.ColumnName != "MergeUpdate")
                                        {
                                            sqlitesync_SyncDataToSend.Append("<" + column.ColumnName + ">");
                                            sqlitesync_SyncDataToSend.Append("<![CDATA[" + record[column.ColumnName].ToString() + "]]>");
                                            sqlitesync_SyncDataToSend.Append("</" + column.ColumnName + ">");
                                        }
                                    }
                                    sqlitesync_SyncDataToSend.Append("</r>");
                                }
                                sqlitesync_SyncDataToSend.Append("</ins>");
                                #endregion

                                #region updated records
                                DataTable updRecords = sh.Select("select * from " + tableName + " where MergeUpdate > 0 and RowId is not null;");
                                sqlitesync_SyncDataToSend.Append("<upd>");
                                foreach (DataRow record in updRecords.Rows)
                                {
                                    sqlitesync_SyncDataToSend.Append("<r>");
                                    foreach (DataColumn column in updRecords.Columns)
                                    {
                                        if (column.ColumnName != "MergeUpdate")
                                        {
                                            sqlitesync_SyncDataToSend.Append("<" + column.ColumnName + ">");
                                            if (record[column.ColumnName].GetType().Name == "Byte[]")
                                            {
                                                sqlitesync_SyncDataToSend.Append("<![CDATA[" + Convert.ToBase64String((byte[])record[column.ColumnName]) + "]]>");
                                            }
                                            else
                                            {
                                                sqlitesync_SyncDataToSend.Append("<![CDATA[" + record[column.ColumnName].ToString() + "]]>");
                                            }
                                            sqlitesync_SyncDataToSend.Append("</" + column.ColumnName + ">");
                                        }
                                    }
                                    sqlitesync_SyncDataToSend.Append("</r>");
                                }
                                sqlitesync_SyncDataToSend.Append("</upd>");
                                #endregion

                                sqlitesync_SyncDataToSend.Append("</tab>");
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    }

                    #region deleted records
                    DataTable delRecords = sh.Select("select * from MergeDelete;");
                    sqlitesync_SyncDataToSend.Append("<delete>");
                    foreach (DataRow record in delRecords.Rows)
                    {
                        sqlitesync_SyncDataToSend.Append("<r>");
                        sqlitesync_SyncDataToSend.Append("<tb>" + record["TableId"].ToString() + "</tb>");
                        sqlitesync_SyncDataToSend.Append("<id>" + record["RowId"].ToString() + "</id>");
                        sqlitesync_SyncDataToSend.Append("</r>");
                    }
                    sqlitesync_SyncDataToSend.Append("</delete>");
                    #endregion

                    sqlitesync_SyncDataToSend.Append("</SyncData>");

                    #region send changes to server
                    JsonObject inputObject = new JsonObject();
                    inputObject.Add("subscriber", subscriberId);
                    inputObject.Add("content", sqlitesync_SyncDataToSend.ToString());
                    inputObject.Add("version", "3");

                    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                    byte[] bytes = encoding.GetBytes(inputObject.ToString());

                    var request = new RestRequest("Send", Method.POST);
                    request.AddHeader("Content-Type", "application/json");
                    request.AddHeader("Accept", "*/*");
                    request.AddHeader("charset", "utf-8");
                    request.AddHeader("Content-Length", bytes.Length.ToString());

                    request.AddParameter("application/json; charset=utf-8", inputObject.ToString(), ParameterType.RequestBody);
                    request.RequestFormat = DataFormat.Json;

                    IRestResponse response = wsClient.Execute(request);
                    #endregion

                    #region clear update marker
                    foreach (DataRow table in tables.Rows)
                    {
                        string tableName = table["tbl_Name"].ToString().ToLower();
                        if (tableName != "MergeDelete".ToLower() && tableName != "MergeIdentity".ToLower())
                        {
                            string updTriggerSQL = (string)sh.ExecuteScalar("select sql from sqlite_master where type='trigger' and name like 'trMergeUpdate_" + tableName + "'");
                            sh.Execute("drop trigger trMergeUpdate_" + tableName + ";");
                            sh.Execute("update " + tableName + " set MergeUpdate=0 where MergeUpdate > 0;");
                            sh.Execute(updTriggerSQL);
                        }

                        if (tableName == "MergeIdentity".ToLower())
                        {
                            sh.Execute("update MergeIdentity set MergeUpdate=0 where MergeUpdate > 0;");
                        }
                    }
                    #endregion

                    #region clear delete marker
                    sh.Execute("delete from MergeDelete");
                    #endregion

                    conn.Close();
                }
            }
        }
Beispiel #45
0
        public async Task <dynamic> UpdateAddressAsync(long addressId, string street1, string street2, string street3, string city, string zip, long regionId, long countryId, long typeId, bool mailing, bool primary)
        {
            var _parameters = new JsonObject();

            _parameters.Add("addressId", addressId);
            _parameters.Add("street1", street1);
            _parameters.Add("street2", street2);
            _parameters.Add("street3", street3);
            _parameters.Add("city", city);
            _parameters.Add("zip", zip);
            _parameters.Add("regionId", regionId);
            _parameters.Add("countryId", countryId);
            _parameters.Add("typeId", typeId);
            _parameters.Add("mailing", mailing);
            _parameters.Add("primary", primary);

            var _command = new JsonObject()
            {
                { "/address/update-address", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
Beispiel #46
0
        private JsonObject ReadObject(JsonObject jsonObject)
        {
            this.scanner.Assert('{');

            this.scanner.SkipWhitespace();

            if (this.scanner.Peek() == '}')
            {
                this.scanner.Read();
            }
            else
            {
                while (true)
                {
                    this.scanner.SkipWhitespace();

                    var errorPosition = this.scanner.Position;
                    var key           = this.ReadJsonKey();

                    if (jsonObject.ContainsKey(key))
                    {
                        throw new JsonParseException(
                                  ErrorType.DuplicateObjectKeys,
                                  errorPosition);
                    }

                    this.scanner.SkipWhitespace();

                    this.scanner.Assert(':');

                    this.scanner.SkipWhitespace();

                    var value = this.ReadJsonValue();

                    jsonObject.Add(key, value);

                    this.scanner.SkipWhitespace();

                    errorPosition = this.scanner.Position;
                    var next = this.scanner.Read();
                    if (next == ',')
                    {
                        // Allow trailing commas in objects
                        this.scanner.SkipWhitespace();
                        if (this.scanner.Peek() == '}')
                        {
                            next = this.scanner.Read();
                        }
                    }

                    if (next == '}')
                    {
                        break;
                    }
                    else if (next == ',')
                    {
                        continue;
                    }
                    else
                    {
                        throw new JsonParseException(
                                  ErrorType.InvalidOrUnexpectedCharacter,
                                  errorPosition);
                    }
                }
            }

            return(jsonObject);
        }
        public JsonObject GetAsJson()
        {
            this.UpdateName();
            JsonObject jsonObj = new JsonObject();

            jsonObj.Add("add", this.add);
            jsonObj.Add("close", this.close);
            jsonObj.Add("delete", this.delete);
            jsonObj.Add("linesAdded", this.linesAdded);
            jsonObj.Add("linesRemoved", this.linesRemoved);
            jsonObj.Add("open", this.open);
            jsonObj.Add("paste", this.paste);
            jsonObj.Add("keystrokes", this.keystrokes);
            jsonObj.Add("netkeys", this.netkeys);
            jsonObj.Add("syntax", this.syntax);
            jsonObj.Add("start", this.start);
            jsonObj.Add("end", this.end);
            jsonObj.Add("local_start", this.local_start);
            jsonObj.Add("local_end", this.local_end);
            jsonObj.Add("duration_seconds", this.duration_seconds);
            jsonObj.Add("projectDir", this.projectDir);
            jsonObj.Add("fsPath", this.fsPath);
            jsonObj.Add("name", this.name);
            jsonObj.Add("update_count", this.update_count);
            jsonObj.Add("fileAgeDays", this.fileAgeDays);
            jsonObj.Add("repoFileContributorCount", this.repoFileContributorCount);
            return(jsonObj);
        }
Beispiel #48
0
        public void Enrich(LogLevel level, Type sender, JsonObject message)
        {
            var value = GetOrAdd(sender, _builder);

            message.Add(Name, value);
        }
Beispiel #49
0
        public void Add_NullKey_ThrowsArgumentNullException()
        {
            JsonObject obj = new JsonObject();

            AssertExtensions.Throws <ArgumentNullException>("key", () => obj.Add(null, new JsonPrimitive(true)));
        }
Beispiel #50
0
        // Save the level to a variable and file using FileBrowser and SaveLevelUsingPath
        private void SaveLevel()
        {
            int[,,] levelToSave = _levelEditor.GetLevel();
            int   width      = _levelEditor.Width;
            int   height     = _levelEditor.Height;
            int   layers     = _levelEditor.Layers;
            float blockScale = _levelEditor.Layers;

            //可能需要更换成json存储格式
            List <string> newLevel = new List <string>();

            // Loop through the layers
            for (int layer = 0; layer < layers; layer++)
            {
                // If the layer is not empty, add it and add \t at the end"
                if (!EmptyLayer(levelToSave, width, height, layer, LevelEditor.GetEmpty()))
                {
                    // Loop through the rows and add \n at the end"
                    for (int y = 0; y < height; y++)
                    {
                        string newRow = "";
                        for (int x = 0; x < width; x++)
                        {
                            newRow += TileSaveRepresentationToString(levelToSave, x, y, layer) + ",";
                        }

                        if (y != 0)
                        {
                            newRow += "\n";
                        }

                        newLevel.Add(newRow);
                    }

                    newLevel.Add("\t" + layer);
                }
            }

            //额外数据 三星字段 json
            JsonObject obj = new JsonObject();

            obj.Add("OneStart", _levelEditor.UiScript._StartInput[0].text);
            obj.Add("TwoStart", _levelEditor.UiScript._StartInput[1].text);
            obj.Add("ThreeStart", _levelEditor.UiScript._StartInput[2].text);
            obj.Add("RowStart", _levelEditor.rowStart + "");
            obj.Add("blockScale", _levelEditor.blockScale + "");
            obj.Add("maxCol", _levelEditor.Width + "");
            obj.Add("ballStartNum", _levelEditor.ballStartNum + "");


            newLevel.Add("%" + obj + "%");

            // Reverse the rows to make the final version rightside up
            newLevel.Reverse();
            string levelComplete = "";

            foreach (string level in newLevel)
            {
                levelComplete += level;
            }

            // Temporarily save the level to save it using SaveLevelUsingPath
            _levelToSave = levelComplete;
            // Open file browser to get the path and file name
            OpenFileBrowser();
        }
        public override void SendOrder(Order order)
        {
            _portfolioCurrent = order.PortfolioNumber;

            JsonObject jsonContent = new JsonObject();

            var contractData = order.SecurityNameCode.Split('_');

            var contractType = "quarter";

            if (contractData[1] == "CW")
            {
                contractType = "this_week";
            }
            else if (contractData[1] == "NW")
            {
                contractType = "next_week";
            }

            jsonContent.Add("symbol", contractData[0]);
            jsonContent.Add("contract_type", contractType);
            jsonContent.Add("client_order_id", order.NumberUser);
            jsonContent.Add("price", order.Price);
            jsonContent.Add("volume", order.Volume);
            jsonContent.Add("direction", order.Side == Side.Buy ? "buy" : "sell");

            // если ордер открывающий позицию - тут "open", если закрывающий - "close"
            if (order.PositionConditionType == OrderPositionConditionType.Close)
            {
                jsonContent.Add("offset", "close");
            }
            else
            {
                jsonContent.Add("offset", "open");
            }

            jsonContent.Add("lever_rate", "10");
            jsonContent.Add("order_price_type", "limit");

            string url = _privateUriBuilder.Build("POST", "/api/v1/contract_order");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadAsStringAsync().Result;

            PlaceFuturesOrderResponse orderResponse = JsonConvert.DeserializeObject <PlaceFuturesOrderResponse>(result);

            if (orderResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else
            {
                //err_msg
                dynamic errorData = JToken.Parse(result);
                string  errorMsg  = errorData.err_msg;

                SendLogMessage($"Order exchange error num {order.NumberUser} : {errorMsg}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }
Beispiel #52
0
        private static async void RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            string     value    = args.Request.Message.First().Value.ToString();
            JsonObject request  = JsonValue.Parse(value).GetObject();
            JsonObject response = new JsonObject
            {
                ["api"]    = JsonValue.CreateNumberValue(1),
                ["result"] = JsonValue.CreateStringValue("ok")
            };

            if (request.TryGetValue("nonce", out var nonce))
            {
                response.Add("nonce", nonce);
            }
            switch (request.GetNamedString("type"))
            {
            case "VERSION":
                PackageVersion version = Package.Current.Id.Version;
                response.Add("version", JsonValue.CreateStringValue(
                                 string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision)));
                break;

            case "CERT":
                try
                {
                    String info = "By selecting a certificate I accept that my name and personal ID code will be sent to service provider.";
                    switch (request.GetNamedString("lang"))
                    {
                    case "et":
                    case "est": info = "Sertifikaadi valikuga nõustun oma nime ja isikukoodi edastamisega teenusepakkujale."; break;

                    case "lt":
                    case "lit": info = "Pasirinkdama(s) sertifikatą, aš sutinku, kad mano vardas, pavardė ir asmens kodas būtų perduoti e. paslaugos teikėjui."; break;

                    case "lv":
                    case "lat": info = "Izvēloties sertifikātu, es apstiprinu, ka mans vārds un personas kods tiks nosūtīts pakalpojuma sniedzējam."; break;

                    case "ru":
                    case "rus": info = "Выбирая сертификат, я соглашаюсь с тем, что мое имя и личный код будут переданы представителю услуг."; break;

                    default: break;
                    }
                    X509Certificate2Collection list = new X509Certificate2Collection();
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        bool forSigning = request.GetNamedString("filter", "SIGN") != "AUTH";
                        foreach (X509Certificate2 x in store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.UtcNow, false))
                        {
                            foreach (var ext in x.Extensions)
                            {
                                if (ext is X509KeyUsageExtension keyExt && ((keyExt.KeyUsages & X509KeyUsageFlags.NonRepudiation) > 0) == forSigning && HasHWToken(x))
                                {
                                    list.Add(x);
                                    break;
                                }
                            }
                        }
                    }
                    if (list.Count > 0)
                    {
                        X509Certificate2Collection certs = X509Certificate2UI.SelectFromCollection(
                            list, "", info, X509SelectionFlag.SingleSelection);
                        if (certs.Count > 0)
                        {
                            response.Add("cert", JsonValue.CreateStringValue(ByteToString(certs[0].Export(X509ContentType.Cert))));
                        }
                        else
                        {
                            response["result"] = JsonValue.CreateStringValue("user_cancel");
                            response.Add("message", JsonValue.CreateStringValue("user_cancel"));
                        }
                    }
                    else
                    {
                        response["result"] = JsonValue.CreateStringValue("no_certificates");
                        response.Add("message", JsonValue.CreateStringValue("no_certificates"));
                    }
                }
                catch (Exception e)
                {
                    response["result"] = JsonValue.CreateStringValue("technical_error");
                    response.Add("message", JsonValue.CreateStringValue(e.Message));
                }
                break;

            case "SIGN":
                try
                {
                    String info = request.GetNamedString("info", "");
                    if (info.Length > 500)
                    {
                        throw new ArgumentException("Info parameter longer than 500 chars");
                    }
                    if (info.Length > 0 && MessageBox.Show(info, "", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                    {
                        throw new Exception("User cancelled");
                    }

                    string thumbprint;
                    using (X509Certificate2 cert = new X509Certificate2(StringToByte(request.GetNamedString("cert"))))
                        thumbprint = cert.Thumbprint;
                    byte[] signature;
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                        if (certs.Count == 0)
                        {
                            throw new ArgumentException("Failed to find certificate");
                        }
                        if (certs[0].PublicKey.Oid.Value.Equals("1.2.840.10045.2.1"))
                        {
                            using (ECDsa ecdsa = certs[0].GetECDsaPrivateKey())
                            {
                                if (ecdsa == null)
                                {
                                    throw new ArgumentException("Failed to find certificate token");
                                }
                                signature = ecdsa.SignHash(StringToByte(request.GetNamedString("hash")));
                            }
                        }
                        else
                        {
                            using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certs[0].PrivateKey)
                            {
                                if (rsa == null)
                                {
                                    throw new ArgumentException("Failed to find certificate token");
                                }
                                signature = rsa.SignHash(StringToByte(request.GetNamedString("hash")),
                                                         CryptoConfig.MapNameToOID(request.GetNamedString("hashtype").Replace("-", "")));
                            }
                        }
                    }
                    if (signature == null)
                    {
                        throw new Exception("Failed to sign hash");
                    }
                    response.Add("signature", JsonValue.CreateStringValue(ByteToString(signature)));
                }
                catch (Exception e)
                {
                    if (e is ArgumentException || e is ArgumentNullException)
                    {
                        response["result"] = JsonValue.CreateStringValue("invalid_argument");
                    }
                    else if (e.Message.Contains("cancelled"))
                    {
                        response["result"] = JsonValue.CreateStringValue("user_cancel");
                    }
                    else
                    {
                        response["result"] = JsonValue.CreateStringValue("technical_error");
                    }
                    response.Add("message", JsonValue.CreateStringValue(e.Message));
                }
                break;

            default:
                Application.Exit();
                return;
            }
            await args.Request.SendResponseAsync(new ValueSet { ["message"] = response.ToString() });
        }
        public async Task <IDictionary <string, object> > AddGroupAsync(long parentGroupId, long liveGroupId, string name, string description, int type, bool manualMembership, int membershipRestriction, string friendlyURL, bool site, bool active, IDictionary <string, object> serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("parentGroupId", parentGroupId);
            _parameters.Add("liveGroupId", liveGroupId);
            _parameters.Add("name", name);
            _parameters.Add("description", description);
            _parameters.Add("type", type);
            _parameters.Add("manualMembership", manualMembership);
            _parameters.Add("membershipRestriction", membershipRestriction);
            _parameters.Add("friendlyURL", friendlyURL);
            _parameters.Add("site", site);
            _parameters.Add("active", active);
            _parameters.Add("serviceContext", serviceContext);

            var _command = new JsonObject()
            {
                { "/group/add-group", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((IDictionary <string, object>)_obj);
        }
        public Dictionary <String, Object> createPayment(double amount, String currency, JsonObject customer, String success_url, String failure_url, String notification_url, String correlation_id, String country_restriction, String kyc_restriction, int min_age, int shop_id, String submerchant_id)
        {
            Dictionary <String, String> headers    = new Dictionary <String, String>();
            Dictionary <String, Object> parameters = new Dictionary <String, Object>();

            if (!String.ReferenceEquals(correlation_id, ""))
            {
                headers.Add("Correlation-ID", correlation_id);
            }

            JsonObject redirect = new JsonObject();

            redirect.Add("success_url", success_url);
            redirect.Add("failure_url", failure_url);

            JsonObject jsonObject = new JsonObject();

            jsonObject.Add("currency", currency);
            jsonObject.Add("amount", amount);
            jsonObject.Add("customer", customer);
            jsonObject.Add("type", "PAYSAFECARD");
            jsonObject.Add("redirect", redirect);
            jsonObject.Add("notification_url", notification_url);
            jsonObject.Add("shop_id", shop_id);

            if (!String.IsNullOrEmpty(country_restriction))
            {
                jsonObject.Add("country_restriction", country_restriction);
            }

            if (!String.IsNullOrEmpty(kyc_restriction))
            {
                jsonObject.Add("kyc_level", kyc_restriction);
            }

            if (min_age != 0)
            {
                jsonObject.Add("min_age", min_age);
            }

            if (!String.IsNullOrEmpty(submerchant_id))
            {
                jsonObject.Add("submerchant_id", submerchant_id);
            }

            String json = jsonObject.ToString();

            this.request = json;

            try{
                this.response = this.doRequest("", this.request, Method.POST, headers);

                Dictionary <String, Object> result = new Dictionary <String, Object>();

                // Convert Result in Dictionary
                result.Add("id", this.response.id);
                result.Add("created", this.response.created);
                result.Add("updated", this.response.updated);
                result.Add("amount", this.response.amount);
                result.Add("currency", this.response.created);
                result.Add("status", this.response.status);
                result.Add("type", this.response.type);
                Dictionary <String, Object> red = new Dictionary <String, Object>();
                red.Add("success_url", this.response.redirect.success_url);
                red.Add("failure_url", this.response.redirect.failure_url);
                red.Add("auth_url", this.response.redirect.auth_url);
                result.Add("redirect", red);
                Dictionary <String, Object> cust = new Dictionary <String, Object>();
                cust.Add("id", this.response.customer.id);
                result.Add("customer", cust);
                result.Add("notification_url", this.response.notification_url);

                return(result);
            }
            catch
            {
                return(null);
            }
        }
 /// <summary>
 /// Creates a JSON representation of this object..
 /// </summary>
 /// <param name="jsonObject">The json object.</param>
 internal virtual void InternalToJson(JsonObject jsonObject)
 {
     jsonObject.Add(XmlAttributeNames.Format, this.Format);
     jsonObject.AddTypeParameter(this.GetXmlElementName());
 }
Beispiel #56
0
        public async Task <dynamic> AddEntryAsync(long groupId, long definitionId, string format, bool schedulerRequest, long startDate, long endDate, bool repeating, string recurrence, string emailNotifications, string emailDelivery, string portletId, string pageURL, string reportName, string reportParameters, JsonObjectWrapper serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("groupId", groupId);
            _parameters.Add("definitionId", definitionId);
            _parameters.Add("format", format);
            _parameters.Add("schedulerRequest", schedulerRequest);
            _parameters.Add("startDate", startDate);
            _parameters.Add("endDate", endDate);
            _parameters.Add("repeating", repeating);
            _parameters.Add("recurrence", recurrence);
            _parameters.Add("emailNotifications", emailNotifications);
            _parameters.Add("emailDelivery", emailDelivery);
            _parameters.Add("portletId", portletId);
            _parameters.Add("pageURL", pageURL);
            _parameters.Add("reportName", reportName);
            _parameters.Add("reportParameters", reportParameters);
            this.MangleWrapper(_parameters, "serviceContext", "$languageUtil.getJSONWrapperClassName($parameter.type)", serviceContext);

            var _command = new JsonObject()
            {
                { "/reports.entry/add-entry", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
Beispiel #57
0
        public async Task <dynamic> AddAddressAsync(string className, long classPK, string street1, string street2, string street3, string city, string zip, long regionId, long countryId, long typeId, bool mailing, bool primary, JsonObjectWrapper serviceContext)
        {
            var _parameters = new JsonObject();

            _parameters.Add("className", className);
            _parameters.Add("classPK", classPK);
            _parameters.Add("street1", street1);
            _parameters.Add("street2", street2);
            _parameters.Add("street3", street3);
            _parameters.Add("city", city);
            _parameters.Add("zip", zip);
            _parameters.Add("regionId", regionId);
            _parameters.Add("countryId", countryId);
            _parameters.Add("typeId", typeId);
            _parameters.Add("mailing", mailing);
            _parameters.Add("primary", primary);
            this.MangleWrapper(_parameters, "serviceContext", "$languageUtil.getJSONWrapperClassName($parameter.type)", serviceContext);

            var _command = new JsonObject()
            {
                { "/address/add-address", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
        public async Task <dynamic> UpdateCompanyAsync(long companyId, string virtualHost, string mx, string homeURL, bool hasLogo, byte[] logoBytes, string name, string legalName, string legalId, string legalType, string sicCode, string tickerSymbol, string industry, string type, string size)
        {
            var _parameters = new JsonObject();

            _parameters.Add("companyId", companyId);
            _parameters.Add("virtualHost", virtualHost);
            _parameters.Add("mx", mx);
            _parameters.Add("homeURL", homeURL);
            _parameters.Add("hasLogo", hasLogo);
            _parameters.Add("logoBytes", logoBytes);
            _parameters.Add("name", name);
            _parameters.Add("legalName", legalName);
            _parameters.Add("legalId", legalId);
            _parameters.Add("legalType", legalType);
            _parameters.Add("sicCode", sicCode);
            _parameters.Add("tickerSymbol", tickerSymbol);
            _parameters.Add("industry", industry);
            _parameters.Add("type", type);
            _parameters.Add("size", size);

            var _command = new JsonObject()
            {
                { "/company/update-company", _parameters }
            };

            var _obj = await this.Session.InvokeAsync(_command);

            return((dynamic)_obj);
        }
 // extension method that adds a primitive value...
 public static void Add(this JsonObject json, string key, string value)
 {
     json.Add(key, JsonValue.CreateStringValue(value));
 }
Beispiel #60
-1
        public void Store()
        {
            var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var sessionJson = new JsonObject();

            if (Folder != null)
            {
                sessionJson.Add("Folder", JsonValue.CreateStringValue(Folder.Path));
            }

            if (Photo != null)
            {
                var photoJson = new JsonObject();
                photoJson.Add("Path", JsonValue.CreateStringValue(Photo.File.Path));
                var filterIdsJson = new JsonArray();
                
                foreach (var filter in Photo.Filters)
                {
                    filterIdsJson.Add(JsonValue.CreateStringValue(filter.Id));
                }

                photoJson.Add("FilterIds", filterIdsJson);

                sessionJson.Add("Photo", photoJson);
            }

            settings.Values["Session"] = sessionJson.Stringify();
        }