public void TestMethod1()
        {
            Console.WriteLine("The UnitTest of Database Connection ! \n");


            // ==DB Connection==

            // Arrange
            bool value = true;
            List<string> dbTestInfo = new List<string>();
            dbTestInfo.Clear();
            dbTestInfo.Add("localhost");
            dbTestInfo.Add("enricolu");
            dbTestInfo.Add("111platform!");
            dbTestInfo.Add("test");


            // Act
            DBConnection db = new DBConnection(dbTestInfo);
            value = db.checkDBExist();


            // Assert
            Assert.AreEqual(value, true);


        }
 public SearchForm(List<string> dbInfo)
 {
     InitializeComponent();
     this.dbInfo = dbInfo;
     postSort = new bool[levelOneList.Columns.Count];
     string sql = "select id, name from pages_info";
     DBConnection conn = new DBConnection(this.dbInfo);
     conn.MySqlConnect();
     MySqlDataReader res = conn.mysql_query(sql);
     while (res.Read())
     {
         pagesID.Add(res.GetString(0));
         pagesName.Add(res.GetString(1));
         page_list.Items.Add(res.GetString(1));
     }
     page_list.Text = page_list.Items[0].ToString();
     page_list.SelectedIndex = 0;
     res.Close();
 }
        private void startUpdateData(string newIDSince)
        {
            bool continueUpdate = false;
            if (updatePageLogsCheck.Checked)
                continueUpdate = true;
            while (true)
            {
                DBConnection conn = new DBConnection(dbInfo);
                conn.MySqlConnect();
                string sql = "select * from access_token where 1";
                MySqlDataReader res = null;
                while (true)
                {
                    try
                    {
                        res = conn.mysql_query(sql);
                        res.Read();
                        break;
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.StackTrace);
                        conn.closeMySqlConnection();
                        conn.MySqlConnect();
                    }
                }
                DateTime nextUpdateTime = DateTime.Now.AddDays((1.0) * (int)pagesLogUpdateF.Value);
                DateTime untileDate = DateTime.Now.AddDays((-1.0) * (int)recentlyDays.Value);
                string since = untileDate.Year.ToString() + "-" + untileDate.Month.ToString() + "-" + untileDate.Day.ToString();
                string access_token = res.GetString(0);
                res.Close();
                string IDString = "";
                foreach (ListViewItem lvi in pagesInfo.CheckedItems)
                {
                    IDString += lvi.Text + ",";
                }
                IDString = IDString.Substring(0, IDString.Length - 1);
                sql = "select id,name,new_id from pages_info where new_id >= 0 and id in (" + IDString + ")";
                List<string[]> pageList = new List<string[]>();
                while (true)
                {
                    try
                    {
                        pageList.Clear();
                        res = conn.mysql_query(sql);
                        break;
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.StackTrace);
                        conn.closeMySqlConnection();
                        conn.MySqlConnect();
                    }
                }
                while (res.Read())
                {
                    string[] tmpPage = { res.GetString(0), res.GetString(1), res.GetString(2) };
                    pageList.Add(tmpPage);
                }
                res.Close();
                foreach (string[] pagesInfoArray in pageList)
                {
                    DateTime startingTime = DateTime.Now;
                    showMessage.AppendText("Now updating " + pagesInfoArray[1] + " at " + DateTime.Now.ToString() + "\n");
                    string url = "https://graph.facebook.com/" + pagesInfoArray[0];

                    //showMessage.AppendText("In firstThread since=" + newIDSince + "\n");
                    if (pagesInfoArray[2] == "1")
                    {
                        get_post(pagesInfoArray[0], access_token, newIDSince, null);
                        sql = "update pages_info set new_id = 0 where id = \"" + pagesInfoArray[0] + "\"";
                        while (true)
                        {
                            try
                            {
                                conn.mysql_query(sql).Close();
                                break;
                            }
                            catch (Exception ee)
                            {
                                Console.WriteLine(ee.StackTrace);
                                conn.closeMySqlConnection();
                                conn.MySqlConnect();
                            }
                        }
                    }
                    else
                    {
                        get_post(pagesInfoArray[0], access_token, since, null);
                    }
                    sql = "select count(*) from allinone where post_id = \"" + pagesInfoArray[0] + "\"";
                    while (true)
                    {
                        try
                        {
                            res = conn.mysql_query(sql);
                            res.Read();
                            break;
                        }
                        catch (Exception ee)
                        {
                            Console.WriteLine(ee.StackTrace);
                            conn.closeMySqlConnection();
                            conn.MySqlConnect();
                        }
                    }
                    string feedsCount = res.GetString(0);
                    res.Close();
                    sql = "select count(*) from pages_posts_comments where page_id = \"" + pagesInfoArray[0] + "\"";
                    while (true)
                    {
                        try
                        {
                            res = conn.mysql_query(sql);
                            res.Read();
                            break;
                        }
                        catch (Exception ee)
                        {
                            Console.WriteLine(ee.StackTrace);
                            conn.closeMySqlConnection();
                            conn.MySqlConnect();
                        }
                    }
                    string commentsCount = res.GetString(0);
                    res.Close();
                    List<string> pageInformation = pages_info(url);
                    if (pageInformation != null)
                    {
                        sql = "insert into pages_logs (id,name,picture,link,category,website,founded,info,likes,talking_about_count,updatetime,feeds,comments) values (" +
                            "?id,?name,?picture,?link,?category,?website,?founded,?info,?likes,?talking_about_count,?updatetime," + feedsCount + "," + commentsCount + ")";
                        while (true)
                        {
                            try
                            {
                                MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
                                thecmd.Parameters.AddWithValue("?id", pageInformation[0]);
                                thecmd.Parameters.AddWithValue("?name", pageInformation[1]);
                                thecmd.Parameters.AddWithValue("?picture", pageInformation[2]);
                                thecmd.Parameters.AddWithValue("?link", pageInformation[3]);
                                thecmd.Parameters.AddWithValue("?category", pageInformation[4]);
                                thecmd.Parameters.AddWithValue("?website", pageInformation[5]);
                                thecmd.Parameters.AddWithValue("?founded", pageInformation[6]);
                                thecmd.Parameters.AddWithValue("?info", pageInformation[7]);
                                thecmd.Parameters.AddWithValue("?likes", pageInformation[8]);
                                thecmd.Parameters.AddWithValue("?talking_about_count", pageInformation[9]);
                                thecmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
                                MySqlDataReader themyData = thecmd.ExecuteReader();
                                themyData.Close();
                                thecmd.Parameters.Clear();
                                break;
                            }
                            catch (Exception ee)
                            {
                                Console.WriteLine(ee.StackTrace);
                                conn.closeMySqlConnection();
                                conn.MySqlConnect();
                            }
                        }
                    }
                    TimeSpan timeSpent = DateTime.Now.Subtract(startingTime);
                    sql = "update pages_info set timespent = \"" + timeSpent.TotalMinutes.ToString("#.#0") + "分鐘" + "\" where id = \"" + pagesInfoArray[0] + "\"";
                    while (true)
                    {
                        try
                        {
                            conn.mysql_query(sql).Close();
                            break;
                        }
                        catch (Exception ee)
                        {
                            Console.WriteLine(ee.StackTrace);
                            conn.closeMySqlConnection();
                            conn.MySqlConnect();
                        }
                    }
                    conn.closeMySqlConnection();
                    showMessage.AppendText(pagesInfoArray[1] + " was updated complete at " + DateTime.Now.ToString() + "\n");
                }
                if (continueUpdate)
                {
                    try
                    {
                        TimeSpan ts = nextUpdateTime.Subtract(DateTime.Now);
                        //七天更新一次
                        showMessage.AppendText("預計下次更新時間為" + nextUpdateTime.ToString() + "\n\n");
                        Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                    }
                    catch { }
                }
                else
                {
                    showMessage.AppendText("更新結束 @" + DateTime.Now.ToString() + "\n");
                    startUpdate.Enabled = true;
                    cancleUpdate.Enabled = false;
                    break;
                }
            }
        }
        /// <summary>
        /// return with id,name,picture,link,category,website,founded,likes,talking_about_count
        /// </summary>

        #region insert post
        public void get_post(string pageID, string access_token, string since, string until)
        {
            //until = "2013-11-22";
            int limit = maxLimit;
            string url = "https://graph.facebook.com/" + pageID + "/feed?access_token=" + access_token + "&limit=" + limit.ToString();

            if (since != null)
            {
                url += "&since=" + since;
            }
            if (until != null)
            {
                url += "&until=" + until;
            }
            //showMessage.AppendText(url + "\n");
            FBGraph api = new FBGraph();
            JSONObject fbJSON = api.FBGraphGet(url);

            do
            {
                fbJSON = resultCheck(fbJSON, url, limit);
                //while (true)
                //{
                //    if (fbJSON.Dictionary == null || fbJSON.Dictionary.ContainsKey("error_msg") || fbJSON.Dictionary.ContainsKey("error"))
                //    {
                //        string errorMessage = "";
                //        string errorNumber = "";
                //        if (fbJSON.Dictionary == null)
                //        {
                //            errorMessage = "An unknown error occurred";
                //            errorNumber = "1";
                //        }
                //        else if (fbJSON.Dictionary.ContainsKey("error_msg"))
                //        {
                //            errorMessage = fbJSON.Dictionary["error_msg"].String;
                //            errorNumber = fbJSON.Dictionary["error_code"].String;
                //        }
                //        else
                //        {
                //            errorMessage = fbJSON.Dictionary["error"].Dictionary["message"].String;
                //            errorNumber = fbJSON.Dictionary["error"].Dictionary["code"].String;
                //        }
                //        messageLog(errorMessage);
                //        //showMessage.AppendText("@" + DateTime.Now.ToString() + ":" + errorMessage + "\n");
                //        if (errorNumber.Equals("4"))
                //        {
                //            //(#4)為超出limit sleep 10秒後再繼續
                //            Thread.Sleep(10 * 1000);
                //            fbJSON = api.FBGraphGet(url);
                //        }
                //        else if (errorNumber.Equals("1"))
                //        {
                //            if (limit <= 25)
                //            {
                //                return;
                //            }
                //            limit = limit / 2;
                //            if (limit <= 25)
                //                limit = 25;
                //            url = "https://graph.facebook.com/" + pageID + "/feed?access_token=" + access_token + "&limit=" + limit.ToString();

                //            if (since != null)
                //            {
                //                url += "&since=" + since;
                //            }
                //            if (until != null)
                //            {
                //                url += "&until=" + until;
                //            }
                //            Thread.Sleep(10 * 1000);
                //            fbJSON = api.FBGraphGet(url);
                //        }
                //        else
                //        {
                //            return;
                //        }
                //    }
                //    else
                //    {
                //        break;
                //    }
                //    //try
                //    //{
                //    //    string errorMessage = fbJSON.Dictionary["error_msg"].String;
                //    //    string errorNumber = fbJSON.Dictionary["error_code"].String;
                //    //    messageLog(errorMessage);
                //    //    //showMessage.AppendText("@" + DateTime.Now.ToString() + ":" + errorMessage + "\n");
                //    //    if (errorNumber.Equals("4"))
                //    //    {
                //    //        //(#4)為超出limit sleep 10秒後再繼續
                //    //        Thread.Sleep(10 * 1000);
                //    //        fbJSON = api.FBGraphGet(url);
                //    //    }
                //    //    else if (errorNumber.Equals("1"))
                //    //    {
                //    //        if (limit <= 25)
                //    //        {
                //    //            return;
                //    //        }
                //    //        limit = limit / 2;
                //    //        if (limit <= 25)
                //    //            limit = 25;
                //    //        url = "https://graph.facebook.com/" + pageID + "/feed?access_token=" + access_token + "&limit=" + limit.ToString();

                //    //        if (since != null)
                //    //        {
                //    //            url += "&since=" + since;
                //    //        }
                //    //        if (until != null)
                //    //        {
                //    //            url += "&until=" + until;
                //    //        }
                //    //        Thread.Sleep(10 * 1000);
                //    //        fbJSON = api.FBGraphGet(url);
                //    //    }
                //    //    else
                //    //    {
                //    //        return;
                //    //    }
                //    //}
                //    //catch { break; }
                //}
                DBConnection conn = new DBConnection(dbInfo);
                conn.MySqlConnect();
                try
                {
                    foreach (JSONObject post in fbJSON.Dictionary["data"].Array)
                    {
                        string postID = " ";
                        string comments = "0";
                        DateTime postCreatedTime = DateTime.Now;

                        if (post.Dictionary.ContainsKey("id"))
                        {
                            postID = post.Dictionary["id"].String;
                        }

                        if (post.Dictionary.ContainsKey("comments"))
                        {
                            comments = get_post_comment(pageID, postID, access_token, post.Dictionary["comments"], postCreatedTime, "").ToString();
                        }

                    }

                    foreach (JSONObject post in fbJSON.Dictionary["data"].Array)
                    {
                        string postID = " ";
                        string fromID = " ";
                        string fromName = " ";
                        string message = " ";
                        string picture = " ";
                        string link = " ";
                        string name = " ";
                        string caption = " ";
                        string source = " ";
                        string icon = " ";
                        string type = " ";
                        string objectID = " ";
                        string description = " ";
                        string likes = "0";
                        string comments = "0";
                        string shares = "0";
                        DateTime postCreatedTime = DateTime.Now;
                        DateTime postUpdateTime = DateTime.Now;

                        //--------------------------//
                        string datatype = "1";

                        if (post.Dictionary.ContainsKey("id"))
                        {
                            postID = post.Dictionary["id"].String;
                        }
                        if (post.Dictionary.ContainsKey("created_time"))
                        {
                            postCreatedTime = fbDatetimeToDatetime(post.Dictionary["created_time"].String);
                        }
                        if (post.Dictionary.ContainsKey("updated_time"))
                        {
                            postUpdateTime = fbDatetimeToDatetime(post.Dictionary["updated_time"].String);
                        }
                        if (post.Dictionary.ContainsKey("from"))
                        {
                            if (post.Dictionary["from"].Dictionary.ContainsKey("id"))
                                fromID = post.Dictionary["from"].Dictionary["id"].String;
                            if (post.Dictionary["from"].Dictionary.ContainsKey("name"))
                                fromName = post.Dictionary["from"].Dictionary["name"].String;
                        }
                        if (post.Dictionary.ContainsKey("message"))
                        {
                            message = post.Dictionary["message"].String;
                        }
                        if (post.Dictionary.ContainsKey("picture"))
                        {
                            picture = post.Dictionary["picture"].String;
                        }
                        if (post.Dictionary.ContainsKey("link"))
                        {
                            link = post.Dictionary["link"].String;
                        }
                        if (post.Dictionary.ContainsKey("name"))
                        {
                            name = post.Dictionary["name"].String;
                        }
                        if (post.Dictionary.ContainsKey("caption"))
                        {
                            caption = post.Dictionary["caption"].String;
                        }
                        if (post.Dictionary.ContainsKey("source"))
                        {
                            source = post.Dictionary["source"].String;
                        }
                        if (post.Dictionary.ContainsKey("icon"))
                        {
                            icon = post.Dictionary["icon"].String;
                        }
                        if (post.Dictionary.ContainsKey("type"))
                        {
                            type = post.Dictionary["type"].String;
                        }
                        if (post.Dictionary.ContainsKey("object_id"))
                        {
                            objectID = post.Dictionary["object_id"].String;
                        }
                        if (post.Dictionary.ContainsKey("description"))
                        {
                            description = post.Dictionary["description"].String;
                        }
                        if (post.Dictionary.ContainsKey("likes"))
                        {
                            likes = get_likes(pageID, postID, access_token, post.Dictionary["likes"], postCreatedTime, "").ToString();
                        }
                        //    if (post.Dictionary.ContainsKey("comments"))
                        //    {
                        //        comments = get_post_comment(pageID, postID, access_token, post.Dictionary["comments"], postCreatedTime, "").ToString();
                        //    }
                        if (post.Dictionary.ContainsKey("share"))
                        {
                            shares = post.Dictionary["shares"].Dictionary["count"].String;
                        }
                        string sql = "insert into allinone (post_id,datatype,author_id,author,message,picture,url,name,caption,source,icon,type,object_id,description,likes,created_time,updated_time,comments,shares,updatetime) values (" +
                            "\"" + postID + "\",\"" + datatype + "\",\"" + fromID + "\",?fname,?message,?picture,?link,?name,?caption,?source,?icon,?type,?object_id,?description," + likes + ",?created_time,?update_time," + comments + "," + shares + ",?updatetime) " +
                            "ON DUPLICATE KEY UPDATE message =?message, likes=" + likes + ",comments=" + comments + ",shares=" + shares + ",updated_time=?update_time,updatetime=?updatetime";
                        //showMessage.AppendText(sql + "\n");
                        for (int loop = 0; loop < 2; loop++)
                        {
                            try
                            {
                                MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
                                thecmd.Parameters.AddWithValue("?fname", fromName);
                                thecmd.Parameters.AddWithValue("?message", message);
                                thecmd.Parameters.AddWithValue("?picture", picture);
                                thecmd.Parameters.AddWithValue("?link", link);
                                thecmd.Parameters.AddWithValue("?name", name);
                                thecmd.Parameters.AddWithValue("?caption", caption);
                                thecmd.Parameters.AddWithValue("?source", source);
                                thecmd.Parameters.AddWithValue("?icon", icon);
                                thecmd.Parameters.AddWithValue("?type", type);
                                thecmd.Parameters.AddWithValue("?object_id", objectID);
                                thecmd.Parameters.AddWithValue("?description", description);
                                thecmd.Parameters.AddWithValue("?created_time", postCreatedTime);
                                thecmd.Parameters.AddWithValue("?update_time", postUpdateTime);
                                thecmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
                                MySqlDataReader themyData = thecmd.ExecuteReader();
                                themyData.Close();
                                thecmd.Parameters.Clear();
                                break;
                                //showMessage.AppendText("Insert complete!!\n");
                            }
                            catch (Exception sqlE)
                            {
                                Console.WriteLine(sqlE.StackTrace);
                                conn.closeMySqlConnection();
                                conn.MySqlConnect();
                            }
                        }
                    }
                }
                catch
                {
                    break;
                }
                conn.closeMySqlConnection();
                //get next page data
                try
                {
                    url = fbJSON.Dictionary["paging"].Dictionary["next"].String;
                }
                catch
                {
                    return;
                }
                if (since != null)
                    url += "&since=" + since;
                url += "&limit=" + limit.ToString();
                fbJSON = api.FBGraphGet(url);
                fbJSON = resultCheck(fbJSON, url, limit);
                //while (true)
                //{
                //    if (fbJSON.Dictionary == null || fbJSON.Dictionary.ContainsKey("error") || fbJSON.Dictionary.ContainsKey("error_msg"))
                //    {
                //        string errorMessage = "";
                //        string errorNumber = "";
                //        if (fbJSON.Dictionary == null)
                //        {
                //            errorMessage = "An unknown error occurred";
                //            errorNumber = "1";
                //        }
                //        else if (fbJSON.Dictionary.ContainsKey("error_msg"))
                //        {
                //            errorMessage = fbJSON.Dictionary["error_msg"].String;
                //            errorNumber = fbJSON.Dictionary["error_code"].String;
                //        }
                //        else
                //        {
                //            errorMessage = fbJSON.Dictionary["error"].Dictionary["message"].String;
                //            errorNumber = fbJSON.Dictionary["error"].Dictionary["code"].String;
                //        }
                //        if (errorNumber.Equals("4"))
                //        {
                //            //(#4)為超出limit sleep 10秒後再繼續
                //            Thread.Sleep(10 * 1000);
                //            fbJSON = api.FBGraphGet(url);
                //        }
                //        else { break; }
                //    }
                //    else { break; }
                //}
                try
                {
                    if (fbJSON.Dictionary["data"].Array.Length > 0)
                    {
                    }
                    else
                    {
                        break;
                    }
                }
                catch
                {
                    break;
                }
            } while (fbJSON.Dictionary["data"].Array.Length > 0);
        }
        private void insertPageID_Click(object sender, EventArgs e)
        {
            if (searchResultList.Items.Count == 0)
            {
                MessageBox.Show("請先搜尋粉絲頁");
                return;
            }
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "";
            string IDString = "";
            int insertCount = 0;
            foreach (ListViewItem lvi in searchResultList.Items)
            {
                if (!lvi.Checked)
                    continue;
                IDString += lvi.Text + ",";
                insertCount++;
            }
            if (insertCount == 0)
            {
                MessageBox.Show("請先勾選要新增的粉絲頁名單");
                return;
            }
            IDString = IDString.Substring(0, IDString.Length - 1);
            string url = "https://api.facebook.com/method/fql.query?query=select page_id,name,pic_small,page_url,website,founded,fan_count,general_info,type from page where page_id in (" + IDString + ")&access_token=" + accessTokenBox.Text + "&format=json";
            FBGraph api = new FBGraph();
            JSONObject result = api.FBGraphGet(url);
            result = resultCheck(result, url, 0);
            //try
            //{
            //    int erro_count = 0;
            //    while (true)
            //    {
            //        if (result.Dictionary.ContainsKey("error_msg") || result.Dictionary.ContainsKey("error"))
            //        {
            //            //若發生error 檢查是何種error 若無error再透過exception離開迴圈
            //            string errorMessage = "";
            //            string errorNumber = "";
            //            if (result.Dictionary.ContainsKey("error_msg"))
            //            {
            //                errorMessage = result.Dictionary["error_msg"].String;
            //                errorNumber = result.Dictionary["error_code"].String;
            //            }
            //            else
            //            {
            //                errorMessage = result.Dictionary["error"].Dictionary["message"].String;
            //                errorNumber = result.Dictionary["error"].Dictionary["code"].String;
            //            }
            //            //Console.WriteLine("Error message(" + errorNumber + ") is : " + errorMessage);
            //            if (errorNumber.Equals("602"))
            //            {
            //                MessageBox.Show(errorMessage);
            //                return;
            //            }
            //            else
            //            {
            //                Thread.Sleep(1000);
            //                erro_count++;
            //                if (erro_count > 30)
            //                {
            //                    MessageBox.Show(errorMessage);
            //                    return;
            //                }
            //            }
            //        }
            //        else
            //        {
            //            break;
            //        }
            //    }
            //}
            //catch { }
            foreach (JSONObject pageData in result.Array)
            {
                sql = "insert ignore into pages_info (id,name,picture,link,category,website,founded,info,likes,talking_about_count,updatetime,feeds,comments,new_id) values (" +
                    "?id,?name,?picture,?link,?category,?website,?founded,?info,?likes,?talking_about_count,?updatetime,0,0,1)";
                //page_id,name,pic_small,page_url,website,founded,fan_count,general_info,type
                while (true)
                {
                    try
                    {
                        MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
                        thecmd.Parameters.AddWithValue("?id", pageData.Dictionary["page_id"].String);
                        thecmd.Parameters.AddWithValue("?name", pageData.Dictionary["name"].String);
                        thecmd.Parameters.AddWithValue("?picture", pageData.Dictionary["pic_small"].String);
                        thecmd.Parameters.AddWithValue("?link", pageData.Dictionary["page_url"].String);
                        thecmd.Parameters.AddWithValue("?category", pageData.Dictionary["type"].String);
                        thecmd.Parameters.AddWithValue("?website", pageData.Dictionary["website"].String);
                        thecmd.Parameters.AddWithValue("?founded", pageData.Dictionary["founded"].String);
                        thecmd.Parameters.AddWithValue("?info", pageData.Dictionary["general_info"].String);
                        thecmd.Parameters.AddWithValue("?likes", pageData.Dictionary["fan_count"].String);
                        thecmd.Parameters.AddWithValue("?talking_about_count", "0");
                        thecmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
                        MySqlDataReader themyData = thecmd.ExecuteReader();
                        themyData.Close();
                        thecmd.Parameters.Clear();
                        break;
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.StackTrace);
                        conn.closeMySqlConnection();
                        conn.MySqlConnect();
                    }
                }
            }

            conn.closeMySqlConnection();
            updatePageIDList();
            checkCanUpdate();
            MessageBox.Show(result.Array.Length.ToString() + "筆資料新增");
        }
        public void updatePageIDList()
        {
            pagesInfo.Items.Clear();
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "select id,name,new_id,timespent from pages_info where new_id >= 0";
            MySqlDataReader res = conn.mysql_query(sql);
            if (res != null)
            {
                while (res.Read())
                {
                    ListViewItem item = new ListViewItem(res.GetString(0));

                    item.SubItems.Add(res.GetString(1));
                    if (res.GetInt32(2) == 0)
                    {
                        item.SubItems.Add("否");
                    }
                    else
                    {
                        item.SubItems.Add("是");
                    }
                    if (res.GetString(3).Length > 0)
                    {
                        item.SubItems.Add(res.GetString(3));
                    }
                    else
                    {
                        item.SubItems.Add("Null");
                    }
                    pagesInfo.Items.Add(item);
                }
                res.Close();
            }
            conn.closeMySqlConnection();
        }
 public void checkCanUpdate()
 {
     DBConnection conn = new DBConnection(dbInfo);
     conn.MySqlConnect();
     string sql = "select count(*) from pages_info where 1";
     MySqlDataReader res = conn.mysql_query(sql);
     res.Read();
     if (res.GetInt32(0) > 0)
     {
         startUpdate.Enabled = true;
     }
     else
     {
         startUpdate.Enabled = false;
     }
     res.Close();
     conn.closeMySqlConnection();
 }
 private void insert_pages_fans(Dictionary<string, string> fansName, string pageID)
 {
     string sql = "";
     DBConnection conn = new DBConnection(dbInfo);
     conn.MySqlConnect();
     StringBuilder sb = new StringBuilder();
     StringBuilder fansInfo = new StringBuilder();
     sb.Append("insert ignore into pages_fans (pages_id,id,name) values ");
     fansInfo.Append("insert ignore into user_info (id,name,username,gender,updatetime) values ");
     foreach (KeyValuePair<string, string> kvp in fansName)
     {
         sb.Append("(" + pageID + "," + kvp.Key + ",?" + kvp.Key + "),");
         fansInfo.Append("(" + kvp.Key + ",?" + kvp.Key + ",'','',?updatetime),");
     }
     sql = sb.ToString();
     sql = sql.Substring(0, sql.Length - 1);
     while (true)
     {
         try
         {
             MySqlCommand cmd = new MySqlCommand(sql, conn.conn);
             foreach (KeyValuePair<string, string> kvp in fansName)
             {
                 cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
             }
             cmd.ExecuteReader().Close();
             break;
         }
         catch (Exception ee)
         {
             Console.WriteLine(ee.StackTrace);
             conn.closeMySqlConnection();
             conn.MySqlConnect();
         }
     }
     sql = fansInfo.ToString();
     sql = sql.Substring(0, sql.Length - 1);
     while (true)
     {
         try
         {
             MySqlCommand cmd = new MySqlCommand(sql, conn.conn);
             cmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
             foreach (KeyValuePair<string, string> kvp in fansName)
             {
                 cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
             }
             cmd.ExecuteReader().Close();
             break;
         }
         catch (Exception ee)
         {
             Console.WriteLine(ee.StackTrace);
             conn.closeMySqlConnection();
             conn.MySqlConnect();
         }
     }
 }
 private void update_user_info_by_ids(StringBuilder sb, DBConnection conn)
 {
     Thread.Sleep(5 * 1000);
     string sql = "";
     string url = "https://graph.facebook.com/fql?q=select uid,username,sex from user where uid in (" + sb.ToString() + ")&access_token=" + accessTokenBox.Text;
     //showMessage.AppendText(url);
     //return;
     FBGraph api = new FBGraph();
     JSONObject result = api.FBGraphGet(url);
     result = resultCheck(result, url, 0);
     if (result == null)
     {
         return;
     }
     //try
     //{
     //    int erro_count = 0;
     //    while (true)
     //    {
     //        if (result.Dictionary.ContainsKey("error_msg") || result.Dictionary.ContainsKey("error"))
     //        {
     //            //若發生error 檢查是何種error 若無error再透過exception離開迴圈
     //            string errorMessage = "";
     //            string errorNumber = "";
     //            if (result.Dictionary.ContainsKey("error_msg"))
     //            {
     //                errorMessage = result.Dictionary["error_msg"].String;
     //                errorNumber = result.Dictionary["error_code"].String;
     //            }
     //            else
     //            {
     //                errorMessage = result.Dictionary["error"].Dictionary["message"].String;
     //                errorNumber = result.Dictionary["error"].Dictionary["code"].String;
     //            }
     //            //Console.WriteLine("Error message(" + errorNumber + ") is : " + errorMessage);
     //            if (errorNumber.Equals("602"))
     //            {
     //                messageLog(errorMessage);
     //                //showMessage.AppendText(errorMessage + "\n");
     //                return;
     //            }
     //            else
     //            {
     //                Thread.Sleep(1000);
     //                erro_count++;
     //                if (erro_count > 30)
     //                {
     //                    messageLog(errorMessage);
     //                    //showMessage.AppendText(errorMessage + "\n");
     //                    return;
     //                }
     //            }
     //        }
     //        else
     //        {
     //            break;
     //        }
     //    }
     //}
     //catch { }
     sb.Clear();
     Dictionary<string, string[]> uInfo = new Dictionary<string, string[]>();
     if (result.Dictionary.ContainsKey("data") && result.Dictionary["data"].Array.Length > 0)
     {
         foreach (JSONObject pageData in result.Dictionary["data"].Array)
         {
             string[] tmpString = { pageData.Dictionary["username"].String, pageData.Dictionary["sex"].String };
             uInfo.Add(pageData.Dictionary["uid"].String, tmpString);
             sb.Append(pageData.Dictionary["uid"].String + ",");
         }
         string allIDs = sb.ToString();
         allIDs = allIDs.Remove(allIDs.Length - 1);
         sb.Clear();
         sb.Append("update user_info set username = case id ");
         foreach (KeyValuePair<string, string[]> kvp in uInfo)
         {
             sb.Append(" when " + kvp.Key + " then '" + kvp.Value[0] + "' ");
         }
         sb.Append(" end, gender = case id ");
         foreach (KeyValuePair<string, string[]> kvp in uInfo)
         {
             sb.Append(" when " + kvp.Key + " then '" + kvp.Value[1] + "' ");
         }
         sb.Append(" end where id in (" + allIDs + ")");
         sql = sb.ToString();
         conn.mysql_query(sql).Close();
         sql = "update user_info set updatetime = ?updatetime where id in (" + allIDs + ")";
         MySqlCommand cmd = new MySqlCommand(sql, conn.conn);
         cmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
         cmd.ExecuteReader().Close();
         cmd.Parameters.Clear();
     }
 }
 private void dbConnect_Click(object sender, EventArgs e)
 {
     if (dbServerBox.Text.Length * dbAcoountBox.Text.Length * dbPasswordBox.Text.Length * dbTableBox.Text.Length == 0)
     {
         MessageBox.Show("資料庫資訊不得為空!");
         return;
     }
     dbInfo.Clear();
     dbInfo.Add(dbServerBox.Text);
     dbInfo.Add(dbAcoountBox.Text);
     dbInfo.Add(dbPasswordBox.Text);
     dbInfo.Add(dbTableBox.Text);
     string errorMessage = "";
     DBConnection conn = new DBConnection(dbInfo);
     if (!conn.checkDBExist())
     {
         MessageBox.Show("資料庫連線資訊錯誤!!");
         return;
     }
     errorMessage = conn.MySqlConnect();
     if (errorMessage.Length > 0)
     {
         MessageBox.Show(errorMessage);
         return;
     }
     else
     {
         accessTokenGroup.Enabled = true;
         string sql = "select count(*) from access_token where 1";
         MySqlDataReader res = conn.mysql_query(sql);
         res.Read();
         if (res.GetInt32(0) > 0)
         {
             res.Close();
             sql = "select access_token from access_token where 1";
             res = conn.mysql_query(sql);
             res.Read();
             accessTokenBox.Text = res.GetString(0);
             pagesEditGroup.Enabled = true;
             res.Close();
             checkCanUpdate();
             init_Timer();
         }
         else
         {
             res.Close();
             MessageBox.Show("請先指定Access Token");
         }
     }
     FileStream stream = new FileStream(dbInfoFileName, FileMode.OpenOrCreate);
     StreamWriter writer = new StreamWriter(stream);
     string baseServer = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(dbServerBox.Text));
     string baseAccount = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(dbAcoountBox.Text));
     string basePWD = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(dbPasswordBox.Text));
     string baseTable = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(dbTableBox.Text));
     writer.WriteLine(baseServer + ":" + baseAccount + ":" + basePWD + ":" + baseTable);
     writer.Close();
     stream.Close();
     updatePageIDList();
     conn.closeMySqlConnection();
     dbConnInfo.Enabled = false;
 }
        private void update_user_info()
        {
            if (updatingUser)
                return;
            updatingUser = true;
            DateTime start = DateTime.Now;
            Console.WriteLine("啟動更新@" + DateTime.Now.ToString("HH:mm:ss") + "!!!");
            if (accessTokenBox.Text.Length >= 0)
            {
                string sql = "select id from user_info where username = \"\" order by updatetime asc";
                DBConnection conn = new DBConnection(dbInfo);
                conn.MySqlConnect();
                List<string> userID = new List<string>();
                MySqlDataReader res = conn.mysql_query(sql);
                while (res.Read())
                {
                    userID.Add(res.GetString(0));
                }
                res.Close();
                StringBuilder sb = new StringBuilder();
                int index = 0;
                foreach (string uid in userID)
                {
                    if (index % 1500 == 0)
                    {
                        if (index != 0)
                        {
                            update_user_info_by_ids(sb, conn);
                        }
                        sb.Clear();
                        sb.Append(uid);
                    }
                    else
                    {
                        sb.Append("," + uid);
                    }
                    index++;
                }
                update_user_info_by_ids(sb, conn);
                conn.closeMySqlConnection();
            }
            updatingUser = false;

            Console.WriteLine("更新結束@" + DateTime.Now.ToString("HH:mm:ss") + "!!!(" + DateTime.Now.Subtract(start).TotalMinutes.ToString(".00Mins"));
        }
 private void deletePageID_Click(object sender, EventArgs e)
 {
     int deleteCount = 0;
     string deleteID = "";
     string deleteResultMessage = "";
     foreach (ListViewItem lvi in pagesInfo.Items)
     {
         if (lvi.Checked)
         {
             deleteID += lvi.SubItems[0].Text + ",";
             deleteResultMessage += lvi.SubItems[1].Text + "(" + lvi.SubItems[0].Text + ")\n";
             deleteCount++;
         }
     }
     if (deleteCount == 0)
     {
         MessageBox.Show("請先勾選要刪除的粉絲頁");
         return;
     }
     deleteID = deleteID.Substring(0, deleteID.Length - 1);
     DBConnection conn = new DBConnection(dbInfo);
     conn.MySqlConnect();
     string sql = "delete from pages_info where id in (" + deleteID + ")";
     try
     {
         conn.mysql_query(sql).Close();
     }
     catch { }
     sql = "delete from pages_logs where id in (" + deleteID + ")";
     try
     {
         conn.mysql_query(sql).Close();
     }
     catch { }
     sql = "delete from allinone where post_id in (" + deleteID + ")";
     try
     {
         conn.mysql_query(sql).Close();
     }
     catch { }
     sql = "delete from pages_posts_comments where page_id in (" + deleteID + ")";
     try
     {
         conn.mysql_query(sql).Close();
     }
     catch { }
     foreach (ListViewItem lvi in pagesInfo.Items)
     {
         if (lvi.Checked)
         {
             sql = "delete from pages_posts_comments_likes where comment_id like \"" + lvi.SubItems[0].Text + "_%\"";
             conn.mysql_query(sql).Close();
             sql = "delete from pages_posts_likes where post_id like \"" + lvi.SubItems[0].Text + "_%\"";
             conn.mysql_query(sql).Close();
         }
     }
     conn.closeMySqlConnection();
     updatePageIDList();
     checkCanUpdate();
     MessageBox.Show(deleteResultMessage + "已被刪除");
 }
        public int get_likes(string pageID, string objectID, string access_token, JSONObject likeJSON, DateTime postCreatedTime, string nextUrl)
        {
            int totoalCount = 0;
            //string url = "https://graph.facebook.com/" + postID + "/comments?access_token=" + access_token + "&limit=500";
            string url = "https://graph.facebook.com/" + objectID + "/likes?access_token=" + access_token + "&limit=" + likeLimit.ToString() + "&summary=1";
            if (nextUrl.Length > 0)
                url = nextUrl + "&limit=" + likeLimit.ToString();
            likeJSON = new FBGraph().FBGraphGet(url);
            likeJSON = resultCheck(likeJSON, url, likeLimit);
            if (likeJSON == null)
                return totoalCount;
            //while (true)
            //{
            //    if (likeJSON.Dictionary == null || likeJSON.Dictionary.ContainsKey("error") || likeJSON.Dictionary.ContainsKey("error_msg"))
            //    {
            //        string errorMessage = "";
            //        string errorNumber = "";
            //        if (likeJSON.Dictionary == null)
            //        {
            //            errorMessage = "An unknown error occurred";
            //            errorNumber = "1";
            //        }
            //        else if (likeJSON.Dictionary.ContainsKey("error_msg"))
            //        {
            //            errorMessage = likeJSON.Dictionary["error_msg"].String;
            //            errorNumber = likeJSON.Dictionary["error_code"].String;
            //        }
            //        else
            //        {
            //            errorMessage = likeJSON.Dictionary["error"].Dictionary["message"].String;
            //            errorNumber = likeJSON.Dictionary["error"].Dictionary["code"].String;
            //        }
            //        messageLog(errorMessage);
            //        //showMessage.AppendText("@" + DateTime.Now.ToString() + ":" + errorMessage + "\n");
            //        if (errorNumber.Equals("4") || errorNumber.Equals("2"))
            //        {
            //            //(#4)為超出limit sleep 30秒後再繼續
            //            Thread.Sleep(30 * 1000);
            //            likeJSON = new FBGraph().FBGraphGet(url);
            //        }
            //        else
            //        {
            //            return totoalCount;
            //        }
            //    }
            //    else { break; }
            //}
            Dictionary<string, string> fansName = new Dictionary<string, string>();
            //bool hasNaxt = false;
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "";
            try
            {
                totoalCount = Convert.ToInt32(likeJSON.Dictionary["summary"].Dictionary["total_count"].String);
            }
            catch { }
            if (likeJSON.Dictionary["data"].Array.Length > 0)
            {
                foreach (JSONObject ljson in likeJSON.Dictionary["data"].Array)
                {
                    string fromID = "";
                    string fromName = "";

                    if (ljson.Dictionary.ContainsKey("id"))
                    {
                        fromID = ljson.Dictionary["id"].String;
                        if (ljson.Dictionary.ContainsKey("name"))
                            fromName = ljson.Dictionary["name"].String;
                        if (!fansName.ContainsKey(fromID))
                        {
                            fansName.Add(fromID, fromName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("In Comment fetch exception with id & name\n");
                        messageLog("In Comment fetch exception with id & name\n");
                        continue;
                    }
                }
                if (fansName.Count > 0)
                {
                    insert_pages_fans(fansName, pageID);
                    insert_posts_likes(fansName, pageID, objectID, postCreatedTime);
                }
                conn.closeMySqlConnection();
                //string after = "";
                if (likeJSON.Dictionary.ContainsKey("paging"))
                {
                    if (likeJSON.Dictionary["paging"].Dictionary.ContainsKey("next"))
                    {
                        url = likeJSON.Dictionary["paging"].Dictionary["next"].String;
                        get_likes(pageID, objectID, access_token, null, postCreatedTime, url);
                    }
                    //hasNaxt = true;
                }
            }
            return totoalCount;
        }
        private void createGroup_Click(object sender, EventArgs e)
        {
            if (nameListBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("請先選擇要群組的名單");
                return;
            }
            if (nameOfGroup.Text.Length == 0)
            {
                MessageBox.Show("請輸入要群組的名稱");
                return;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("insert ignore into talk_msg_namelist (id,category) values ");
            foreach (KeyValuePair<string, string> kvp in nameListBox.CheckedItems)
            {
                sb.Append("(" + kvp.Key + ",?category),");
            }

            string sql = sb.ToString();
            sql = sql.Remove(sql.Length - 1);
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
            thecmd.Parameters.AddWithValue("?category", nameOfGroup.Text);
            MySqlDataReader themyData = thecmd.ExecuteReader();
            themyData.Close();
            thecmd.Parameters.Clear();
            conn.closeMySqlConnection();
            MessageBox.Show("『" + nameOfGroup.Text + "』群組已建立成功");
        }
        private void SetAccessToken_Click(object sender, EventArgs e)
        {
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "truncate table access_token";
            conn.mysql_query(sql).Close();

            sql = "insert into access_token (access_token) values (\"" + accessTokenBox.Text + "\")";
            conn.mysql_query(sql).Close();
            pagesEditGroup.Enabled = true;
            conn.closeMySqlConnection();
            init_Timer();
        }
        private void searchButton_Click(object sender, EventArgs e)
        {
            if (keywordBox.Text.Length == 0)
            {
                MessageBox.Show("請輸入要查詢的關鍵詞");
                return;
            }
            searchButton.Text = "資料查詢中…";
            searchButton.Enabled = false;
            pageName.Clear();
            postMessage.Clear();
            commentMessage.Clear();
            allCommentMessage.Clear();
            levelOneList.Items.Clear();
            commentsList.Items.Clear();
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "select id,name from pages_info";
            MySqlDataReader res = conn.mysql_query(sql);
            while (res.Read())
            {
                pageName.Add(res.GetString(0), res.GetString(1));
            }
            res.Close();

            string keyword = keywordBox.Text.Replace("\"", "");

            string allPostID = "";
            keyword = keyword.Replace("%", "\\%");
            keyword = keyword.Replace("_", "\\_");
            sql = "select post_id, page_id, from_name, message,likes,comments,created_time, from_id from pages_posts where message like \"%" + keyword + "%\" and page_id in (select id from pages_info)";
            //MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
            //thecmd.Parameters.AddWithValue("?keyword", keywordBox.Text);
            //res = thecmd.ExecuteReader();
            res = conn.mysql_query(sql);
            Console.WriteLine(sql);
            /*
            if (res != null)
            {
                while (res.Read())
                {
                    string[] postData = { res.GetString(1), res.GetString(2), res.GetString(3), res.GetString(4), res.GetString(5), res.GetString(6) };
                    //page_id, from_name, message, likes, comments, created_time
                    postMessage.Add(res.GetString(0), postData);
                    allPostID += "\"" + res.GetString(0) + "\",";
                }
            }
            */
            while (res.Read())
            {
                string[] postData = { res.GetString(1), res.GetString(2), res.GetString(3), res.GetString(4), res.GetString(5), res.GetDateTime(6).ToString("yyyy-MM-dd HH:mm:ss"), res.GetString(7) };
                //page_id, from_name, message, likes, comments, created_time
                postMessage.Add(res.GetString(0), postData);
                allPostID += "\"" + res.GetString(0) + "\",";
            }
            res.Close();
            if (allPostID.Length > 0)
            {
                allPostID = allPostID.Substring(0, allPostID.Length - 1);
                sql = "select comment_id, post_id, page_id, from_name, message, likes, created_time,from_id from pages_posts_comments where post_id in (" + allPostID + ")";
                res = conn.mysql_query(sql);
                if (res != null)
                {
                    while (res.Read())
                    {
                        string[] commentData = { res.GetString(1), res.GetString(2), res.GetString(3), res.GetString(4), res.GetString(5), res.GetString(6), res.GetString(7) };
                        allCommentMessage.Add(res.GetString(0), commentData);
                    }
                    res.Close();
                }
            }
            //thecmd.Parameters.Clear();


            sql = "select comment_id, post_id, page_id, from_name, message, likes, created_time, from_id from pages_posts_comments where message like \"%" + keyword + "%\" and page_id in (select id from pages_info)";
            //MySqlCommand thecmd = new MySqlCommand(sql, conn.conn);
            //thecmd.Parameters.AddWithValue("?keyword", keywordBox.Text);
            //res = thecmd.ExecuteReader();
            res = conn.mysql_query(sql);
            if (res != null)
            {
                while (res.Read())
                {
                    string[] commentData = { res.GetString(1), res.GetString(2), res.GetString(3), res.GetString(4), res.GetString(5), res.GetString(6), res.GetString(7) };
                    //post_id, page_id, from_name, message, likes, created_time
                    commentMessage.Add(res.GetString(0), commentData);
                }
                res.Close();
            }
            //thecmd.Parameters.Clear();

            display_Message();

            searchButton.Enabled = true;
            searchButton.Text = "查詢";
        }
        public int get_post_comment(string pageID, string postID, string access_token, JSONObject commJSON, DateTime postCreatedTime, string nextUrl)
        {
            int totoalCount = 0;
            string url = "https://graph.facebook.com/" + postID + "/comments?access_token=" + access_token + "&limit=" + commentLimit.ToString() + "&summary=1";
            if (nextUrl.Length > 0)
                url = nextUrl + "&limit=" + commentLimit.ToString();
            commJSON = new FBGraph().FBGraphGet(url);
            commJSON = resultCheck(commJSON, url, commentLimit);
            if (commJSON == null)
                return totoalCount;
            //while (true)
            //{
            //    if (commJSON.Dictionary == null || commJSON.Dictionary.ContainsKey("error") || commJSON.Dictionary.ContainsKey("error_msg"))
            //    {
            //        string errorMessage = "";
            //        string errorNumber = "";
            //        if (commJSON.Dictionary == null)
            //        {
            //            errorMessage = "An unknown error occurred";
            //            errorNumber = "1";
            //        }
            //        else if (commJSON.Dictionary.ContainsKey("error_msg"))
            //        {
            //            errorMessage = commJSON.Dictionary["error_msg"].String;
            //            errorNumber = commJSON.Dictionary["error_code"].String;
            //        }
            //        else
            //        {
            //            errorMessage = commJSON.Dictionary["error"].Dictionary["message"].String;
            //            errorNumber = commJSON.Dictionary["error"].Dictionary["code"].String;
            //        }
            //        messageLog(errorMessage);
            //        //showMessage.AppendText("@" + DateTime.Now.ToString() + ":" + errorMessage + "\n");
            //        if (errorNumber.Equals("4") || errorNumber.Equals("2"))
            //        {
            //            //(#4)為超出limit sleep 30秒後再繼續
            //            Thread.Sleep(30 * 1000);
            //            commJSON = new FBGraph().FBGraphGet(url);
            //        }
            //        else
            //        {
            //            return totoalCount;
            //        }
            //    }
            //    else { break; }
            //}
            Dictionary<string, string> fansName = new Dictionary<string, string>();
            //bool hasNaxt = false;
            DBConnection conn = new DBConnection(dbInfo);
            conn.MySqlConnect();
            string sql = "";
            try
            {
                totoalCount = Convert.ToInt32(commJSON.Dictionary["summary"].Dictionary["total_count"].String);
            }
            catch { }
            if (commJSON.Dictionary["data"].Array.Length > 0)
            {
                foreach (JSONObject comment in commJSON.Dictionary["data"].Array)
                {
                    string fromID = "";
                    string fromName = "";
                    string commID = "";
                    string message = "";
                    string likes = "0";

                    //----------------//
                    string datatype = "2";
                    string picture = " ";
                    string link = " ";
                    string name = " ";
                    string caption = " ";
                    string source = " ";
                    string icon = " ";
                    string type = " ";
                    string object_id = " ";
                    string description = " ";
                    string comments = "0";
                    string shares = "0";

                    DateTime created_time = DateTime.Now;
                    if (comment.Dictionary.ContainsKey("id"))
                    {
                        commID = comment.Dictionary["id"].String;
                    }
                    else
                    {
                        Console.WriteLine("In Comment fetch exception with comment id\n");
                        continue;
                    }
                    if (comment.Dictionary.ContainsKey("from"))
                    {
                        if (comment.Dictionary["from"].Dictionary.ContainsKey("id"))
                            fromID = comment.Dictionary["from"].Dictionary["id"].String;
                        if (comment.Dictionary["from"].Dictionary.ContainsKey("name"))
                            fromName = comment.Dictionary["from"].Dictionary["name"].String;
                        if (!fansName.ContainsKey(fromID))
                        {
                            fansName.Add(fromID, fromName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("In Comment fetch exception with id & name\n");
                        continue;
                    }
                    if (comment.Dictionary.ContainsKey("message"))
                    {
                        message = comment.Dictionary["message"].String;
                    }
                    else
                    {
                        Console.WriteLine("In Comment fetch exception with comment message\n");
                    }
                    if (comment.Dictionary.ContainsKey("like_count"))
                    {
                        likes = comment.Dictionary["like_count"].String;
                    }
                    if (comment.Dictionary.ContainsKey("created_time"))
                    {
                        created_time = fbDatetimeToDatetime(comment.Dictionary["created_time"].String);
                    }
                    else
                    {
                        Console.WriteLine("In Comment fetch exception with comment created_time \n");
                    }
                    /*    sql = "insert ignore into pages_posts_comments (comment_id,page_id,post_id,from_id,from_name,message,created_time,post_created_time,likes,updatetime) values (" +
                            "?comment_id,?page_id,?post_id,?from_id,?from_name,?message,?created_time,?post_created_time,?likes,?updatetime) " +
                            "ON DUPLICATE KEY UPDATE likes=?likes,updatetime=?updatetime";
                        */
                    //	sql = "insert into allinone (post_id,datatype,author_id,author,message,picture,url,name,caption,source,icon,type,object_id,description,likes,created_time,updated_time,comments,shares,updatetime) values (" +
                    //            "?post_id," + datatype + ",?from_id,?from_name,?message,"+ picture + "," + link +"," + name + "," + caption + ",?source," + icon + "," + type + "," + object_id + "," + description +
                    //			",?likes,?created_time,?updated_time," + comments + "," + shares + ",?updatetime)" ;

                    sql = "insert into allinone (post_id,datatype,author_id,author,message,picture,url,name,caption,source,icon,type,object_id,description,likes,created_time,updated_time,comments,shares,updatetime) values (" +
                            "?post_id,?datatype,?from_id,?from_name,?message,?picture,?link,?name,?caption,?source,?icon,?type,?object_id,?description,?likes,?created_time,?updated_time,?comments,?shares,?updatetime)";

                    /*	while (true)
                        {
                            try
                            {
                                MySqlCommand cmd = new MySqlCommand(sql, conn.conn);
                                cmd.Parameters.AddWithValue("?comment_id", commID);
                                cmd.Parameters.AddWithValue("?page_id", pageID);
                                cmd.Parameters.AddWithValue("?post_id", postID);
                                cmd.Parameters.AddWithValue("?from_id", fromID);
                                cmd.Parameters.AddWithValue("?from_name", fromName);
                                cmd.Parameters.AddWithValue("?message", message);
                                cmd.Parameters.AddWithValue("?created_time", created_time);
                                cmd.Parameters.AddWithValue("?post_created_time", postCreatedTime);
                                cmd.Parameters.AddWithValue("?likes", likes);
                                cmd.Parameters.AddWithValue("?updatetime", DateTime.Now);
                                cmd.ExecuteReader().Close();
                                //totoalCount++;
                                break;
                            }
                            catch (Exception ce)
                            {
                                Console.WriteLine(ce.StackTrace);
                                conn.closeMySqlConnection();
                                conn.MySqlConnect();
                            }
                        }*/

                    while (true)
                    {
                        try
                        {
                            MySqlCommand cmd = new MySqlCommand(sql, conn.conn);

                            cmd.Parameters.AddWithValue("?post_id", commID);
                            cmd.Parameters.AddWithValue("?datatype", datatype);
                            cmd.Parameters.AddWithValue("?from_id", fromID);
                            cmd.Parameters.AddWithValue("?from_name", fromName);
                            cmd.Parameters.AddWithValue("?message", message);
                            cmd.Parameters.AddWithValue("?picture", picture);
                            cmd.Parameters.AddWithValue("?link", link);
                            cmd.Parameters.AddWithValue("?name", name);
                            cmd.Parameters.AddWithValue("?caption", caption);
                            cmd.Parameters.AddWithValue("?source", source);
                            cmd.Parameters.AddWithValue("?icon", icon);
                            cmd.Parameters.AddWithValue("?type", type);
                            cmd.Parameters.AddWithValue("?object_id", object_id);
                            cmd.Parameters.AddWithValue("?description", description);
                            cmd.Parameters.AddWithValue("?likes", likes);
                            cmd.Parameters.AddWithValue("?created_time", postCreatedTime);
                            cmd.Parameters.AddWithValue("?updated_time", DateTime.Now);
                            cmd.Parameters.AddWithValue("?comments", comments);
                            cmd.Parameters.AddWithValue("?shares", shares);
                            cmd.Parameters.AddWithValue("?updatetime", DateTime.Now);

                            cmd.ExecuteReader().Close();
                            //totoalCount++;
                            break;
                        }
                        catch (Exception ce)
                        {
                            Console.WriteLine(ce.StackTrace);
                            conn.closeMySqlConnection();
                            conn.MySqlConnect();
                        }
                    }

                }
                if (fansName.Count > 0)
                {
                    insert_pages_fans(fansName, pageID);
                }
                //string after = "";
                conn.closeMySqlConnection();
                if (commJSON.Dictionary.ContainsKey("paging"))
                {
                    if (commJSON.Dictionary["paging"].Dictionary.ContainsKey("next"))
                    {
                        url = commJSON.Dictionary["paging"].Dictionary["next"].String;
                        get_post_comment(pageID, postID, access_token, null, postCreatedTime, url);
                    }
                    //hasNaxt = true;
                }
            }
            else
            {
                conn.closeMySqlConnection();
            }
            return totoalCount;
        }