Beispiel #1
0
        public void loginThreadMethod()
        {
            WebClient           webClient  = new WebClient();
            NameValueCollection loginValue = new NameValueCollection();

            loginValue.Add("action", "login");
            loginValue.Add("userName", userName);
            loginValue.Add("userPwd", userPwd);
            byte[] loginValueResultByte = null;
            try
            {
                loginValueResultByte = webClient.UploadValues(permissions, "POST", loginValue);
            }
            catch (Exception e) {
                MessageBox.Show("暂时无法连接服务器,请检查您的网络连接是否正常!", "提示");
                this.btnLOgin.BeginInvoke(new loginDelegate(btnLoginShow));
                return;
            }
            string loginValueResult = System.Text.Encoding.UTF8.GetString(loginValueResultByte).Trim();

            //获取登陆数据
            jsonValue = parser.Parse(loginValueResult);
            bool   jsonIsLogin = false;
            string jsonUserId  = "";

            foreach (JsonObject field in jsonValue as JsonObjectCollection)
            {
                if (field.Name.Trim().Equals("islogin") && (bool)field.GetValue())
                {
                    jsonIsLogin = true;
                }
                if (field.Name.Equals("userId"))
                {
                    jsonUserId = field.GetValue().ToString();
                }
            }
            if (jsonIsLogin && !"".Equals(jsonUserId))
            {
                InfoHelper.islogin = true;
                InfoHelper.userId  = jsonUserId;
                this.btnLOgin.BeginInvoke(new loginDelegate(getUserInfo));
            }
            else
            {
                MessageBox.Show("如果您的帐号已通过审核,原因在于帐号已在其他地方登录 或者 软件不正常关闭!\n 请稍等五分钟后再登录 或者 请联系管理员!帐号审核请登录官网查看联系方式!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            this.btnLOgin.BeginInvoke(new loginDelegate(btnLoginShow));
        }
        public void ShowData(string jsonStr)
        {
            this.MenuClassList.Items.Clear();
            this.MenuClassList.Items.Add(Strings.MenuClassFormListFirst);
            this.MenuClassList.SelectedIndex = 0;

            this.MenuClassIDList = new List <int>();
            this.MenuClassIDList.Add(0);

            JsonTextParser       parser   = new JsonTextParser();
            JsonObjectCollection jsonData = (JsonObjectCollection)parser.Parse(jsonStr);

            JsonArrayCollection data = (JsonArrayCollection)jsonData["data"];

            for (int i = 0; i < data.Count; i++)
            {
                JsonObjectCollection itemData = (JsonObjectCollection)data[i];

                this.MenuClassList.Items.Add(((JsonStringValue)itemData["name"]).Value);
                this.MenuClassIDList.Add((int)((JsonNumericValue)itemData["id"]).Value);
            }

            //选定上一次所选定的索引
            this.MenuClassList.SelectedIndex = this.PrevSelectedIndex;
        }
Beispiel #3
0
        public static void LoadColoring()
        {
            if (!File.Exists(FileColor))
            {
                return;
            }


            string text = "", key;
            int    val;

            using (StreamReader sr = new StreamReader(FileColor)) {
                text = sr.ReadToEnd();
            }

            try {
                JsonTextParser      parser         = new JsonTextParser();
                JsonArrayCollection jsoncollection = (JsonArrayCollection)(parser.Parse(text));
                foreach (JsonObjectCollection obj in jsoncollection)
                {
                    key = obj["k"].GetValue().ToString();
                    val = Convert.ToInt32(obj["v"].GetValue());

                    if (!DictCellColor.ContainsKey(key))
                    {
                        DictCellColor.Add(key, val);
                    }
                }
            } catch (Exception ex) { }
        }
Beispiel #4
0
        public void ShowData(string jsonStr)
        {
            this.ClientList.Items.Clear();
            this.ClientIDList = new List <int>();

            JsonTextParser       parser   = new JsonTextParser();
            JsonObjectCollection jsonData = (JsonObjectCollection)parser.Parse(jsonStr);

            JsonArrayCollection data = (JsonArrayCollection)jsonData["data"];

            for (int i = 0; i < data.Count; i++)
            {
                JsonObjectCollection itemData = (JsonObjectCollection)data[i];

                string isAdmin = Strings.CommonsClientIsAdmin0;
                if (((JsonNumericValue)itemData["is_admin"]).Value == 1)
                {
                    isAdmin = Strings.CommonsClientIsAdmin1;
                }

                ListViewItem item = new ListViewItem(new string[] { "", ((JsonStringValue)itemData["name"]).Value, ((JsonStringValue)itemData["ip"]).Value, isAdmin });
                this.ClientList.Items.Add(item);

                this.ClientIDList.Add((int)((JsonNumericValue)itemData["id"]).Value);
            }
        }
Beispiel #5
0
        public List <object> JSONToList(string json)
        {
            JsonTextParser parser  = new JsonTextParser();
            JsonObject     obj     = parser.Parse(json);
            List <object>  objects = new List <object>();

            foreach (JsonObject field in obj as JsonObjectCollection)
            {
                string name  = field.Name;
                string value = string.Empty;
                string type  = field.GetValue().GetType().Name;

                switch (type)
                {
                case "String":
                    value = (string)field.GetValue();
                    break;

                case "Double":
                    value = field.GetValue().ToString();
                    break;

                case "Boolean":
                    value = field.GetValue().ToString();
                    break;

                default:
                    throw new NotSupportedException();
                }

                objects.Add(value);
            }

            return(objects);
        }
Beispiel #6
0
        public static Dictionary <int, int> GetCheck()
        {
            Dictionary <int, int> dict = Data.Idols.ToDictionary(i => i.Id, i => 0);

            if (!File.Exists(CountPath))
            {
                return(dict);
            }

            JsonTextParser      parser = new JsonTextParser();
            JsonArrayCollection root   = null;

            using (StreamReader sr = new StreamReader(CountPath)) {
                root = (JsonArrayCollection)parser.Parse(sr.ReadToEnd());
            }

            foreach (JsonObjectCollection obj in root)
            {
                try {
                    int id    = getInt(obj["Id"]);
                    int count = getInt(obj["Count"]);

                    dict[id] = count;
                }catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }

            return(dict);
        }
Beispiel #7
0
 private void ProtectFriend()
 {
     if (Operation.ProtectId != 0)
     {
         try
         {
             SetMessageLn("保护" + GetFriendNameById(Operation.ProtectId) + ":");
             string param = string.Format("verify={0}&touid={1}&_=", this._verifyCode, Operation.ProtectId);
             HH.DelayedTime = Constants.DELAY_2SECONDS;
             string content = HH.Post("http://www.kaixin001.com/bite/shield.php", param);
             //{"ret":"","prompt":"<div style='margin:20px 0 60px 60px;'><strong class='f14'>\u4f60\u5df2\u7ecf\u6210\u4e3a\u6731\u536b\u9752\u7684\u4fdd\u62a4\u5929\u4f7f\uff01<br>\u5982\u679c\u522b\u4eba\u6765\u54ac\u6731\u536b\u9752\uff0c\u4f60\u5c06\u66ff\u5979\u62b5\u6321\u4e00\u53e3\u3002<\/strong><\/div>"}
             JsonTextParser       parser  = new JsonTextParser();
             JsonObjectCollection objects = parser.Parse(content) as JsonObjectCollection;
             string ret = JsonHelper.FiltrateHtmlTags(JsonHelper.GetStringValue(objects["ret"]) + JsonHelper.GetStringValue(objects["prompt"]));
             SetMessage(ret);
         }
         catch (ThreadAbortException)
         {
             throw;
         }
         catch (ThreadInterruptedException)
         {
             throw;
         }
         catch (Exception ex)
         {
             LogHelper.Write("GameBite.ProtectFriend", ex, LogSeverity.Error);
             SetMessageLn("保护好友失败!错误:" + ex.Message);
         }
     }
 }
Beispiel #8
0
        public bool getKey(string key)
        {
            try
            {
                JsonTextParser parser = new JsonTextParser();
                JsonObject     obj    = parser.Parse(JsonValue);

                foreach (JsonObject field in obj as JsonObjectCollection)
                {
                    string name  = field.Name;
                    string value = (string)field.GetValue();

                    if (name == key)
                    {
                        return(Boolean.Parse(value));
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(true);
            }
        }
Beispiel #9
0
        private void InitializeConnection()
        {
            try {
                // clientSocket.Connect(ipEndPoint);
                myNetwork.GetConnect(txtIp.Text.Trim(), Convert.ToInt32(txtPort.Text.Trim()));

                Send_Login_Message();

                string readMessage = myNetwork.ReadMessage();

                JsonTextParser       parser = new JsonTextParser();
                JsonObject           obj    = parser.Parse(readMessage);
                JsonObjectCollection col    = (JsonObjectCollection)obj;

                string cmd = (string)col["cmd"].GetValue();
                if (cmd == "login")
                {
                    string rt = (string)col["result"].GetValue();
                    if (rt == "fail")
                    {
                        MsgBox.Show((string)col["reason"].GetValue(), "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("{0}", e.ToString());
                MsgBox.Show("in connecting...", "Error",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ConnectOn();
            GetThread();
        }
Beispiel #10
0
        public static Dictionary <string, SyncItem> GetHashList()
        {
            Dictionary <string, SyncItem> Hashlist = new Dictionary <string, SyncItem> ();

            //get remote hash data
            string HashJSON = getHashData();

            //read JSON
            JsonTextParser parser = new JsonTextParser();
            JsonObject     hashes = parser.Parse(HashJSON);

            foreach (JsonObject field in hashes as JsonObjectCollection)
            {
                if (field.GetValue().GetType().Name != "String")
                {
                    List <JsonObject> obj = (List <JsonObject>)field.GetValue();



                    SyncFile sf = new SyncFile(field.Name.ToString(), obj);
                    Hashlist.Add(field.Name, sf);
                }
                else
                {
                    //Console.WriteLine(field.Name, field.GetValue().ToString());
                }
            }

            return(Hashlist);
        }
Beispiel #11
0
        private void ReadMessage()
        {
            while (bConnected)
            {
                try {
                    string readMessage = myNetwork.ReadMessage();

                    JsonTextParser       parser = new JsonTextParser();
                    JsonObject           obj    = parser.Parse(readMessage);
                    JsonObjectCollection col    = (JsonObjectCollection)obj;

                    string cmd = (string)col["cmd"].GetValue();

                    if (cmd == "chat")
                    {
                        this.Invoke(new UpdateLogCallback(this.UpdateLog),
                                    new object[] { (string)col["msg"].GetValue() });
                    }
                }
                catch (Exception e) {
                    Console.WriteLine("{0}", e.ToString());
                    //MessageBox.Show("Error in receiving...");
                    break;
                }
                Thread.Sleep(100);
            }
        }
        private void AddConfigFrm_Load(object sender, EventArgs e)
        {
            JsonTextParser parser = new JsonTextParser();
            JsonObject     jsonValue;
            //加载用户购买的域名后缀
            WebClient           webClient       = new WebClient();
            NameValueCollection userDomainValue = new NameValueCollection();

            userDomainValue.Add("action", "getUserDomain");
            userDomainValue.Add("userId", InfoHelper.userId);
            byte[] userDomainValueResultByte = webClient.UploadValues(InfoHelper.permissions, "POST", userDomainValue);
            string userDomainValueResult     = System.Text.Encoding.UTF8.GetString(userDomainValueResultByte).Trim();

            jsonValue = parser.Parse(userDomainValueResult);
            String selectedItem = "";

            foreach (JsonObject field in jsonValue as JsonObjectCollection)
            {
                if ("0".Equals(field.Name))
                {
                    selectedItem = (String)field.GetValue();
                }
                this.comboBoxDomain.Items.Add(field.GetValue());
            }
            this.comboBoxDomain.SelectedItem = selectedItem;
        }
Beispiel #13
0
        private T ParseResponse(string responseStr)
        {
            if (responseStr == null || responseStr.Length == 0)
            {
                throw new GSearchException("The search response is null or empty");
            }

            JsonTextParser       jsonParser = new JsonTextParser();
            JsonObjectCollection response   = (JsonObjectCollection)jsonParser.Parse(responseStr);

            string responseDetails = (string)response[ResponseDetailsField].GetValue();
            int    responseStatus  = int.Parse((string)response[ResponseStatusField].GetValue().ToString());

            if (responseStatus != ResponseStatusSuccess)
            {
                throw new GSearchException(responseDetails, responseStatus);
            }

            T results = (T)Activator.CreateInstance(typeof(T));

            results.Load((JsonObjectCollection)response[ResponseDataField]);
            results.SetProxy(Proxy);

            return(results);
        }
Beispiel #14
0
        public void ReadAllMyFriends(string content, bool printMessage)
        {
            if (printMessage)
            {
                SetMessageLn("读取我的所有朋友信息...");
            }

            this._allMyFriendsList.Clear();

            //我的所有好友
            JsonTextParser      parser            = new JsonTextParser();
            JsonArrayCollection arrayAllMyFriends = parser.Parse(content) as JsonArrayCollection;

            foreach (JsonObjectCollection item in arrayAllMyFriends)
            {
                FriendInfo friend = new FriendInfo();
                friend.Id   = JsonHelper.GetIntegerValue(item["uid"]);
                friend.Name = JsonHelper.GetStringValue(item["real_name"]);
                this._allMyFriendsList.Add(friend);
                if (printMessage)
                {
                    SetMessageLn(friend.Name + "(" + friend.Id.ToString() + ")");
                }
            }

            if (printMessage)
            {
                SetMessageLn(string.Format("您有{0}个朋友", new object[] { this._allMyFriendsList.Count }));
            }
        }
Beispiel #15
0
        public static List <Listdata> Week(string weekCode, string type)
        {
            List <Listdata> list = new List <Listdata>();
            int             week = 0;

            try {
                week = Convert.ToInt32(weekCode);
            } catch { return(list); }

            try {
                string result = Network.GET(@"http://www.anissia.net/anitime/list?w=" + weekCode);

                JsonTextParser      parser = new JsonTextParser();
                JsonArrayCollection obj    = (JsonArrayCollection)parser.Parse(result);

                foreach (JsonObjectCollection item in obj)
                {
                    Listdata listitem = new Listdata()
                    {
                        Title = item["s"].GetValue().ToString(),
                        Url   = string.Format("{0}{1}", "http://www.anissia.net/anitime/cap?i=", item["i"].GetValue()),
                        Type  = type, Time = item["t"].GetValue().ToString(),
                        Tag   = item["i"].GetValue().ToString(),
                    };

                    list.Add(listitem);
                }
            } catch (Exception ex) {
                list.Clear();
            }

            return(list);
        }
        private string getOrientation()
        {
            string projectConfigPath = projectPath + @"\assets\LuamingProject.json";
            string orientation       = "landscape";

            if (!File.Exists(projectConfigPath))
            {
                System.Windows.MessageBox.Show("LuamingProject.json 파일이 없습니다!");
                return(orientation);
            }
            try
            {
                StreamReader sr     = File.OpenText(projectConfigPath);
                string       config = sr.ReadToEnd();
                sr.Close();

                JsonTextParser       jsonParser   = new JsonTextParser();
                JsonObjectCollection configObject = (JsonObjectCollection)jsonParser.Parse(config);
                orientation = configObject["ORIENTATION"].GetValue().ToString().ToLower();
                if (!orientation.Equals("landscape") && !orientation.Equals("portrait"))
                {
                    return("landscape");
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.ToString());
                return("landscape");
            }
            return(orientation);
        }
Beispiel #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "no-cache");
            Response.Expires = 0;
            Response.Buffer  = true;

            try
            {
                bytes = Request.BinaryRead(Request.TotalBytes);
                datas = Request.ContentEncoding.GetString(bytes);

                jsonParser = new JsonTextParser();
                jsonObj    = jsonParser.Parse(datas);
                jsonCol    = (JsonObjectCollection)jsonObj;

                string mode = (jsonCol["mode"] != null) ? jsonCol["mode"].GetValue().ToString() : string.Empty;

                if (mode.Equals(string.Empty))
                {
                    result.Add(new JsonStringValue("result", "154"));
                    result.Add(new JsonStringValue("message", "mode 값이 없습니다."));
                }

                if (mode.Equals("getbranchlist"))
                {
                    getbranchlist();
                    return;
                }

                if (mode.Equals("updatebranch"))
                {
                    updatebranch();
                    return;
                }

                if (mode.Equals("getcallbranchlist"))
                {
                    getcallbranchlist();
                    return;
                }

                if (mode.Equals("synccallbranch"))
                {
                    synccallbranch();
                    return;
                }
            }
            catch (Exception ex)
            {
                result.Add(new JsonStringValue("result", "153"));
                result.Add(new JsonStringValue("message", "예외오류가 발생되었습니다." + ex.Message.Replace("\"", "'").Replace("\r\n", "")));
            }
            finally
            {
                Response.Clear();
                Response.Write(result.ToString());
                Response.End();
            }
        }
Beispiel #18
0
        public static List <Listdata> GetMakerList(string url, bool noti)
        {
            List <Listdata> listMaker = new List <Listdata>();

            try {
                string result = Network.GET(url);

                JsonTextParser      parser        = new JsonTextParser();
                JsonArrayCollection objCollection = (JsonArrayCollection)parser.Parse(result);

                foreach (JsonObjectCollection item in objCollection)
                {
                    Listdata data = GetListData(item, noti);
                    if (noti)
                    {
                        data.Url = url;
                    }


                    listMaker.Add(data);
                }

                listMaker.Sort();
            } catch (Exception ex) {
                listMaker.Clear();
            }

            return(listMaker);
        }
    private void OnGUI() {

        if (GUI.Button(new Rect(100, 100, 150, 50), "二进制加载全部")) {
            TextAsset asset = Resources.Load<TextAsset>(_cBinary);
            if (asset != null) {
                ConfigVoMapMap<string, string, TaskStepVO> maps = new ConfigVoMapMap<string, string, TaskStepVO>();
                maps.LoadFromTextAsset(asset, true);
            }
        }

        if (GUI.Button(new Rect(250, 100, 150, 50), "二进制加载索引")) {
            TextAsset asset = Resources.Load<TextAsset>(_cBinary);
            if (asset != null) {
                ConfigVoMapMap<string, string, TaskStepVO> maps = new ConfigVoMapMap<string, string, TaskStepVO>();
                maps.LoadFromTextAsset(asset, false);
            }
        }

        if (GUI.Button(new Rect(400, 100, 150, 50), "二进制预加载全部")) {
            TextAsset asset = Resources.Load<TextAsset>(_cBinary);
            if (asset != null) {

                ConfigVoMapMap<string, string, TaskStepVO> maps = new ConfigVoMapMap<string, string, TaskStepVO>();
                m_StartTime = Time.realtimeSinceStartup;
                maps.Preload(asset, this, OnReadEnd, null);
            }
        }

        if (GUI.Button(new Rect(100, 150, 150, 50), "LITJSON加载")) {
            TextAsset asset = Resources.Load<TextAsset>(_cJson);
            if (asset != null) {
                LitJson.JsonMapper.ToObject<Dictionary<string, Dictionary<string, TaskStepVO>>>(asset.text);
            }
        }

        if (GUI.Button(new Rect(250, 150, 150, 50), "FastJson加载")) {
            TextAsset asset = Resources.Load<TextAsset>(_cJson);
            if (asset != null) {
                fastJSON.JSON.ToObject<Dictionary<string, Dictionary<string, TaskStepVO>>>(asset.text);
            }
        }

        if (GUI.Button(new Rect(400, 150, 150, 50), "System.Net.Json测试")) {
            
            TextAsset asset = Resources.Load<TextAsset>(_cJson);
            if (asset != null) {
                JsonTextParser parser = new JsonTextParser();
                parser.Parse(asset.text);
            }
        }

        if (GUI.Button(new Rect(550, 150, 150, 50), "Newtonsoft.Json测试")) {
            TextAsset asset = Resources.Load<TextAsset>(_cJson);
            if (asset != null) {
                Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, TaskStepVO>>>(asset.text);
            }
        }
            
    }
Beispiel #20
0
        public Object parse(String json)
        {
            BindingFlags bindingFlags = BindingFlags.Public |
                                        BindingFlags.Instance;

            var instance = Activator.CreateInstance(c);

            JsonTextParser       parser  = new JsonTextParser();
            JsonObjectCollection jObject = (JsonObjectCollection)parser.Parse(json);

            foreach (FieldInfo field in c.GetFields(bindingFlags))
            {
                String fieldName = removeTag(field.ToString());

                object value = null;

                var oValue = jObject [field.Name].GetValue();
                switch (fieldName)
                {
                case "System.String":
                    value = Convert.ToString(oValue);
                    break;

                case "System.Double":
                    value = Convert.ToDouble(oValue);
                    break;

                case "Int32":
                    value = Convert.ToInt32(oValue);
                    break;

                case "Int64":
                    value = Convert.ToInt64(oValue);
                    break;

                case "System.Boolean":
                    value = Convert.ToInt64(oValue);
                    break;

                case "System.Collections.Generic.List":
                    value = oValue;
                    break;

                default:
                    //value = parse (varToList(oValue)[0].ToString());
                    break;
                }

                field.SetValue(instance, value);

                Console.WriteLine(field.Name + "," + field.ToString() + "," + jObject [field.Name].GetValue());
            }


            return(instance);
        }
Beispiel #21
0
        /// <summary>
        /// 旧JSON转string
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static List <PFileInfos> ParseJsonString(string jsonString)//
        {
            List <PFileInfos> filelist = new List <PFileInfos>();

            //jsonString = jsonString.Substring(1, jsonString.Length - 2);

            List <string>  listString = new List <string>();
            JsonTextParser parser     = new JsonTextParser();

            while (jsonString.Length != 0)
            {
                int    index      = jsonString.IndexOf("},{");
                string itemString = null;
                if (index == -1)
                {
                    itemString = jsonString;
                }
                else
                {
                    itemString = jsonString.Substring(0, index + 1);
                }
                listString.Add(itemString);
                JsonObject jsonObj = parser.Parse(itemString);
                PFileInfos file    = new PFileInfos();
                foreach (JsonObject field in jsonObj as JsonObjectCollection)
                {
                    string fieldName  = field.Name;
                    string fieldValue = field.GetValue().ToString().Replace(",", "");
                    switch (fieldName)
                    {
                    case "fileName":
                        file.FileName = fieldValue;
                        break;

                    case "filePath":
                        file.FileAddress = fieldValue;
                        break;

                    case "fileSize":
                        file.FileSize = fieldValue;
                        break;
                    }
                }
                filelist.Add(file);
                if (index == -1)
                {
                    jsonString = "";
                }
                else
                {
                    jsonString = jsonString.Substring(index + 2);
                }
            }

            return(filelist);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            HttpWebRequest wReq;
            HttpWebResponse wRes;
            int count = CommentCount + 20;
            Uri uri = new Uri("http://powdertoy.co.uk/Browse/Comments.json?ID=" + textBox1.Text + "& Start =" + CommentCount + "&Count=" + count); // string 을 Uri 로 형변환
            wReq = (HttpWebRequest)WebRequest.Create(uri); // WebRequest 객체 형성 및 HttpWebRequest 로 형변환
            wReq.Method = "GET"; // 전송 방법 "GET" or "POST"
            wReq.ServicePoint.Expect100Continue = false;
            wReq.CookieContainer = new CookieContainer();
            string res = null;

            using (wRes = (HttpWebResponse)wReq.GetResponse())
            {
                Stream respPostStream = wRes.GetResponseStream();
                StreamReader readerPost = new StreamReader(respPostStream, Encoding.GetEncoding("EUC-KR"), true);

                res = readerPost.ReadToEnd();
            }
            JsonTextParser parser = new JsonTextParser();
            JsonObject obj = parser.Parse(res);
            JsonArrayCollection col = (JsonArrayCollection)obj;

            List<string> Username = new List<string>();
            List<string> CommentText = new List<string>();
            List<string> Timestamp = new List<string>();
            List<DateTime> Date = new List<DateTime>();

            foreach (JsonObjectCollection joc in col)
            {
                Username.Add((string)joc["Username"].GetValue());
                CommentText.Add((string)joc["Text"].GetValue());
                Timestamp.Add((string)joc["Timestamp"].GetValue());
                Console.WriteLine(Username[Username.Count - 1] + CommentText[CommentText.Count - 1] + Timestamp[Timestamp.Count - 1]);
                TimeSpan t = TimeSpan.FromSeconds(Convert.ToInt32(Timestamp[Timestamp.Count - 1]));
                Date.Add(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) + t);
                int hour = t.Hours + 9;
                if (hour > 24)
                {
                    hour = hour - 24;
                    if (hour >= 12)
                        hour = hour + 12;
                }
            }
            if (전에[1] != CommentText[1])
            {              
                notifyIcon1.Visible = true; // 트레이의 아이콘을 보이게 한다.
                notifyIcon1.BalloonTipText = CommentText[0];
                notifyIcon1.ShowBalloonTip(500);
                전에 = CommentText.ToArray();
                timer1.Start();
            }
        }
Beispiel #23
0
 public static object ParseJson(string jsonText)
 {
     if (jsonText == "{}")
     {
         return(new Hashtable());
     }
     if (!string.IsNullOrEmpty(jsonText))
     {
         JsonTextParser parser = new JsonTextParser();
         return(ParseJson(parser.Parse(jsonText)));
     }
     return(null);
 }
Beispiel #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string rqID = Request["rqid"];
            string url  = "http://www.kexiaomi.com/api/recommend/researcher?rqid=" + rqID;
            string news;

            try
            {
                HttpWebRequest  webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
                HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
                Stream          stream     = webreponse.GetResponseStream();
                StreamReader    objReader  = new StreamReader(stream, System.Text.Encoding.UTF8);
                //byte[] rsByte = new Byte[webreponse.ContentLength];  //save data in the stream
                string m_Html = objReader.ReadToEnd();

                //解析JSON语句
                JsonTextParser parser = new JsonTextParser();
                JsonObject     obj = parser.Parse(m_Html);
                int            value_code = 0; string value_msg = string.Empty;
                foreach (JsonObject field in obj as JsonObjectCollection)
                {
                    string name = field.Name;
                    switch (name)
                    {
                    case "name":
                        value_code = (int)field.GetValue();
                        break;

                    case "msg":
                        value_msg = (string)field.GetValue();
                        break;
                    }
                }
                if (value_code == 0)
                {
                    news = "自动获取成功!";
                }
                else
                {
                    news = "更新失败" + value_msg;
                }
            }
            catch (Exception)
            {
                news = "系统异常,请稍候再试!";
            }
            //System.Threading.Thread.Sleep(5000);
            Response.Write("<script type='text/javascript'>alert('" + news + "');parent.location.reload();</script>");
            // string Url=
            //Response.Redirect(Url);
        }
Beispiel #25
0
        //
        // for subscription
        //

        public void fromJSON(string msg)
        {
            string json;

            using (XmlReader xmlrd = XmlReader.Create(new StringReader(msg)))
            {
                xmlrd.ReadToFollowing(JSON);
                json = xmlrd.ReadElementString();
                // Debug.WriteLine("json string after parsing xml data : " + json);

                JsonTextParser parser = new JsonTextParser();
                m_jsonObj = parser.Parse(json);
            }
        }
Beispiel #26
0
        public static JsonObjectCollection getJson(string query)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);

            request.Method = "GET";
            HttpWebResponse response     = (HttpWebResponse)request.GetResponse();
            Stream          stream       = response.GetResponseStream();
            StreamReader    streamReader = new StreamReader(stream, Encoding.UTF8);
            string          result       = streamReader.ReadToEnd();

            JsonTextParser       parser = new JsonTextParser();
            JsonObject           obj    = parser.Parse(result);
            JsonObjectCollection col    = (JsonObjectCollection)obj;

            return(col);
        }
        private void button4_Click(object sender, EventArgs e)
        {
            CommentCount -= 20;
            HttpWebRequest wReq;
            HttpWebResponse wRes;
            int count = CommentCount;
            int startcount = CommentCount - 20;
            Uri uri = new Uri("http://powdertoy.co.uk/Browse/Comments.json?ID=" + textBox1.Text + "&Start=" + startcount + "&Count=" + count); // string 을 Uri 로 형변환
            wReq = (HttpWebRequest)WebRequest.Create(uri); // WebRequest 객체 형성 및 HttpWebRequest 로 형변환
            wReq.Method = "GET"; // 전송 방법 "GET" or "POST"
            wReq.ServicePoint.Expect100Continue = false;
            wReq.CookieContainer = new CookieContainer();
            string res = null;

            using (wRes = (HttpWebResponse)wReq.GetResponse())
            {
                Stream respPostStream = wRes.GetResponseStream();
                StreamReader readerPost = new StreamReader(respPostStream, Encoding.GetEncoding("EUC-KR"), true);

                res = readerPost.ReadToEnd();
            }
            JsonTextParser parser = new JsonTextParser();
            JsonObject obj = parser.Parse(res);
            JsonArrayCollection col = (JsonArrayCollection)obj;

            string[] Username = new string[22];
            string[] CommentText = new string[22];
            string[] Date = new string[22];
            int i = 0;
            foreach (JsonObjectCollection joc in col)
            {
                i++;
                Username[i] = (string)joc["Username"].GetValue();
                CommentText[i] = (string)joc["Text"].GetValue();
                Date[i] = (string)joc["Timestamp"].GetValue();
                Console.WriteLine(Username[i] + CommentText[i] + Date[i]);
                TimeSpan t = TimeSpan.FromSeconds(Convert.ToInt32(Date[i]));
                int hour = t.Hours + 9;
                if (hour > 24)
                {
                    hour = hour - 24;
                    if (hour >= 12)
                        hour = hour + 12;
                }
                textBox3.AppendText("닉네임: " + Username[i] + "\r\n" + "날짜: " + hour + "시" + t.Minutes + "분" + t.Seconds + "초" + " 댓글: " + CommentText[i] + "\r\n\r\n");
            }
        }
        public void Int()
        {
            textBox3.Clear();
            HttpWebRequest wReq;
            HttpWebResponse wRes;
            int count = CommentCount + 20;
            Uri uri = new Uri("http://powdertoy.co.uk/Browse/Comments.json?ID=" + textBox1.Text + "& Start =" + CommentCount + "&Count=" + count); // string 을 Uri 로 형변환
            wReq = (HttpWebRequest)WebRequest.Create(uri); // WebRequest 객체 형성 및 HttpWebRequest 로 형변환
            wReq.Method = "GET"; // 전송 방법 "GET" or "POST"
            wReq.ServicePoint.Expect100Continue = false;
            wReq.CookieContainer = new CookieContainer();
            string res = null;

            using (wRes = (HttpWebResponse)wReq.GetResponse())
            {
                Stream respPostStream = wRes.GetResponseStream();
                StreamReader readerPost = new StreamReader(respPostStream, Encoding.GetEncoding("EUC-KR"), true);

                res = readerPost.ReadToEnd();
            }
            JsonTextParser parser = new JsonTextParser();
            JsonObject obj = parser.Parse(res);
            JsonArrayCollection col = (JsonArrayCollection)obj;

            List<string> Username = new List<string>();
            List<string> CommentText = new List<string>();
            List<DateTime> Date = new List<DateTime>();
            List<string> Timestamp = new List<string>();
            foreach (JsonObjectCollection joc in col)
            {   
                Username.Add((string)joc["Username"].GetValue());
                CommentText.Add((string)joc["Text"].GetValue());
                Timestamp.Add((string)joc["Timestamp"].GetValue());
                Console.WriteLine(Username[Username.Count - 1] + CommentText[CommentText.Count - 1] + Timestamp[Timestamp.Count - 1]);
                TimeSpan t = TimeSpan.FromSeconds(Convert.ToInt32(Timestamp[Timestamp.Count - 1]));
                Date.Add(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) + t);
                int hour = t.Hours + 9;
                if (hour > 24)
                {
                    hour = hour - 24;
                    if (hour >= 12)
                        hour = hour + 12;
                }
                textBox3.AppendText("닉네임: " + Username[Username.Count - 1] + "\r\n" + "날짜:" + Date[Date.Count - 1].Year + "년" + Date[Date.Count - 1].Month + "월" + Date[Date.Count - 1].Day + "일" + hour + "시" + t.Minutes + "분" + t.Seconds + "초" + " 댓글: " + CommentText[CommentText.Count - 1] + "\r\n\r\n");
            }
            전에 = CommentText.ToArray();
        }
        public void ShowData(string jsonStr)
        {
            JsonTextParser       parser   = new JsonTextParser();
            JsonObjectCollection jsonData = (JsonObjectCollection)parser.Parse(jsonStr);

            if (((JsonNumericValue)jsonData["ok"]).Value == 1)
            {
                JsonObjectCollection data = (JsonObjectCollection)jsonData["data"];

                string imgBase64Str = ((JsonStringValue)data["img_base64str"]).Value;
                byte[] imageBytes   = Convert.FromBase64String(imgBase64Str);

                this.BigImgMemoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
                this.BigImgMemoryStream.Write(imageBytes, 0, imageBytes.Length);
                this.BigImg = Image.FromStream(this.BigImgMemoryStream);
                BigImagePictureBox.Image = this.BigImg;
            }
        }
Beispiel #30
0
        /// <summary>
        /// Google URL 줄임 서비스,
        /// </summary>
        public static string URLshorten(string longurl)
        {
            WebRequest webreq;

            JsonTextParser       objParser  = new JsonTextParser();       //json 파서
            JsonObjectCollection SentJson   = new JsonObjectCollection(); //보낼 json객체 생성
            JsonObjectCollection objRcvJson = new JsonObjectCollection(); //받을 json객체 생성
            string jsonData;
            string rtnJson;

            byte[] bytebuffer;

            SentJson.Add(new JsonStringValue("longUrl", longurl));                                      //json항목 생성
            jsonData   = SentJson.ToString();                                                           //json객체를 string으로 변환
            bytebuffer = Encoding.UTF8.GetBytes(jsonData);                                              //string json객체를 바이트코드로 변환

            webreq               = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url"); //google URL shorten API
            webreq.Method        = WebRequestMethods.Http.Post;
            webreq.ContentType   = "application/json";
            webreq.ContentLength = bytebuffer.Length;

            //리퀘스트
            using (Stream RequestStream = webreq.GetRequestStream())
            {
                RequestStream.Write(bytebuffer, 0, bytebuffer.Length);
                RequestStream.Close();
            }

            //리스폰스
            using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
            {
                using (Stream ResponseStream = webresp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(ResponseStream))
                    {
                        rtnJson = sr.ReadToEnd();
                    }
                }
            }

            objRcvJson = (JsonObjectCollection)objParser.Parse(rtnJson);

            return(objRcvJson["id"].GetValue().ToString());
        }