Beispiel #1
0
        static async Task <dynamic> DeleteApi(string url, Dictionary <string, string> headers, dynamic parameter)
        {
            var requestJson = DynamicJson.Serialize(parameter ?? new {});

            using var content = new StringContent(requestJson);
            foreach (var header in headers)
            {
                content.Headers.Add(header.Key, header.Value);
            }
            var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, url)
            {
                Content = content,
            });

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(response.StatusCode.ToString());
            }
            var responseJson = await response.Content.ReadAsStringAsync();

            dynamic result = DynamicJson.Parse(!string.IsNullOrEmpty(responseJson) ? responseJson : "{}");

            Console.WriteLine($"[REQUEST ] {url}");
            Console.WriteLine(requestJson);
            Console.WriteLine();
            Console.WriteLine($"[RESPONSE] {url}");
            Console.WriteLine(responseJson);
            Console.WriteLine();

            return(result);
        }
        public void TestSerialize()
        {
            // 声明一个匿名对象
            var obj = new
            {
                Name    = "Foo",
                Age     = 30,
                Address = new
                {
                    Country = "Japan",
                    City    = "Tokyo"
                },
                Like = new[] { "Microsoft", "Xbox" }
            };
            // 序列化
            // {"Name":"Foo","Age":30,"Address":{"Country":"Japan","City":"Tokyo"},"Like":["Microsoft","Xbox"]}
            var jsonStringFromObj = DynamicJson.Serialize(obj);

            // 还支持直接序列化数组,集合
            // [{"foo":"fooooo!","bar":1000},{"foo":"orz","bar":10}]
            var foobar = new FooBar[] {
                new FooBar {
                    foo = "fooooo!", bar = 1000
                },
                new FooBar {
                    foo = "orz", bar = 10
                }
            };
            // 序列化
            var jsonFoobar = DynamicJson.Serialize(foobar);
        }
Beispiel #3
0
        public string GetMailList()
        {
            var obj = new
            {
                startid     = 0,
                ignore_time = 1,
            };

            string outdatacode = DynamicJson.Serialize(obj);


            outdatacode = AuthCode.Encode(outdatacode, ProgrameData.sign);//用自身作为密匙把自身加密

            string requeststring = String.Format("uid={0}&outdatacode={1}&req_id={2}", ProgrameData.uid, System.Web.HttpUtility.UrlEncode(outdatacode), ProgrameData.req_id++.ToString());

            string result = "";

            while (string.IsNullOrEmpty(result) == true)
            {
                result = DoPost(ProgrameData.GameAdd + RequestUrls.GetMailList, requeststring);
                //result = AuthCode.Decode(result, ProgrameData.sign);
                result = CommonHelp.DecodeAndMapJson(result);
            }

            return(result);//未json化
        }
        public static dynamic WaitOrBattle(dynamic data)
        {
            dynamic json;

            while (true)
            {
                if (!data.IsDefined("users"))
                {
                    throw new Exception("users column is not defined");
                }
                // 対戦待ちのユーザを列挙
                Console.WriteLine("Users:");
                foreach (dynamic user in data.users)
                {
                    Console.WriteLine(string.Format("  username: {0}, rating: {1}", user.name, user.rating));
                }

                // 待つか戦うか
                string wait_battle;
                Console.Write("Wait(0) or Battle(1)? -->");
                wait_battle = Console.ReadLine();
                if (wait_battle != "0" && wait_battle != "1")
                {
                    continue;
                }
                else if (wait_battle == "0")
                {
                    var obj = new {
                        action = "wait"
                    };
                    // 送信
                    Send(DynamicJson.Serialize(obj));
                }
                else if (wait_battle == "1")
                {
                    // 戦うなら誰と戦うか
                    string username;
                    Console.Write("battle with :");
                    username = Console.ReadLine();
                    var obj = new {
                        action = "battle",
                        user   = username
                    };
                    // 送信
                    Send(DynamicJson.Serialize(obj));
                }

                // 受信
                json = DynamicJson.Parse(Recv());
                string r = CheckResult(json);
                if (r.Length == 0)
                {
                    break;
                }

                // 失敗してた
                Console.WriteLine("ERROR: " + r);
            }
            return(json);
        }
        public static void SaveWindowPlacement(FormMain form, string path)
        {
            try {
                string parent = Directory.GetParent(path).FullName;
                if (!Directory.Exists(parent))
                {
                    Directory.CreateDirectory(parent);
                }


                var wp = new WindowPlacementWrapper();



                GetWindowPlacement(form.Handle, out wp.RawData);


                string settings = DynamicJson.Serialize(wp);

                using (StreamWriter sw = new StreamWriter(path)) {
                    sw.Write(settings);
                }
            } catch (Exception ex) {
                Utility.ErrorReporter.SendErrorReport(ex, "ウィンドウ状態の保存に失敗しました。");
            }
        }
Beispiel #6
0
        /// <summary>
        /// API呼出方法(POST)(非同期)
        /// </summary>
        /// <param name="url">パス</param>
        /// <param name="requestAll">レクエスト</param>
        /// <param name="apiKey">APIのキー</param>
        /// <returns>レスポンス</returns>
        public async Task HttpPostAsync(string url, object requestAll, string apiKey)
        {
            var inputJson = DynamicJson.Serialize(requestAll);

            this._outputJson = string.Empty;

            var client = this.GetHttpClient(url);

            HttpResponseMessage response = null;
            var content = new StringContent(inputJson, Encoding.UTF8, "application/json");

            if (client.DefaultRequestHeaders.Contains("x-api-key"))
            {
                client.DefaultRequestHeaders.Remove("x-api-key");
            }

            client.DefaultRequestHeaders.Add("x-api-key", apiKey);

            //post
            response = client.PostAsync(url, content).Result;

            var responseByte = await response.Content.ReadAsByteArrayAsync();

            this._outputJson = Encoding.UTF8.GetString(responseByte);
        }
Beispiel #7
0
        /// <summary>
        /// API呼出方法(GET)(同期)
        /// </summary>
        /// <param name="url">パス</param>
        /// <param name="requestAll">リクエスト</param>
        /// <param name="apiKey">APIのキー</param>
        /// <returns>レスポンス</returns>
        public void HttpGetSync(string url, object requestAll, string apiKey)
        {
            var inputJson = DynamicJson.Serialize(requestAll);

            this._outputJson = string.Empty;

            var client = this.GetHttpClient(url);

            HttpResponseMessage response = null;
            var content = new StringContent(inputJson, Encoding.UTF8, "application/json");

            if (client.DefaultRequestHeaders.Contains("x-api-key"))
            {
                client.DefaultRequestHeaders.Remove("x-api-key");
            }

            client.DefaultRequestHeaders.Add("x-api-key", apiKey);

            var sWkJson = HttpUtility.UrlEncode(inputJson);

            // Get
            response = client.GetAsync(url + "?d=" + sWkJson).Result;

            var responseByte = response.Content.ReadAsByteArrayAsync().Result;

            this._outputJson = Encoding.UTF8.GetString(responseByte);
        }
Beispiel #8
0
        public void Exec(string func)
        {
            try
            {
                base.GetType().InvokeMember(func, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, this, null);
            }
            catch (TargetInvocationException ex)
            {
                this.ret.SetCode(1, ex.InnerException.Message);
            }
            catch (MissingMethodException)
            {
                this.ret.SetCode(1, "指定されたWeb Apiはありません。" + func);
            }
            catch (Exception ex2)
            {
                Log.Write(ex2.Message);
                this.ret.SetCode(1, ex2.Message);
            }
            string s = DynamicJson.Serialize(this.ret);

            byte[] bytes = Encoding.UTF8.GetBytes(s);
            this.res.ContentEncoding = new UTF8Encoding();
            this.res.ContentType     = "application/json";
            try
            {
                this.res.OutputStream.Write(bytes, 0, bytes.Length);
            }
            catch (Exception ex3)
            {
                Log.Write(ex3.Message);
                Log.Write(1, ex3.StackTrace);
            }
        }
        private void absButton_Click(object sender, RoutedEventArgs e)
        {
            if (selectpath != "")
            {
                warn.Visibility = Visibility.Hidden;
                //send api true
                var obj = new
                {
                    response = autoreschk.IsChecked
                };
                dynamic json = DynamicJson.Serialize(obj);
                postjson("http://intathome.azurewebsites.net/api/response", json);

                FileStream fs = new FileStream(
                    @selectpath,
                    FileMode.Open,
                    FileAccess.Read);
                byte[] bs = new byte[fs.Length];
                fs.Read(bs, 0, bs.Length);
                fs.Close();
                dynamic base64 = Convert.ToBase64String(bs);
                postjson("http://intathome.azurewebsites.net/api/blob", base64);
            }
            else
            {
                warn.Visibility = Visibility.Visible;
            }
        }
Beispiel #10
0
        public void Save()
        {
            var obj = new { data = ItemViews.Select(x => x.Item).ToList() };

            using (var writer = new StreamWriter(DATA_FILE)) {
                writer.WriteLine(DynamicJson.Serialize(obj));
            }
        }
Beispiel #11
0
        internal static void WriteJson(string file, dynamic obj)
        {
            string s = DynamicJson.Serialize(obj);

            using (StreamWriter writer = new StreamWriter(file)) {
                writer.WriteLine(s);
            }
        }
Beispiel #12
0
        public void Can_serialize_dynamic_instance()
        {
            var dog  = new { Name = "Spot" };
            var json = DynamicJson.Serialize(dog);

            Assert.IsNotNull(json);
            json.Print();
        }
Beispiel #13
0
        /// <summary>
        /// 发送模板消息
        /// 在模版消息发送任务完成后,微信服务器会将是否送达成功作为通知,发送到开发者中心中填写的服务器配置地址中。
        /// 参见WeixinExecutor.cs TEMPLATESENDJOBFINISH Event
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="content">模板消息体,由于模板众多,且结构不一,请开发者自行按照模板自行构建模板消息体,模板消息体为json字符串,请登录微信公众号后台查看</param>
        /// <returns>  { "errcode":0,"errmsg":"ok", "msgid":200228332}
        /// </returns>
        public static dynamic SendTemplateMessage(string access_token, dynamic content)
        {
            var url    = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", access_token);
            var client = new HttpClient();
            var result = client.PostAsync(url, new StringContent(DynamicJson.Serialize(content))).Result;

            return(DynamicJson.Parse(result.Content.ReadAsStringAsync().Result));
        }
Beispiel #14
0
        /// <summary>
        /// Save all control value.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, EventArgs e)
        {
            /// Get all control value by ControlProperty method.
            var ctrlList = ControlProperty.ControlProperty.Get(this.Controls);

            /// Write all control value use JSON file.
            System.IO.File.WriteAllText("ctrl.json", DynamicJson.Serialize(ctrlList.ToArray()));
        }
        /// <summary>
        /// 上传图文消息素材【订阅号与服务号认证后均可用】
        /// thumb_media_id:图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="articles">图文消息,一个图文消息支持1到10条图文</param>
        /// <returns>success: { "type":"news","media_id":"CsEf3ldqkAYJAU6EJeIkStVDSvffUJ54vqbThMgplD-VJXXof6ctX5fI6-aYyUiQ", "created_at":1391857799}</returns>
        public static dynamic UploadArtcles(string access_token, List <WeixinArtcle> articles)
        {
            var url    = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_token);
            var client = new HttpClient();
            var result = client.PostAsync(url, new StringContent(DynamicJson.Serialize(articles))).Result;

            return(DynamicJson.Parse(result.Content.ReadAsStringAsync().Result));
        }
Beispiel #16
0
        /// <summary>
        /// 增加货架
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="content">货架详情,参见官方文档
        /// 注意:货架有五个控件,每个控件post的数据都不一样。
        /// </param>
        /// <returns>
        /// {
        ///"errcode":0,
        ///"errmsg":"success",
        ///"shelf_id": 12
        ///}
        /// </returns>
        public static dynamic Add(string access_token, dynamic content)
        {
            var client = new HttpClient();
            var result = client.PostAsync(string.Format("https://api.weixin.qq.com/merchant/shelf/add?access_token={0}", access_token),
                                          new StringContent(DynamicJson.Serialize(content))).Result;

            return(DynamicJson.Parse(result.Content.ReadAsStringAsync().Result));
        }
Beispiel #17
0
        public void Can_deserialize_dynamic_instance()
        {
            var dog          = new { Name = "Spot" };
            var json         = DynamicJson.Serialize(dog);
            var deserialized = DynamicJson.Deserialize(json);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual(dog.Name, deserialized.Name);
        }
Beispiel #18
0
 public static void CleanKey(string key, bool sync = true)
 {
     CacheProvider.Provider.Remove(key);
     if (sync)
     {
         var msg = CacheSyncMsg.CreateRemoveMsg(_sender, key);
         _subscriber.Publish(_channel, DynamicJson.Serialize(msg));
     }
 }
Beispiel #19
0
        private void GatherTweetFavo()
        {
            Task.Run(() =>
            {
                ListBox.ObjectCollection idList;
                Action _GatherTweetFavo = null;
                _GatherTweetFavo        = () =>
                {
                    User readData;
                    string userId = null;

                    if (this.Api.TokenFlag == true)
                    {
                        try
                        {
                            idList = this.listBox1.Items;
                            foreach (string id in idList)
                            {
                                userId = id;
                                this.Api.TweetFavo(3, id);
                            }
                        }
                        catch (TwitterException e)
                        {
                            if (e.Status == (System.Net.HttpStatusCode) 429)
                            {
                                MessageBox.Show("API制限にかかりました");
                                Application.Exit();
                            }
                            else if (e.Status == System.Net.HttpStatusCode.NotFound)
                            {
                                using (var sr = new StreamReader("../../UserId.json"))
                                {
                                    readData = (User)DynamicJson.Parse(sr.ReadToEnd());
                                }
                                using (var sw = new StreamWriter("../../UserId.json", false))
                                {
                                    readData.UserId.Remove(userId);
                                    this.listBox1.Items.Remove(userId);
                                    string writeData = DynamicJson.Serialize(readData);
                                    sw.WriteLine(writeData);
                                }
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            _GatherTweetFavo();
                        }
                    }
                };

                while (true)
                {
                    _GatherTweetFavo();
                }
            });
        }
Beispiel #20
0
        /// <summary>
        /// 已开通银行卡列表查询
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public static string UnionAPI_OpenedData(string customerId)
        {
            com.ecc.emp.data.KeyedCollection input  = new com.ecc.emp.data.KeyedCollection("input");
            com.ecc.emp.data.KeyedCollection output = new com.ecc.emp.data.KeyedCollection("output");

            input.put("masterId", SDKConfig.MasterID); //商户号,注意生产环境上要替换成商户自己的生产商户号
            input.put("customerId", customerId);       //会员号,商户自行生成

            KeyedCollection recv         = new KeyedCollection();
            String          businessCode = "UnionAPI_Opened";
            String          toOrig       = input.toString().replace("\n", "").replace("\t", "");
            String          toUrl        = SDKConfig.sdbUnionUrl + "UnionAPI_Opened.do";

            output = NETExecute(businessCode, toOrig, toUrl);

            String errorCode = (String)output.getDataValue("errorCode");
            String errorMsg  = (String)output.getDataValue("errorMsg");


            if ((errorCode == null || errorCode.Equals("")) && (errorMsg == null || errorMsg.Equals("")))
            {
                //System.out.println("---订单状态---" + output.getDataValue("status"));
                //System.out.println("---支付完成时间---" + output.getDataValue("date"));
                String OpenId               = null;
                String accNo                = null;
                String plantBankName        = null;
                String plantBankId          = null;
                List <UnionBankModel> Mlist = new List <UnionBankModel>();
                IndexedCollection     icoll = (IndexedCollection)output.getDataElement("unionInfo");
                for (int i = 0; i < icoll.size(); i++)
                {
                    //取出index为i的一条记录,结构为KeyedCollection
                    com.ecc.emp.data.KeyedCollection kcoll = (com.ecc.emp.data.KeyedCollection)icoll.getElementAt(i);
                    OpenId        = (String)kcoll.getDataValue("OpenId");
                    accNo         = (String)kcoll.getDataValue("accNo");
                    plantBankName = (String)kcoll.getDataValue("plantBankName");

                    plantBankId = (String)kcoll.getDataValue("plantBankId");
                    UnionBankModel m = new UnionBankModel();
                    m.OpenId        = OpenId;
                    m.accNo         = accNo;
                    m.plantBankName = plantBankName;
                    m.plantBankId   = plantBankId;
                    Mlist.Add(m);
                }
                return(DynamicJson.Serialize(Mlist));

                //      return output.getDataValue("status").toString();
            }
            else
            {
                //   System.out.println("---错误码---" + output.getDataValue("errorCode"));
                //    System.out.println("---错误说明---" + output.getDataValue("errorMsg"));
                return(output.getDataValue("errorMsg").toString());
            }
            return(output.toString());
        }
Beispiel #21
0
        public static void Clear(bool sync = true)
        {
            CacheProvider.Provider.Clear();

            if (sync)
            {
                var msg = CacheSyncMsg.CreateClearMsg(_sender);
                _subscriber.Publish(_channel, DynamicJson.Serialize(msg));
            }
        }
Beispiel #22
0
        async private Task SendCommand(string s)
        {
            string str = DynamicJson.Serialize(new
            {
                requestId = RequestId++,
                command   = s
            });

            await SendMessage(Encoding.UTF8.GetBytes(str));
        }
Beispiel #23
0
        async private Task ReplyMessage(int requestId, string s)
        {
            string str = DynamicJson.Serialize(new
            {
                requestId = requestId,
                result    = s
            });

            await SendMessage(Encoding.UTF8.GetBytes(str));
        }
Beispiel #24
0
        private static void ReqWeixinToken()
        {
            var access_token = BasicAPI.GetAccessToken(AppID, AppSecret).access_token;
            var js           = JSAPI.GetTickect(access_token);
            var jssdk_ticket = js.ticket;
            var json         = DynamicJson.Serialize(new weixin_token {
                access_token = access_token, jssdk_ticket = jssdk_ticket
            });

            cache.Insert(AppID, json, null, DateTime.Now.AddSeconds(ACCESS_TOKEN_EXPIRE_SECONDS), System.Web.Caching.Cache.NoSlidingExpiration);
        }
Beispiel #25
0
        private void Save_Click_exclusion(object sender, EventArgs e)
        {
            /// Make exclusion control list.
            var exclusionList = new[] { textBox6.Name };

            /// Get all control value by ControlProperty method.
            /// After, It excepts using LINQ.
            var ctrlList = ControlProperty.ControlProperty.Get(this.Controls).Where(p => (!exclusionList.Contains(p.Name)));

            System.IO.File.WriteAllText("ctrl.json", DynamicJson.Serialize(ctrlList.ToArray()));
        }
Beispiel #26
0
 /// <summary>
 /// 重写ToString方法。用于返回此类的Json格式字符串。
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     try
     {
         return(DynamicJson.Serialize(this));
     }
     catch (Exception ex)
     {
         return(base.ToString());
     }
 }
Beispiel #27
0
 /// <summary>
 /// 序列化Json
 /// </summary>
 /// <param name="obj">对象</param>
 /// <returns></returns>
 public static string Serialize(object obj)
 {
     try
     {
         return(DynamicJson.Serialize(obj));
     }
     catch (Exception)
     {
         return(null);
     }
 }
Beispiel #28
0
        public async Task <HttpResponseMessage> FineUploadIe9()
        {
            var fineUpload = await ProcessData();

            var res = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(DynamicJson.Serialize(fineUpload), Encoding.UTF8, "text/plain")
            };

            return(res);
        }
Beispiel #29
0
        public HttpResponseMessage RefundItemSessionIe9(int id, DateTime?qqtimestamp)
        {
            var session = GetRefundItemSession(id);

            var res = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(DynamicJson.Serialize(session), Encoding.UTF8, "text/plain")
            };

            return(res);
        }
Beispiel #30
0
        //public static void commentToSlackUemura(string text)
        //{
        //    var data = generateJson(text);

        //    uploadToSlackUemura(data);
        //}


        private static string generateJson(string text)
        {
            string data = DynamicJson.Serialize(new
            {
                text       = text,
                icon_emoji = ":finish:",         //アイコンを動的に変更する
                username   = "******" //名前を動的に変更する
            });

            return(data);
        }