Пример #1
0
        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();
            }
        }
Пример #2
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);
 }
Пример #3
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);
        }
Пример #4
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);
            }
        }
Пример #5
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);
        }
Пример #6
0
        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");
            }
        }
Пример #7
0
        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;
            }
        }
Пример #9
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());
        }
Пример #10
0
    private void LoadJson()
    {
        string               LoadPos    = System.IO.File.ReadAllText("Assets/Resources/PathData.json");
        JsonTextParser       textParser = new JsonTextParser();
        JsonObjectCollection root       = textParser.Parse(LoadPos) as JsonObjectCollection;
        JsonArrayCollection  array      = root["path"] as JsonArrayCollection;

        foreach (JsonObjectCollection obj in array)
        {
            double x = (obj["X"] as JsonNumericValue).Value;
            double y = (obj["Y"] as JsonNumericValue).Value;
            movePath.Add(new MovePath((int)x / 64, 11 - (int)y / 64));
            data[(int)x / 64, 11 - (int)y / 64] = 1;
            foreach (MovePath path in movePath)  // 무브패스에 있는 가상의 길만큼.
            {
                MakeTile(path, "rpgTile024", 1);
            }
        }
    }
Пример #11
0
        private static List <Listdata> NaverParse(string html)
        {
            List <Listdata> listData = new List <Listdata>();
            int             sIndex = 0, eIndex = 0;

            try {
                sIndex = html.IndexOf("aPostFiles[", sIndex);
                if (sIndex < 0)
                {
                    throw new Exception();
                }
                sIndex = html.IndexOf("[{", sIndex);
                if (sIndex < 0)
                {
                    throw new Exception();
                }
                eIndex = html.IndexOf("}]", sIndex);
                if (eIndex < 0)
                {
                    throw new Exception();
                }

                string jsonString = html.Substring(sIndex, eIndex - sIndex + 2)
                                    .Replace("\\'", "\"")
                                    .Replace("\\\\", "\\");

                JsonTextParser      parser = new JsonTextParser();
                JsonArrayCollection files  = (JsonArrayCollection)parser.Parse(jsonString);

                foreach (JsonObjectCollection file in files)
                {
                    listData.Add(new Listdata()
                    {
                        Title = Regex.Unescape(file["encodedAttachFileName"].GetValue().ToString()),
                        Url   = file["encodedAttachFileUrl"].GetValue().ToString(),
                        Type  = "File"
                    });
                }
            }
            catch (Exception ex) {
            }
            return(listData);
        }
Пример #12
0
        private XmlDocument ParseXml(DownloadStringCompletedEventArgs e, out string error)
        {
            error = null;

            if (e.Error != null)
            {
                error = "ERROR: " + e.Error.Message.ToUpper();
                return(null);
            }

            string data = e.Result;

            if (string.IsNullOrWhiteSpace(data))
            {
                return(null);
            }

            // Check if the data is JSON.
            if (data[0] == '{' && data[data.Length - 1] == '}')
            {
                try
                {
                    JsonTextParser       jsonParser = new JsonTextParser();
                    JsonObjectCollection json       = jsonParser.Parse(data) as JsonObjectCollection;

                    error = json["cod"].GetValue().ToString() + ": " + json["message"].GetValue().ToString().ToUpper();
                    return(null);
                }
                catch (FormatException) { }
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.InnerXml = data;
                return(doc);
            }
            catch (XmlException)
            { }

            return(null);
        }
Пример #13
0
        private void applyConfig()
        {
            string projectConfigPath = MainWindow.projectPath + @"\assets\LuamingProject.json";

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

                JsonTextParser       jsonParser   = new JsonTextParser();
                JsonObjectCollection configObject = (JsonObjectCollection)jsonParser.Parse(config);
                string prevProjectName            = projectName;
                projectName = configObject["PROJECT_NAME"].GetValue().ToString();
                project_name_label.Content = projectName;
                versionName = configObject["VERSION_NAME"].GetValue().ToString();
                packageName = configObject["PACKAGE_NAME"].GetValue().ToString();

                if (prevProjectName != projectName)
                {
                    string newPath = projectPath.Replace(prevProjectName, projectName);
                    Directory.Move(projectPath, newPath);
                    projectPath = newPath;
                    project_path_textbox.Text = projectPath;
                    StreamWriter sw = File.CreateText(lastBrowsingDataFile);
                    sw.WriteLine(projectPath);
                    sw.Close();
                }
            }
            catch (IOException)
            {
                System.Windows.MessageBox.Show("프로젝트 폴더가 열려있어 이름을 바꿀 수 없습니다.");
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.ToString());
            }
        }
        private void Init()
        {
            string projectConfigPath = MainWindow.projectPath + @"\assets\LuamingProject.json";

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

                JsonTextParser       jsonParser   = new JsonTextParser();
                JsonObjectCollection configObject = (JsonObjectCollection)jsonParser.Parse(config);
                project_name_textbox.Text = configObject["PROJECT_NAME"].GetValue().ToString();
                package_name_textbox.Text = configObject["PACKAGE_NAME"].GetValue().ToString();
                version_name_textbox.Text = configObject["VERSION_NAME"].GetValue().ToString();
                version_code_textbox.Text = configObject["VERSION_CODE"].GetValue().ToString();
                JsonObject offlineIconObject = configObject["OFFLINE_ICON"];
                if (offlineIconObject != null)
                {
                    offline_icon_textbox.Text = offlineIconObject.GetValue().ToString();
                }
                main_script_textbox.Text = configObject["MAIN_SCRIPT"].GetValue().ToString();
                string orientation = configObject["ORIENTATION"].GetValue().ToString().ToLower();
                if (orientation.Equals("portrait"))
                {
                    radioLandscape.IsChecked = false;
                    radioPortrait.IsChecked  = true;
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.ToString());
                this.DialogResult = false;
                Close();
            }
        }
Пример #15
0
        public void ShowData(string jsonStr)
        {
            JsonTextParser       parser   = new JsonTextParser();
            JsonObjectCollection jsonData = (JsonObjectCollection)parser.Parse(jsonStr);

            if (((JsonStringValue)jsonData["cmd"]).Value.Equals(AppConfig.CLIENT_WANT_MENU_CLASS))
            {
                this.MenuClassData = (JsonArrayCollection)jsonData["data"];

                this.MenuClassList.Items.Clear();
                this.MenuClassList.Items.Add(Strings.MenuFormListFirst);
                this.MenuClassList.SelectedIndex = 0;

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

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

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

                //选定上一次所选定的索引
                //this.MenuClassList.SelectedIndex = this.PrevSelectedIndex;
            }
            else if (((JsonStringValue)jsonData["cmd"]).Value.Equals(AppConfig.CLIENT_WANT_MENU))
            {
                this.MenuData = (JsonArrayCollection)jsonData["data"];

                this.MenuDataList.Items.Clear();
                for (int i = 0; i < this.MenuData.Count; i++)
                {
                    JsonObjectCollection itemData = (JsonObjectCollection)this.MenuData[i];

                    ListViewItem item = new ListViewItem(new string[] { "", ((JsonStringValue)itemData["name"]).Value, ((JsonNumericValue)itemData["price"]).Value.ToString("f1"), ((JsonStringValue)itemData["mc_name"]).Value, Commons.UnixTimeFrom((long)((JsonNumericValue)itemData["add_time"]).Value).ToString("yyyy-MM-dd") });
                    this.MenuDataList.Items.Add(item);
                }
            }
        }
        public void ShowData(string jsonStr)
        {
            this.ReportList.Items.Clear();

            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];
                if (itemData["total_price"].GetValue() == null)
                {
                    continue;
                }

                ListViewItem item = new ListViewItem(new string[] { "", Commons.UnixTimeFrom((long)((JsonNumericValue)itemData["time"]).Value).ToString("yyyy-MM"), ((int)((JsonNumericValue)itemData["total"]).Value).ToString(), ((int)((JsonNumericValue)itemData["total_quantity"]).Value).ToString(), ((float)((JsonNumericValue)itemData["total_price"]).Value).ToString("f1") });
                this.ReportList.Items.Add(item);
            }
        }
        public void TestValidText()
        {
            double[] longitudes = { -6.043701, -10.27699, -10.4240951, -7.915833, -7 };
            double[] latitudes  = { 52.986375, 51.92893, 51.8856167, 53.74452, 51.999447 };
            int[]    userIds    = { 12, 1, 2, 20, 31 };
            string[] names      = { "Christina McArdle", "Alice Cahill", "Ian McArdle", "Georgina Gallagher", "Jack Dempsey" };

            var builder = new StringBuilder();

            for (int i = 0; i < longitudes.Length; ++i)
            {
                builder
                .AppendFormat("{{\"latitude\": \"{0}\", \"user_id\": {1}, \"name\": \"{2}\", \"longitude\": \"{3}\"}}",
                              latitudes[i].ToString().Replace(',', '.'), userIds[i], names[i], longitudes[i].ToString().Replace(',', '.'))
                .AppendLine();
            }

            var jsonReader = new JsonTextParser();
            var customers  = jsonReader.ParseText(builder.ToString().TrimEnd());

            Assert.AreEqual(customers.Count, longitudes.Length,
                            string.Format("Wrong number of customers read! Expected number of customers: {0}, number of read customers: {1}.",
                                          longitudes.Length, customers.Count));

            for (int i = 0; i < customers.Count; ++i)
            {
                var customer          = customers[i];
                var customerLongitude = customer.Location.DegreeLongitude;
                var customerLatitude  = customer.Location.DegreeLatitude;
                Assert.IsTrue(Math.Abs(customerLongitude - longitudes[i]) < 2 * double.Epsilon,
                              string.Format("Wrong customer longitude read! Expected: {0}, got: {1}", longitudes[i], customerLongitude));
                Assert.IsTrue(Math.Abs(customerLatitude - latitudes[i]) < 2 * double.Epsilon,
                              string.Format("Wrong customer latitude read! Expected: {0}, got: {1}", latitudes[i], customerLatitude));
                Assert.AreEqual(customer.UserId, userIds[i],
                                string.Format("Wrong user ID read! Expected {0}, got {1}.", userIds[i], customer.UserId));
                Assert.AreEqual(customer.Name, names[i],
                                string.Format("Wrong customer name read! Expected {0}, got {1}.", names[i], customer.Name));
            }
        }
Пример #18
0
        private string GetBiteFeedBack(string content)
        {
            try
            {
                if (content.Length < 4)
                {
                    SetMessageLn("失败!");
                    return(string.Empty);
                }

                JsonTextParser       parser  = new JsonTextParser();
                JsonObjectCollection objects = parser.Parse(content) as JsonObjectCollection;
                string ret = JsonHelper.FiltrateHtmlTags(JsonHelper.GetStringValue(objects["ret"]) + JsonHelper.GetStringValue(objects["prompt"]));
                if (ret.IndexOf("对方体力已经处于耗尽状态,你不能再咬了") > -1 || ret.IndexOf("根据你的级别,1天只能咬同1个人2次") > -1)
                {
                    ret += " 失败!";
                }
                else
                {
                    ret += " 成功!";
                }
                SetMessage(ret);
                return(ret);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (ThreadInterruptedException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.Write("GameBite.GetBiteFeedBack", content, ex, LogSeverity.Error);
                return("");
            }
        }
Пример #19
0
        public JsonLoader()
        {
            if (!System.IO.File.Exists(strLocalPath + "\\info.json"))
            {
                return; //파일없음
            }
            string strReturnValue = System.IO.File.ReadAllText("info.json");

            if (strReturnValue == "")
            {
                return; //불러오기 실패
            }
            JsonTextParser       jtr = new JsonTextParser();
            JsonObject           jo  = jtr.Parse(strReturnValue);
            JsonObjectCollection jac = (JsonObjectCollection)jo;

            Address  = (jac["Address"].GetValue() != null) ? jac["Address"].GetValue().ToString() : "irc.twitch.tv";
            Ports    = (jac["Ports"].GetValue() != null) ? int.Parse(jac["Ports"].GetValue().ToString()) : 6667;
            Password = (jac["Password"].GetValue() != null) ? jac["Password"].GetValue().ToString() : "";
            Nickname = (jac["Nickname"].GetValue() != null) ? jac["Nickname"].GetValue().ToString() : "";
            Channel  = (jac["Channel"].GetValue() != null) ? jac["Channel"].GetValue().ToString() : "";
            Color    = (jac["Color"].GetValue() != null) ? jac["Color"].GetValue().ToString() : "#FFFFFF";
        }
Пример #20
0
        public void LoadJsonFile(ListBox JsonList, TreeView VariableList, Button StartBtn)
        {
            if (JsonList.SelectedIndices.Count > 0)
            {
                string       fileName = JsonList.SelectedItem.ToString();
                StreamReader sr       = new StreamReader(m_jsonFilePath + fileName);

                // 파일에서 다 읽는다
                string jsonText = sr.ReadToEnd();

                // 빈 파일이면?
                if (jsonText.Length == 0)
                {
                    // 파싱 없이 리턴
                    MessageBox.Show("Empty File!");
                    return;
                }

                // 파싱한 다음
                JsonTextParser parser = new JsonTextParser();
                JsonObject     obj    = parser.Parse(jsonText);

                // JSON 멤버 변수로 전달한다
                m_JsonCollection = (JsonObjectCollection)obj;

                // TreeVIew에 계층별로 집어넣는다
                ShowJsonData(VariableList);

                MessageBox.Show("Load Json Success!");

                // 스트림 리더를 닫는다.
                sr.Close();

                // 시작 버튼을 선택 가능하게
                StartBtn.Enabled = true;
            }
        }
Пример #21
0
        public static List <Idol> GetIdols()
        {
            List <Idol> idols = new List <Idol>();

            if (!File.Exists(DataPath))
            {
                return(idols);
            }

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

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

            foreach (JsonObjectCollection obj in root)
            {
                int    id                   = getInt(obj["Id"]);
                string rarity               = getString(obj["Rarity"]);
                int    rarityNumber         = getInt(obj["RarityNumber"]);
                string type                 = getString(obj["Type"]);
                int    cute                 = getInt(obj["Vocal"]);
                int    cool                 = getInt(obj["Dance"]);
                int    passion              = getInt(obj["Visual"]);
                string name                 = getString(obj["Name"]);
                string originalName         = getString(obj["OriginalName"]);
                string centerSkill          = getString(obj["CenterSkill"]);
                string centerSkillType      = getString(obj["CenterSkillType"]);
                string centerSkillCondition = getString(obj["CenterSkillCondition"]);
                string skill                = getString(obj["Skill"]);

                idols.Add(new Idol(id, rarity, rarityNumber, type, cute, cool, passion, name, originalName, centerSkill, centerSkillType, centerSkillCondition, skill));
            }

            return(idols);
        }
Пример #22
0
        public static bool Load()
        {
            if (!File.Exists(SettingPath))
            {
                Save();
                return(false);
            }

            try {
                using (StreamReader sr = new StreamReader(SettingPath)) {
                    string text = sr.ReadToEnd();

                    JsonTextParser       parser  = new JsonTextParser();
                    JsonObjectCollection collect = (JsonObjectCollection)parser.Parse(text);

                    Server     = collect["Server"].GetValue().ToString();
                    Token      = collect["Token"].GetValue().ToString();
                    SaveMethod = collect["SaveMethod"].GetValue().ToString();
                }
            } catch (Exception ex) {
                //MessageBox.Show(ex.Message);
            }
            return(true);
        }
Пример #23
0
        static void Main(string[] args)
        {
            // 1. parse sample

            Console.WriteLine();
            Console.WriteLine("Source data:");
            Console.WriteLine(jsonText);
            Console.WriteLine();

            JsonTextParser parser = new JsonTextParser();
            JsonObject     obj    = parser.Parse(jsonText);

            Console.WriteLine();
            Console.WriteLine("Parsed data with indentation in JSON data format:");
            Console.WriteLine(obj.ToString());
            Console.WriteLine();


            JsonUtility.GenerateIndentedJsonText = false;

            Console.WriteLine();
            Console.WriteLine("Parsed data without indentation in JSON data format:");
            Console.WriteLine(obj.ToString());
            Console.WriteLine();


            // enumerate values in json object
            Console.WriteLine();
            Console.WriteLine("Parsed object contains these nested fields:");
            foreach (JsonObject field in obj as JsonObjectCollection)
            {
                string name  = field.Name;
                string value = string.Empty;
                string type  = field.GetValue().GetType().Name;

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

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

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

                default:
                    // in this sample we'll not parse nested arrays or objects.
                    throw new NotSupportedException();
                }

                Console.WriteLine("{0} {1} {2}",
                                  name.PadLeft(15), type.PadLeft(10), value.PadLeft(15));
            }

            Console.WriteLine();


            // 2. generate sample
            Console.WriteLine();

            // root object
            JsonObjectCollection collection = new JsonObjectCollection();

            // nested values
            collection.Add(new JsonStringValue("FirstName", "Pavel"));
            collection.Add(new JsonStringValue("LastName", "Lazureykis"));
            collection.Add(new JsonNumericValue("Age", 23));
            collection.Add(new JsonStringValue("Email", "*****@*****.**"));
            collection.Add(new JsonBooleanValue("HideEmail", true));

            Console.WriteLine("Generated object:");
            JsonUtility.GenerateIndentedJsonText = true;
            Console.WriteLine(collection);

            Console.WriteLine();

            Console.ReadLine();
        }
Пример #24
0
        /// <summary>
        /// DS2JsonString으로 변환된 json문자열을 Dataset으로 변환
        /// </summary>
        public static System.Data.DataSet JsonString2DS(string json_str)
        {
            System.Data.DataSet            DS        = new System.Data.DataSet();
            System.Net.Json.JsonTextParser objParser = new JsonTextParser();

            JsonObjectCollection dataset = null;
            bool parsingSuccess;

            try
            {
                dataset        = (JsonObjectCollection)objParser.Parse(json_str);//데이터셋
                parsingSuccess = true;
            }
            catch (Exception ex)
            {
                libMyUtil.clsFile.writeLog("ERR PARSING JSON : " + ex.ToString());
                parsingSuccess = false;
            }

            if (parsingSuccess)
            {
                JsonArrayCollection  datatable;
                JsonObjectCollection datarow;
                JsonArrayCollection  datacolumn;
                JsonObjectCollection cell;

                string columnName;
                string columnValue;
                int    tableIdx;
                int    rowIdx;
                int    columnIdx;

                for (tableIdx = 0; tableIdx < dataset.Count; tableIdx++)
                {
                    datatable = (JsonArrayCollection)dataset[tableIdx];//데이터테이블
                    DS.Tables.Add();
                    for (rowIdx = 0; rowIdx < datatable.Count; rowIdx++)
                    {
                        datarow    = (JsonObjectCollection)datatable[rowIdx]; //데이터로우
                        datacolumn = (JsonArrayCollection)datarow[0];         //데이터컬럼 구조

                        DS.Tables[tableIdx].Rows.Add(DS.Tables[tableIdx].NewRow());
                        for (columnIdx = 0; columnIdx < datacolumn.Count; columnIdx++)
                        {
                            cell = (JsonObjectCollection)datacolumn[columnIdx];//셀

                            if (rowIdx == 0)
                            {
                                columnName = cell["e_id"].GetValue().ToString();
                                DS.Tables[tableIdx].Columns.Add();
                                DS.Tables[tableIdx].Columns[columnIdx].ColumnName = columnName;
                            }

                            columnValue = cell["e_value"].GetValue().ToString();
                            DS.Tables[tableIdx].Rows[rowIdx][columnIdx] = columnValue;
                        }
                    }
                }
            }

            return(DS);
        }
Пример #25
0
        private void LoadSetting()
        {
            textVersion.Text = Version.NowVersion;

            if (Directory.Exists(@"X:\Anime"))
            {
                Status.Root = true;
                SetImageByMode(buttonArrange, Tab, true, TabMode.Season);
            }

            ClearFolder();

            if (Migration.CheckMigration())
            {
                Setting.SaveSetting();
            }
            else
            {
                if (!File.Exists(Setting.FileSetting))
                {
                    Setting.SaveSetting();
                }

                using (StreamReader sr = new StreamReader(Setting.FileSetting)) {
                    string text = sr.ReadToEnd();

                    JsonTextParser       parser         = new JsonTextParser();
                    JsonObjectCollection jsoncollection = (JsonObjectCollection)(parser.Parse(text));

                    // Setting
                    JsonObjectCollection jsonSetting = (JsonObjectCollection)jsoncollection["Setting"];
                    foreach (JsonStringValue value in jsonSetting)
                    {
                        switch (value.Name)
                        {
                        case "SaveDirectory":
                            Setting.SaveDirectory = value.Value;
                            break;

                        case "Tray":
                            Setting.Tray = Convert.ToBoolean(value.Value);
                            break;

                        case "NoQuestion":
                            Setting.NoQuestion = Convert.ToBoolean(value.Value);
                            break;

                        case "OldVersion":
                            Version.OldVersion = value.Value;
                            break;

                        case "ShowRaws":
                            Setting.ShowRaws = Convert.ToBoolean(value.Value);
                            break;
                        }
                    }

                    // Archive

                    JsonArrayCollection jsonArchive = (JsonArrayCollection)jsoncollection["Archive"];
                    foreach (JsonObjectCollection value in jsonArchive)
                    {
                        ArchiveData data = new ArchiveData();

                        data.Title   = value["Title"].GetValue().ToString();
                        data.Episode = Convert.ToInt32(value["Episode"].GetValue());

                        if (value["SeasonTitle"] != null)
                        {
                            data.SeasonTitle = value["SeasonTitle"].GetValue().ToString();
                        }

                        Data.DictArchive.Add(data.Title, data);
                    }

                    // Season

                    JsonArrayCollection jsonSeason = (JsonArrayCollection)jsoncollection["Season"];
                    foreach (JsonObjectCollection value in jsonSeason)
                    {
                        SeasonData data = new SeasonData();

                        data.Title        = value["Title"].GetValue().ToString();
                        data.Week         = Convert.ToInt32(value["Week"].GetValue());
                        data.TimeString   = value["TimeString"].GetValue().ToString();
                        data.Keyword      = value["Keyword"].GetValue().ToString();
                        data.ArchiveTitle = value["ArchiveTitle"].GetValue().ToString();

                        Data.DictSeason.Add(data.Title, data);
                    }
                }
            }

            ApplySettingToControl();
            InitTray();

            checkTray.Checked         += SettingCheck_Changed;
            checkTray.Unchecked       += SettingCheck_Changed;
            checkNoQuestion.Checked   += SettingCheck_Changed;
            checkNoQuestion.Unchecked += SettingCheck_Changed;
            checkShowRaws.Checked     += SettingCheck_Changed;
            checkShowRaws.Unchecked   += SettingCheck_Changed;

            ResourceManager rm = Simplist3.Properties.Resources.ResourceManager;

            Setting.ChangeLog = (string)rm.GetObject("ChangeLog");
        }
Пример #26
0
    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);
            }
        }
    }
Пример #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            Int();
            HttpWebRequest wReq;
            HttpWebResponse wRes;
            textBox2.Clear();

            WebRequest requestPic = WebRequest.Create("http://static.powdertoy.co.uk/" + textBox1.Text + ".png");

            WebResponse responsePic = requestPic.GetResponse();

            Image webImage = Image.FromStream(responsePic.GetResponseStream());

            pictureBox1.Image = webImage;
            Uri uri = new Uri("http://powdertoy.co.uk/Browse/View.json?ID=" + textBox1.Text); // 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);

            JsonUtility.GenerateIndentedJsonText = false;

            Console.WriteLine();
            Console.WriteLine("Parsed data without indentation in JSON data format:");
            Console.WriteLine(obj.ToString());
            Console.WriteLine();


            // enumerate values in json object
            Console.WriteLine();
            int i = 0;
            String[] View = null;
            View = new string[17];
            foreach (JsonObject field in obj as JsonObjectCollection)
            {
                i++;
                string name = field.Name;
                string value = string.Empty;
                string type = field.GetValue().GetType().Name;

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

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

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

                }
                View[i] = value;
                Console.WriteLine("{0} {1}",
                    name, value);
            }

            textBox2.AppendText("요청하신 ID:" + View[1] + "\r\n");
            textBox2.AppendText("총점수:" + View[3] + "\r\n");
            textBox2.AppendText("보트업:" + View[4] + "\r\n");
            textBox2.AppendText("보트다운:" + View[5] + "\r\n");
            textBox2.AppendText("조회수:" + View[6] + "\r\n");
            textBox2.AppendText("제목:" + View[8] + "\r\n");
            제목 = View[8];
            textBox2.AppendText("설명:" + View[9] + "\r\n");
            TimeSpan t = TimeSpan.FromSeconds(Convert.ToInt32(View[11]));
            DateTime Date = 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;
            }

            textBox2.AppendText("업로드날짜:"+Date.Year+ "년"+Date.Month+"월"+Date.Day+"일"+hour + "시" + t.Minutes + "분" + t.Seconds + "초" + "\r\n");
            textBox2.AppendText("제작자:" + View[12] + "\r\n");
            textBox2.AppendText("댓글개수:" + View[13] + "\r\n");
            if (Convert.ToInt32(View[13]) / 20 == 0)
            {
                totalpage = Convert.ToInt32(View[13]);
                textBox2.AppendText("댓글 페이지 수:" + "1" + "\r\n");
            }
            else if (Convert.ToInt32(View[13]) / 20 == Convert.ToInt32(Convert.ToInt32(View[13]) / 20))
            {
                int one = Convert.ToInt32(View[13]) / 20 + 1;
                totalpage = one;
                textBox2.AppendText("댓글 페이지 수:" + one + "\r\n");
            }
            else
            {
                totalpage = Convert.ToInt32(View[13]) / 20;
                textBox2.AppendText("댓글 페이지 수:" + Convert.ToInt32(View[13]) / 20 + "\r\n");
            }
            textBox2.AppendText("공개세이브:" + View[14] + "\r\n");
            //if(View[16] == "")
            //    textBox2.AppendText("태그:" + "없음" + "\r\n");
            //else
            //    textBox2.AppendText("태그:" + View[16] + "\r\n");
        }
Пример #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        JsonObjectCollection rtnJsonCol = new JsonObjectCollection();

        try
        {
            JsonTextParser              parser    = new JsonTextParser();
            StringBuilder               sb        = new StringBuilder();
            JsonObject                  jo        = null;
            JsonObjectCollection        joc       = new JsonObjectCollection();
            Dictionary <string, string> paramsDic = new Dictionary <string, string>();
            if (Request.ContentLength > 0 && Request.ContentType.Contains("json"))
            {
                using (StreamReader sr = new StreamReader(Request.InputStream))
                {
                    jo  = parser.Parse(sr.ReadToEnd());
                    joc = jo as JsonObjectCollection;

                    foreach (var param in joc)
                    {
                        if (param != null)
                        {
                            if (param.GetValue() != null)
                            {
                                paramsDic.Add(param.Name, param.GetValue().ToString());
                            }
                        }
                        else
                        {
                        }
                    }
                }
            }

            //상황에 따라서 DB에 접속할것인지(검색), 소켓통신(추가, 저장, 삭제)을 할것인지 판단 하여 진행
            if (paramsDic.ContainsKey("PROC_TYPE"))
            {
                if (paramsDic["PROC_TYPE"] == "SQL")
                {
                    rtnJsonCol = DbProcess.Select_Adapter(paramsDic);
                }
                else if (paramsDic["PROC_TYPE"] == "SOCKET")
                {
                    rtnJsonCol = DbProcess.Socket_Adapter(paramsDic);
                }
                else if (paramsDic["PROC_TYPE"] == "LOGIN")
                {
                    if (DbProcess.LogIn(paramsDic))
                    {
                        rtnJsonCol.Add(new JsonStringValue("RESULT", "{\"result\":\"true\"}"));
                        Session["id"] = paramsDic["ID"];
                    }
                    else
                    {
                        rtnJsonCol.Add(new JsonStringValue("RESULT", "{\"result\":\"false\"}"));
                        Session["id"] = null;
                    }
                }
                else if (paramsDic["PROC_TYPE"] == "FILE")
                {
                    rtnJsonCol = DbProcess.FileList(paramsDic);
                }
                else if (paramsDic["PROC_TYPE"] == "FILE_READ")
                {
                    rtnJsonCol = DbProcess.FileRead(paramsDic);
                }
                else if (paramsDic["PROC_TYPE"] == "FILE_DELETE")
                {
                    rtnJsonCol = DbProcess.FileDelete(paramsDic);
                }
            }
        }
        catch (Exception ex)
        {
            string strErrorMessage = "";

            strErrorMessage += ex.Message;
            if (ex.InnerException != null)
            {
                strErrorMessage += string.Format("<br/>({0})", ex.InnerException.Message);
            }
            Response.Write(strErrorMessage);
        }
        finally
        {
            if (rtnJsonCol.Count > 0)
            {
                Response.Write(rtnJsonCol.ToString());
            }
            Response.End();
        }
    }
        public TimeCapsule parseTimeCapsule(string timecapsulejson)
        {
            TimeCapsule    result = new TimeCapsule();
            JsonTextParser parser = new JsonTextParser();
            JsonObject     obj    = parser.Parse(timecapsulejson);

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

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

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

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

                case "null":
                    value = "null";
                    break;

                default:
                    value = "NotSupportedException";
                    break;
                    // DEBUG: in this sample we'll not parse nested arrays or objects.
                    //throw new NotSupportedException();
                }

                switch (name)
                {
                case "_id":
                    result._id = value;
                    break;

                case "platform":
                    result.platform = value;
                    break;

                case "platform_user_id":
                    result.platform_user_id = value;
                    break;

                case "user_name":
                    result.user_name = value;
                    break;

                case "title":
                    result.title = value;
                    break;

                case "text":
                    result.text = value;
                    break;

                case "language":
                    result.language = value;
                    break;

                case "items":
                    result.items = value;
                    break;

                case "is_active":
                    result.is_active = Convert.ToBoolean(value);
                    break;

                case "votes_up":
                    result.votes_up = Convert.ToInt32(value);
                    break;

                case "votes_down":
                    result.votes_down = Convert.ToInt32(value);
                    break;

                case "copies_found":
                    result.copies_found = Convert.ToInt32(value);
                    break;

                case "class_id":
                    result.class_id = value;
                    break;

                case "modified_at":
                    result.modified_at = value;
                    break;

                case "updated_at":
                    result.updated_at = value;
                    break;

                case "created_at":
                    result.created_at = value;
                    break;

                case "image":
                    result.image = value;
                    break;

                case "time_ago":
                    result.time_ago = value;
                    break;

                case "item_list":
                    result.item_list = value;
                    break;

                default:
                    throw new NotSupportedException();
                }
                // DEBUG
                //Console.WriteLine("{0} {1} {2}", name.PadLeft(15), type.PadLeft(10), value.PadLeft(15));
            }

            if (obj != null)
            {
                obj = null;
            }
            if (parser != null)
            {
                parser = null;
            }
            return(result);
        }
Пример #30
0
        public static List <Listdata> getNaverCategoryPostList(string url)
        {
            List <Listdata> list = new List <Listdata>();

            try {
                string html = Network.GET(url, "UTF-8");

                // Blog id

                Uri uri = new UriBuilder(url).Uri;
                NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);
                string blogId             = query.Get("blogId");
                string logNo            = query.Get("logNo");
                string categoryNo       = query.Get("categoryNo");
                string parentCategoryNo = query.Get("parentCategoryNo");

                // etc

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                if (logNo == null)
                {
                    string   copyLinkIdPrefix = string.Format("url_{0}_", blogId);
                    HtmlNode copyLinkNode     = doc.DocumentNode.SelectSingleNode(string.Format("//p[contains(@id, '{0}')]", copyLinkIdPrefix));
                    if (copyLinkNode != null)
                    {
                        logNo = copyLinkNode.Id.Replace(copyLinkIdPrefix, "").Trim();
                    }
                    else
                    {
                        return(list);
                    }
                }

                if (categoryNo == null)
                {
                    categoryNo = getJsValue(html, "categoryNo");
                }

                if (parentCategoryNo == null)
                {
                    parentCategoryNo = getJsValue(html, "parentCategoryNo");
                }

                Dictionary <string, string> dict = new Dictionary <string, string>()
                {
                    { "blogId", blogId },
                    { "logNo", logNo },
                    { "viewDate", "" },
                    { "categoryNo", categoryNo == "0" ? "" : categoryNo },
                    { "parentCategoryNo", parentCategoryNo },
                    { "showNextPage", "true" },
                    { "showPreviousPage", "false" },
                    { "sortDateInMilli", "" }
                };

                string data = Function.GetHttpParams(dict);

                JsonTextParser parser = new JsonTextParser();

                for (int i = 0; i < 3; i++)
                {
                    string result = Network.POST("http://blog.naver.com/PostViewBottomTitleListAsync.nhn", data);
                    if (result == "")
                    {
                        break;
                    }

                    JsonObjectCollection collect = (JsonObjectCollection)parser.Parse(result);
                    JsonArrayCollection  array   = (JsonArrayCollection)collect["postList"];

                    foreach (JsonObjectCollection obj in array)
                    {
                        Listdata item = new Listdata(
                            HttpUtility.HtmlDecode(HttpUtility.UrlDecode(obj["filteredEncodedTitle"].GetValue().ToString())),
                            "Maker2",
                            string.Format("http://blog.naver.com/{0}/{1}", blogId, obj["logNo"].GetValue()));

                        list.Add(item);
                    }

                    bool hasNextPage = Convert.ToBoolean(collect["hasNextPage"].GetValue());

                    if (hasNextPage)
                    {
                        bool   hasPreviousPage   = Convert.ToBoolean(collect["hasPreviousPage"].GetValue());
                        string nextIndexLogNo    = collect["nextIndexLogNo"].GetValue().ToString();
                        string nextIndexSortDate = collect["nextIndexSortDate"].GetValue().ToString();

                        dict["logNo"]           = nextIndexLogNo;
                        dict["sortDateInMilli"] = nextIndexSortDate;
                        dict["showNextPage"]    = hasNextPage.ToString().ToLower();

                        data = Function.GetHttpParams(dict);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex) {
            }
            return(list);
        }