private async Task LoadContent(DataItem _item)
        {
            string contentStr = string.Empty;
            try
            {
                contentStr = await Define.DownloadStringAsync(_item.Link);
            }
            catch (Exception ex)
            {

                //throw;
            }

            if (contentStr != string.Empty)
            {
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.LoadHtml(contentStr);

                HtmlAgilityPack.HtmlNode htmlNode = htmlDoc.GetElementbyId("ContentContainer");
                while (htmlNode.Descendants("script").Count() > 0)
                {
                    htmlNode.Descendants("script").ElementAt(0).Remove();
                }
                while (htmlNode.Descendants("meta").Count() > 0)
                {
                    htmlNode.Descendants("meta").ElementAt(0).Remove();
                }

                //contentStr = "<p><i>This blog post was authored by Andrew Byrne (<a href=\"http://twitter.com/AndrewJByrne\" target=\"_blank\">@AndrewJByrne</a>), a Senior Content Developer on the Windows Phone Developer Content team.</i> <p><i></i> <p><i>- Adam</i></p> <hr>  <p> <table cellspacing=\"1\" cellpadding=\"2\" width=\"722\" border=\"0\"> <tbody> <tr> <td valign=\"top\" width=\"397\"> <p>The Windows Phone Developer Content team is continually adding new code samples that you can download from MSDN. In this post, we introduce you to the 10 latest samples that we’ve posted on MSDN. Each sample includes a readme file that walks you through building and running the sample, and includes links to relevant, related documentation. We hope these samples help you with your app development and we look forward to providing more samples as we move forward. You can check out all of our <a href=\"http://code.msdn.microsoft.com/wpapps/site/search?f%5B0%5D.Type=Contributors&amp;f%5B0%5D.Value=Windows%20Phone%20SDK%20Team&amp;f%5B0%5D.Text=Windows%20Phone%20SDK&amp;sortBy=Date\" target=\"_blank\">samples on MSDN</a>.</p></td> <td valign=\"top\" width=\"320\"> <p><a href=\"http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image002_5F00_1765A66A.png\"><img title=\"clip_image002\" style=\"border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; border-left: 0px; display: block; padding-right: 0px; margin-right: auto\" border=\"0\" alt=\"clip_image002\" src=\"http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image002_5F00_thumb_5F00_7B083E7C.png\" width=\"121\" height=\"213\"></a></p></td></tr></tbody></table></p> <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306704\" target=\"_blank\">Stored Contacts Sample</a></h3> <p>This sample illustrates how to use the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.personalinformation.contactstore(v=vs.105).aspx\" target=\"_blank\">ContactStore</a> class and related APIs to create a contact store for your app. This feature is useful if your app uses an existing cloud-based contact store. You can use the APIs you to create contacts on the phone that represent the contacts in your remote store. You can display and modify the contacts in the People Hub on your phone, just like contacts that are added through the built-in experience. You can use the APIs to update and delete contacts you have created on the phone and also to query for any changes the user has made to the contacts locally so you can sync those changes to your remote store. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306701\" target=\"_blank\">Basic Storage Recipes</a></h3> <p>This is a “Windows Runtime Storage 101” sample for Windows Phone developers moving from isolated storage and <b>System.IO</b> to <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.storage.aspx\" target=\"_blank\">Windows.Storage</a> and <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.storage.streams.aspx\" target=\"_blank\">Windows.Storage.Streams</a>. The sample demonstrates how to write to and read files, in addition to how to enumerate directory trees. It also demonstrates how to pass data from one page to the next, and how to persist application state when the app is deactivated. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=301509\" target=\"_blank\">Trial Experience Sample</a></h3> <p>This sample shows you how to design your app to detect its license state when the app launches, and how to detect changes to the license state while running. It comes with a helper class that you can use in your app to wrap <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.applicationmodel.store.licenseinformation.aspx\" target=\"_blank\">LicenseInformation</a> functionality. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=302059\" target=\"_blank\">Windows Runtime Component Sample</a></h3> <p>This sample demonstrates the basics of creating a Windows Phone Runtime component in C++ and consuming it in a XAML app. The sample demonstrates three scenarios: the first scenario illustrates how to call synchronous and asynchronous methods to perform a computation. The second scenario uses the same computation component to demonstrate progress reporting and cancellation of long-running tasks. Finally, the third scenario shows how to use a component to wrap logic that uses <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206944(v=vs.105).aspx\" target=\"_blank\">XAudio2 APIs</a> to play a sound. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306097\" target=\"_blank\">Company Hub Sample</a></h3> <p>This sample demonstrates the construction of an app that is capable of deploying line-of-business (LOB) apps to employees of a corporation. The sample uses an example XML file to define the company XAPs that are available to employees for secure download, and shows you how to dynamically access that file at run time. Then it shows you how to install company apps, enumerate the apps, and then launch the installed company apps. This app is just an example framework and requires additional work beyond the sample to be functional. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306702\" target=\"_blank\">Image Recipes</a></h3> <p>This sample illustrates how to use images in your app efficiently, while giving your users a great experience. It tackles downsampling images, implementing pinch and zoom, and downloading images with a progress display and an option to cancel the download. We’ve taken a recipe approach: each recipe is delivered in a self-contained page in the app so you can focus your attention on the particular part of the sample you are most interested in.  <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306026\" target=\"_blank\">Azure Voice Notes</a></h3> <p>This sample uses Windows Phone speech recognition APIs and Windows Azure Mobile Services to record voice notes as text and store the notes in the cloud. It shows how Mobile Services can be used to authenticate a user with their Microsoft Account. It also demonstrates how to use Mobile Services to store, retrieve, and delete data from an Azure database table. The app generates text from speech using the Windows Phone speech recognition APIs and the phone’s predefined dictation grammar. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=299241\" target=\"_blank\">Kid's Corner Sample</a></h3> <p>This sample illustrates how to use the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.applicationmodel.applicationprofile.modes(v=vs.105).aspx\" target=\"_blank\">ApplicationProfile.Modes</a> property to recognize Kid’s Corner mode. When the app runs, it checks the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.applicationmodel.applicationprofile.modes(v=vs.105).aspx\" target=\"_blank\">ApplicationProfile.Modes</a> property. If the value is <b>ApplicationProfileModes.Alternate</b>, you’ll know that the app is running in Kid’s Corner mode. Depending on the content of your app, you may want to change its appearance or features when it runs in Kid’s Corner mode. Some features that you should consider disabling when running in Kid’s Corner mode include in-app purchases, launching the web browser, and the ad control. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=267468\" target=\"_blank\">URI Association Sample</a></h3> <p>Use this sample to learn how to automatically launch your app via URI association. This sample includes three apps: a URI launcher, and two apps that handle the URI schemes that are built in to the launcher app. You can launch an app that is included with the sample or edit the URI and launch a different app. There is also a button for launching a URI on another phone using Near Field Communication (NFC).  <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=275007\" target=\"_blank\">Speech for Windows Phone: Speech recognition using a custom grammar</a></h3> <p>A grammar defines the words and phrases that an app will recognize in speech input. This sample shows you how to go beyond the basics to create a powerful grammar (based on the grammar schema) with which your app can recognize commands and phrases constructed in different ways. <p>&nbsp; <p>This post is just a glimpse of the latest Windows Phone samples we’ve added to the MSDN code gallery. From launching apps with URI associations, to dictating notes and storing them in the cloud, we hope that there’s something for everyone. We’ll be sure to keep you posted as new samples are added to the collection, so stay tuned. In the meantime, grab the samples, experiment with them, and use the code to light up your apps. You can download all Windows Phone samples at <a href=\"http://code.msdn.microsoft.com/wpapps\" target=\"_blank\">http://code.msdn.microsoft.com/wpapps</a>. <div style=\"clear:both;\"></div><img src=\"http://blogs.windows.com/aggbug.aspx?PostID=588575&AppID=5384&AppType=Weblog&ContentType=0\" width=\"1\" height=\"1\">";
                Items[Items.IndexOf(_item)].Content = htmlNode.InnerHtml.Replace("\r", "").Replace("\n", "");
            }
        }
Exemple #2
0
        private void button2_Click(object sender, EventArgs e)
        {
            // get HTML content from website
            string HTML;
            using (var wc = new WebClient())
            {
                HTML = wc.DownloadString("http://www.gagangiri.org/teachings.html");
            }

            // create HtmlAgilityPack document object from HTML
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(HTML);

            // pasing HTML
            label1.Text = "City: " + doc.GetElementbyId("city").InnerText;
        }
        private void ValidateTable(ValidationEventArgs e)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(e.Response.BodyString);

            var table = doc.GetElementbyId(TableId);

            if (table == null)
            {
                Fail(e, String.Format("Could not locate a table tag named '{0}'!", TableId));
            }
            else if (table.Name != "table")
            {
                Fail(e, String.Format("Found a tag named '{0}' but it wasn't a table!", TableId));
            }
            else
            {
                ValidateTable(e, table);
            }
        }
Exemple #4
0
        public override int Follow()
        {
            // 沒有資料就離開
            if (string.IsNullOrEmpty(this.DownHome.Data)) return 0;

            int result = 0;
            BasicInfo gameInfo = null;
            //HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            //string xPath = "/html[1]/body[1]/div[1]/div[2]/div[1]/div[6]";
            //// 載入資料
            //document.LoadHtml(this.DownHome.Data);
            // 資料位置
            //HtmlAgilityPack.HtmlNode nodeGames = document.DocumentNode.SelectSingleNode(xPath);

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(this.DownHome.Data);
            HtmlAgilityPack.HtmlNode nodeGames = doc.GetElementbyId("calendarWrap");
            // 判斷資料
            if (nodeGames != null && nodeGames.ChildNodes != null)
            {
                DateTime gameDate = this.GameDate;
                DateTime gameTime = this.GameDate;
                // 資料
                foreach (HtmlAgilityPack.HtmlNode gameRow in nodeGames.ChildNodes)
                {
                    // 不是資料就往下處理
                    if (gameRow.Name != "div") continue;
                    if (gameRow.GetAttributeValue("class", "").IndexOf("nogame") != -1) continue;

                    HtmlAgilityPack.HtmlNode table = gameRow.ChildNodes[1].ChildNodes[3];
                    // 資料
                    for (int tr = 1; tr < table.ChildNodes.Count; tr += 2)
                    {
                        string webID = null;
                        string webUrl = null;
                        int td = 1;

                        #region 取得日期
                        if (tr == 1)
                        {
                            string dateStr = table.ChildNodes[tr].ChildNodes[1].ChildNodes[1].ChildNodes[0].InnerText.Replace(".", "/");
                            // 日期錯誤就離開
                            if (!DateTime.TryParse(gameDate.ToString("yyyy/") + " " + dateStr, out gameDate))
                            {
                                break;
                            }
                            td += 2;
                        }
                        #endregion

                        // 資料錯誤就往下處理
                        if (table.ChildNodes[tr].ChildNodes[td + 2].ChildNodes.Count != 10) continue;

                        #region 取得時間
                        string timeStr = table.ChildNodes[tr].ChildNodes[td].InnerText;
                        // 時間錯誤就離開
                        if (!DateTime.TryParse(gameDate.ToString("yyyy/MM/dd") + " " + timeStr, out gameTime)) break;
                        #endregion
                        #region 跟盤 ID
                        if (table.ChildNodes[tr].ChildNodes[td + 4].ChildNodes[1].ChildNodes.Count < 2)
                        {
                            // 沒有跟盤 ID,比賽是中止
                            webID = "P" + table.ChildNodes[tr].ChildNodes[td + 2].ChildNodes[0].InnerText
                                        + table.ChildNodes[tr].ChildNodes[td + 2].ChildNodes[8].InnerText;
                        }
                        else
                        {
                            if (table.ChildNodes[tr].ChildNodes[td + 4].ChildNodes[1].ChildNodes[7].Name.ToLower()=="a")
                            {
                                webID = table.ChildNodes[tr].ChildNodes[td + 4].ChildNodes[1].ChildNodes[7].GetAttributeValue("href", "");
                            }
                            else
                            {
                                webID = table.ChildNodes[tr].ChildNodes[td + 4].ChildNodes[1].ChildNodes[3].GetAttributeValue("href", "");
                            }

                            int findFirst = webID.IndexOf("\'");
                            int findLast = webID.LastIndexOf("\'");
                            if (findFirst != -1 && findLast != -1)
                            {
                                findFirst++;
                                webID = webID.Substring(findFirst, findLast - findFirst);
                            }
                            Uri uri = null;
                            HttpRequest req = null;
                            // 錯誤處理
                            try
                            {
                                uri = new Uri(@"http://www.a.com" + webID);
                                // 判斷是否有資料
                                if (uri.Query != null && !string.IsNullOrEmpty(uri.Query))
                                {
                                    req = new HttpRequest("", uri.AbsoluteUri, uri.Query.Substring(1));
                                    // 判斷資料
                                    if (req["gameid"] != null && !string.IsNullOrEmpty(req["gameid"].Trim()))
                                    {
                                        webID = req["gameid"];
                                        // 判斷編號是否為日期
                                        if (DateTime.TryParse(webID.Substring(0, 4) + "/" + webID.Substring(4, 2) + "/" + webID.Substring(6, 2), out gameDate) &&
                                            gameDate.Date == gameTime.Date)
                                        {
                                            webUrl = string.Format(sWebUrl1, webID.Substring(0, 4), webID.Substring(4, 2), webID) + "?tk=" + DateTime.Now.Ticks.ToString();
                                        }
                                        else
                                        {
                                            gameDate = gameTime.Date;
                                            webUrl = string.Format(sWebUrl1, gameTime.Date.ToString("yyyy"), gameTime.Date.ToString("MM"), webID);
                                        }
                                    }
                                }
                            }
                            catch { webID = null; } // 錯誤,清除跟盤 ID
                            // 沒有跟盤 ID 就往下處理
                            if (webID == null || string.IsNullOrEmpty(webID.Trim())) continue;
                        }
                        #endregion

                        // 不是今天就往下處理
                        if (gameTime.Date != this.GameDate.Date) continue;
                        //if (gameTime.Date != DateTime.Parse("2013-7-7")) continue;

                        // 建立比賽資料
                        gameInfo = null;
                        gameInfo = new BasicInfo(this.AllianceID, this.GameType, gameTime, webID);
                        gameInfo.IsBall = true;
                        gameInfo.Away = table.ChildNodes[tr].ChildNodes[td + 2].ChildNodes[0].InnerText;
                        gameInfo.Home = table.ChildNodes[tr].ChildNodes[td + 2].ChildNodes[8].InnerText;

                        // 比賽中止
                        if (webID.Substring(0, 1) == "P")
                        {
                            //因比賽中止無法透過webID取得正常比分資料,所以取緩存/DB
                            GetGameScore(gameInfo, -1, true);

                            gameInfo.GameStates = "P";
                            gameInfo.TrackerText = "因雨延賽";

                            //BSOB 清除
                            gameInfo.BallB = 0;
                            gameInfo.BallS = 0;
                            gameInfo.BallO = 0;
                            gameInfo.Bases = 0;
                        }
                        else
                        {
                            #region 下載比賽資料,比賽時間 10 分鐘前就開始處理
                            if (!this.DownReal.ContainsKey(webID) &&
                                GetUtcKr(DateTime.Now) >= gameTime.AddMinutes(-10))
                            {
                                this.DownReal[webID] = new BasicDownload(this.Sport, webUrl, webID);
                                this.DownReal[webID].DownloadString();
                            }
                            #endregion

                            #region 處理比賽資料
                            if (this.DownReal.ContainsKey(webID) &&
                                !string.IsNullOrEmpty(this.DownReal[webID].Data))
                            {
                                string data = this.DownReal[webID].Data;
                                int relayStart = data.IndexOf("sportscallback_relay");
                                // 判斷
                                if (relayStart != -1)
                                {
                                    int dataStart = data.IndexOf("document", relayStart);
                                    int dataEnd = data.LastIndexOf("}");
                                    // 沒有資料就離開
                                    if (dataStart == -1 || dataEnd == -1)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        dataStart += 10;
                                        // 錯誤處理
                                        try
                                        {
                                            string strJson = data.Substring(dataStart, dataEnd - dataStart) + "}";
                                            JObject json = JObject.Parse(strJson);

                                            // 隊伍名稱
                                            gameInfo.Away = json["gameInfo"]["aFullName"].ToString();
                                            gameInfo.Home = json["gameInfo"]["hFullName"].ToString();
                                            gameInfo.Status = json["relayTexts"]["currentBatter"]["inn"].ToString();

                                            #region Away
                                            string nums = null;
                                            string[] num = null;
                                            // 分數
                                            if (json["scoreBoard"]["inn"]["away"] != null)
                                            {
                                                nums = json["scoreBoard"]["inn"]["away"].ToString();
                                                num = nums.Replace("\r\n", "").Replace("[", "").Replace("]", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                                // 判斷分數
                                                if (num != null)
                                                {
                                                    foreach (string board in num)
                                                    {
                                                        gameInfo.AwayBoard.Add(board.Trim());
                                                    }
                                                }
                                            }
                                            // 總分
                                            if (json["scoreBoard"]["rheb"]["away"]["r"] != null)
                                            {
                                                gameInfo.AwayPoint = json["scoreBoard"]["rheb"]["away"]["r"].ToString();
                                            }
                                            if (json["scoreBoard"]["rheb"]["away"]["h"] != null)
                                            {
                                                gameInfo.AwayH = json["scoreBoard"]["rheb"]["away"]["h"].ToString();
                                            }
                                            if (json["scoreBoard"]["rheb"]["away"]["e"] != null)
                                            {
                                                gameInfo.AwayE = json["scoreBoard"]["rheb"]["away"]["e"].ToString();
                                            }
                                            #endregion
                                            #region Home
                                            // 分數
                                            if (json["scoreBoard"]["inn"]["home"] != null)
                                            {
                                                nums = json["scoreBoard"]["inn"]["home"].ToString();
                                                num = num = nums.Replace("\r\n", "").Replace("[", "").Replace("]", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                                // 判斷分數
                                                if (num != null)
                                                {
                                                    foreach (string board in num)
                                                    {
                                                        gameInfo.HomeBoard.Add(board.Trim());
                                                    }
                                                }
                                            }
                                            // 總分
                                            if (json["scoreBoard"]["rheb"]["home"]["r"] != null)
                                            {
                                                gameInfo.HomePoint = json["scoreBoard"]["rheb"]["home"]["r"].ToString();
                                            }
                                            if (json["scoreBoard"]["rheb"]["home"]["h"] != null)
                                            {
                                                gameInfo.HomeH = json["scoreBoard"]["rheb"]["home"]["h"].ToString();
                                            }
                                            if (json["scoreBoard"]["rheb"]["home"]["e"] != null)
                                            {
                                                gameInfo.HomeE = json["scoreBoard"]["rheb"]["home"]["e"].ToString();
                                            }
                                            #endregion
                                            #region BSOB
                                            int bsob = 0;
                                            // Bases
                                            if (json["groundBaseAndBallCount"]["b1"]["name"].ToString().Length > 0) bsob += 1;
                                            if (json["groundBaseAndBallCount"]["b2"]["name"].ToString().Length > 0) bsob += 2;
                                            if (json["groundBaseAndBallCount"]["b3"]["name"].ToString().Length > 0) bsob += 4;
                                            gameInfo.Bases = bsob;
                                            // BSO
                                            if (int.TryParse(json["groundBaseAndBallCount"]["sbo"]["b"].ToString(), out bsob)) gameInfo.BallB = bsob;
                                            if (int.TryParse(json["groundBaseAndBallCount"]["sbo"]["s"].ToString(), out bsob)) gameInfo.BallS = bsob;
                                            if (int.TryParse(json["groundBaseAndBallCount"]["sbo"]["o"].ToString(), out bsob)) gameInfo.BallO = bsob;
                                            #endregion
                                            #region 比賽結束
                                            if (json["relayTexts"]["final"] != null &&
                                                json["relayTexts"]["final"].ToString() != "[]")
                                            {
                                                gameInfo.GameStates = "E";
                                                gameInfo.Status = "結束";
                                                gameInfo.BallB = 0;
                                                gameInfo.BallS = 0;
                                                gameInfo.BallO = 0;
                                                gameInfo.Bases = 0;
                                                // 判斷分數
                                                if (gameInfo.AwayBoard.Count > gameInfo.HomeBoard.Count)
                                                {
                                                    gameInfo.HomeBoard.Add("X");
                                                }
                                            }
                                            else
                                            {
                                                // 有分數才是比賽開始
                                                if (gameInfo.Quarter > 0)
                                                {
                                                    gameInfo.GameStates = "S";
                                                }
                                            }
                                            #endregion
                                        }
                                        catch { continue; }
                                    }
                                }
                            }
                            #endregion
                        }

                        // 加入
                        this.GameData[gameInfo.WebID] = gameInfo;
                        // 累計
                        result++;
                    }
                }
            }
            // 傳回
            return result;
        }
 void FinishCompund()
 {
     System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(m_link);
     System.Net.WebResponse response = request.GetResponse();
     System.IO.StringReader reader = new System.IO.StringReader(new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd());
     HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
     document.Load(reader);
     HtmlAgilityPack.HtmlNode mainNode = document.GetElementbyId("p_p_id_dissclinventory_WAR_dissclinventoryportlet_");
     mainNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/table[1]/tbody[1]");
     HtmlAgilityPack.HtmlNode dataNode = mainNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/table[1]/tbody[1]/td[1]/table[2]");
     int numCodes = (dataNode.ChildNodes.Count - 5) / 2;
     m_HazardCodes = new string[numCodes];
     m_HazardTexts = new string[numCodes];
     for (int i = 0; i < numCodes; i++)
     {
         m_HazardTexts[i] = dataNode.ChildNodes[5 + i * 2].ChildNodes[3].InnerText.Trim();
         m_HazardCodes[i] = dataNode.ChildNodes[5 + i * 2].ChildNodes[1].InnerText.Trim();
     }
     HtmlAgilityPack.HtmlNode dsdTableNode = mainNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/table[1]/div[1]/div[1]/div[2]/div[1]/table[1]/tbody[1]");
     HtmlAgilityPack.HtmlNode rPhraseNode = dsdTableNode.ChildNodes[1].ChildNodes[3];
     m_rPhrases = rPhraseNode.InnerText.Trim().Split(' ');
     HtmlAgilityPack.HtmlNode sPhraseNode = dsdTableNode.ChildNodes[1].ChildNodes[5];
     m_SPhrases = sPhraseNode.InnerText.Trim().Split(' ');
     HtmlAgilityPack.HtmlNode indicationOfDangerNode = dsdTableNode.ChildNodes[1].ChildNodes[7];
     m_IndicationOfDanger = indicationOfDangerNode.InnerText.Trim().Split(' ');
     finished = true;
 }
        void document_MouseDown(object sender, System.Windows.Forms.HtmlElementEventArgs e)
        {
            System.Windows.Forms.HtmlElement element = this.automation_browser.Document.GetElementFromPoint(e.ClientMousePosition);

            //System.Windows.Forms.HtmlElement xPath_element = this.automation_browser.Document.GetElementFromPoint(e.ClientMousePosition);



            //******************* for testing XPATH *****************



            var savedId  = element.Id;
            var uniqueId = Guid.NewGuid().ToString();

            element.Id = uniqueId;

            var doc = new HtmlAgilityPack.HtmlDocument();

            doc.LoadHtml(element.Document.GetElementsByTagName("html")[0].OuterHtml);
            element.Id = savedId;

            var    node  = doc.GetElementbyId(uniqueId);
            string xpath = node.XPath;



            string[] parentNodes = xpath.Split('/');

            parentCounting = 0;

            System.Windows.Forms.HtmlElement starting_element = Finding_Parent_With_Identifier(element);

            string starting_element_idName = starting_element.GetAttribute("id");

            string startingPattern = @"//*[@";
            string middlePattern   = "=" + '"'; //"="";
            string endingPattern   = '"' + "]"; //""]";

            string XPATH = startingPattern + "id" + middlePattern + starting_element_idName + endingPattern;

            for (int i = parentNodes.Length - parentCounting + 1; i < parentNodes.Length; i++)
            {
                string tmp = '/' + parentNodes[i];
                XPATH += tmp;
            }



            //******************* for testing XPATH *****************


            if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Right)
            {
                string element_tagName = element.TagName.ToString();
                //string innerHtml=element.TagName.
                //string element_outerHTML = element2.OuterHtml;


                //MessageBox.Show("inner html= " + element.InnerHtml);
                //MessageBox.Show("inner text= "+ element.InnerText);
                //MessageBox.Show("class name= "+element.GetAttribute("class").Trim());

                //MessageBox.Show(element_tagName);


                //MessageBox.Show("id= "+element.GetAttribute("id"));
                //MessageBox.Show("name= "+element.GetAttribute("name"));
                //MessageBox.Show("inner text= " + element.InnerText);
                //MessageBox.Show("inner html= " + element.InnerHtml);

                selenium_id = element.GetAttribute("id").Trim();

                System.Windows.Forms.HtmlElement aelement = automation_browser.Document.GetElementById(selenium_id);
                string element_type = element.GetAttribute("type").Trim();
                //MessageBox.Show(element.InnerHtml);
                //MessageBox.Show(element.OuterHtml);
                // MessageBox.Show(selectedIndex.ToString());

                //MessageBox.Show(element_tagName);
                if (element_type.ToLower() == "radio")
                {
                    selenium_id = element.GetAttribute("id").Trim();
                    if (!input_id_check_str.Contains(selenium_id.ToLower()))
                    {
                        string           msgtext = "Select this Radio Button?";
                        string           txt     = Application.Current.MainWindow.Title;
                        MessageBoxButton button  = MessageBoxButton.YesNoCancel;
                        MessageBoxResult result  = MessageBox.Show(msgtext, txt, button);

                        switch (result)
                        {
                        case MessageBoxResult.Yes:


                            input_id_check_str.Add(selenium_id.ToLower());
                            selenium_name = element.GetAttribute("name").Trim();

                            //object objElement = element.DomElement;
                            //object objSelectedIndex = objElement.GetType().InvokeMember("selectedIndex",
                            //BindingFlags.GetProperty, null, objElement, null);
                            //int selectedIndex = (int)objSelectedIndex;

                            // MessageBox.Show("in yes indes= "+selectedIndex);

                            AutomationBrowser_HtmlElementInfo.Add(new HtmlElementInfo()
                            {
                                Html_element_id    = selenium_id,
                                Html_element_name  = selenium_name,
                                Html_element_XPATH = XPATH
                            });



                            //(this.Parent as MetroWindow).DialogResult = true;
                            //(this.Parent as MetroWindow).Close();
                            break;

                        case MessageBoxResult.No:

                            break;

                        case MessageBoxResult.Cancel:

                            break;
                        }
                    }
                    else
                    {
                        //MessageBox.Show("You have already entered value in thid field.");
                    }
                }
                else
                {
                    MessageBox.Show("Please, Focus only Radio Button");
                }
            }
        }
Exemple #7
0
        public static string DisplayResults()
        {
            string scope = HostingEnvironment.MapPath("~");

            Regex regex = new Regex(@"([a-fA-F0-9]{64})");
            string connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
            HashSet<string> imgExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                {
                    ".jpg", ".jpeg", ".jpe", ".gif", ".png", ".tiff", ".tif", ".svg", ".svgz", ".xbm", ".bmp", ".ico"
                };

            OleDbConnection connection = new OleDbConnection(connectionString);

            string query = @"SELECT TOP 100 System.ItemFolderPathDisplay FROM SystemIndex WHERE scope ='file:" + scope + "' AND System.FileName = 'index.htm' ORDER BY System.DateModified DESC";
            OleDbCommand command = new OleDbCommand(query, connection);
            connection.Open();
            HashSet<string> result = new HashSet<string>();
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string searchString = reader.GetString(0);
                Match match = regex.Match(searchString);
                if (match.Success)
                {
                    result.Add(match.Value);
                }
            }
            connection.Close();
            if (result.Count > 0)
            {
                string searchHTML = "";
                var uniqueResults = result.Distinct();
                foreach (string s in uniqueResults)
                {
                    var signature = "";
                    var img = "";
                    //var file = "";
                    var msg = "";
                    var date = "";
                    var blockchain = "";
                    var profiles = "";
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    try
                    {
                        doc.Load(scope + s + "\\index.htm");
                    }
                    catch { break; }


                    try
                    {
                        img = doc.GetElementbyId("img0").InnerText;
                        searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"><a href=\"" + s + "/index.htm\"><img src=\"" + s + "/" + img + "\" /></a></th><th></th></tr>";
                    }
                    catch { searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"></th><th></th></tr>"; }
                    try { signature = doc.GetElementbyId("signature").InnerText; }
                    catch { }
                    try { blockchain = doc.GetElementbyId("blockchain").InnerText; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td>" + blockchain + " - " + signature + "</td></tr>";
                    try { date = doc.GetElementbyId("block-date").InnerText; }
                    catch { }
                    try { msg = doc.GetElementbyId("msg1").InnerText; }
                    catch { }
                    try { profiles = doc.GetElementbyId("profiles").InnerHtml; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\">" + msg.PadRight(50).Substring(0, 49) + "</a></td></tr>";

                    if (msg.Length > 500)
                    { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg.Substring(0, 499) + "...</td></tr>"; }
                    else { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg + "</td></tr>"; }

                    if (profiles.Length > 0)
                    {
                        searchHTML = searchHTML + "<tr><td>" + profiles + "</td></tr>";
                    }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\"><font size=\"1\">" + s + "</font></a></td></tr></table></div></div>";

                }
                return searchHTML;

            }
            else
            { return "<div class=\"item\"><div class=\"content\">Nothing found</div></div>"; }
        
        }
Exemple #8
0
        private BasicInfo ProcessGameData(HtmlAgilityPack.HtmlNode game, DateTime gameDate, string webID)
        {
            // 建立比賽資料,時間以台灣為主
            BasicInfo gameInfo = new BasicInfo(this.AllianceID, this.GameType, gameDate, webID);
            gameInfo.Away = game.SelectSingleNode("div/div[@class='team visitor']/div[@class='team-capsule']/p[@class='team-name']/span/a").InnerText;
            gameInfo.Home = game.SelectSingleNode("div/div[@class='team home']/div[@class='team-capsule']/p[@class='team-name']/span/a").InnerText;
            gameInfo.Status = game.SelectSingleNode("div/div[@class='game-header']/div/p").InnerText;
            gameInfo.Status = gameInfo.Status.ToLower();
            // 取代文字
            gameInfo.Status = gameInfo.Status.Replace("halftime", "中場休息");
            gameInfo.Status = gameInfo.Status.Replace("half", "中場休息");
            gameInfo.Status = gameInfo.Status.Replace("qtr", "");
            gameInfo.Status = gameInfo.Status.Replace("1st", "");
            gameInfo.Status = gameInfo.Status.Replace("2nd", "");
            gameInfo.Status = gameInfo.Status.Replace("3rd", "");
            gameInfo.Status = gameInfo.Status.Replace("4th", "");
            gameInfo.Status = gameInfo.Status.Replace("ot", "");
            gameInfo.Status = gameInfo.Status.Replace("2ot", "");
            gameInfo.Status = gameInfo.Status.Replace("of", "");
            gameInfo.Status = gameInfo.Status.Replace("end", "結束");
            gameInfo.Status = gameInfo.Status.Replace("&nbsp;", "");//移除空白字元
            gameInfo.Status = gameInfo.Status.Trim();

            if (gameInfo.Status == "00:00") gameInfo.Status = "結束";

            //目前有顯示的分數欄位

            HtmlAgilityPack.HtmlNode scoreHeader = game.SelectSingleNode("div/div[@class='game-header']/ul[@class='score header']");
            if (scoreHeader != null)//是否已經有比分
            {
                string linescoreHeader = game.SelectSingleNode("div/div[@class='game-header']/ul[@class='score header']").InnerText;
                if (linescoreHeader.Length > 7)//資料不完整,缺乏前面局數比分     2 3 4 OT OT T
                {
                    //第1個數字才是有顯示的比分
                    int lossInning = 1;
                    int.TryParse(linescoreHeader.Substring(0, 1), out lossInning);
                    if (lossInning > 1)
                    {
                        lossInning--;
                        GetGameScore(gameInfo, lossInning);//無暫存取得遺漏比分
                    }
                }

                List<int> FullAwayBoard = new List<int>();//完整比分
                List<int> FullHomeBoard = new List<int>();//完整比分
                if (this.DownScore.ContainsKey(webID) && !string.IsNullOrEmpty(this.DownScore[webID].Data))
                {
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(this.DownScore[webID].Data);

                    HtmlAgilityPack.HtmlNodeCollection HomeAway = doc.GetElementbyId("gamepackageTop").SelectNodes("div[@class='line-score clear']/div[@class='line-score-container']/table/tr");
                    if (HomeAway != null && HomeAway.Count == 3)
                    {
                        foreach (HtmlAgilityPack.HtmlNode scores in HomeAway)
                        {
                            if (scores.Attributes["class"] != null)//忽略periods
                                continue;

                            HtmlAgilityPack.HtmlNodeCollection score = scores.SelectNodes("td");
                            if (score != null)
                            {
                                bool isAway = false;
                                if (FullAwayBoard.Count == 0)
                                    isAway = true;

                                int period = score.Count - 1;
                                for (int i = 1; i < period; i++)//第0個值為隊名
                                {
                                    string tmpNum = score[i].InnerHtml.Replace("\n", "").Replace("\t", "").Trim();
                                    int tryInt = 0;
                                    int.TryParse(tmpNum, out tryInt);

                                    if (isAway)
                                        FullAwayBoard.Add(tryInt);
                                    else
                                        FullHomeBoard.Add(tryInt);
                                }
                            }
                        }
                    }
                }

                //首頁比分計算
                foreach (HtmlAgilityPack.HtmlNode numDoc in game.SelectNodes("div/div[@class='team visitor']/ul[@class='score']/li"))
                {
                    int num = 0;
                    if (int.TryParse(numDoc.InnerText, out num))
                    {
                        if (gameInfo.AwayBoard.Count < 4)//沒有OT
                            gameInfo.AwayBoard.Add(numDoc.InnerText);
                        else
                        {
                            int otDiff = FullAwayBoard.Count - gameInfo.AwayBoard.Count;//OT數差別
                            if (FullAwayBoard.Count == 0 || otDiff == 0)
                                gameInfo.AwayBoard.Add(numDoc.InnerText);
                            else
                            {
                                int sum = 0;
                                for (int i = 0; i < otDiff - 1; i++)
                                {
                                    sum += FullAwayBoard[4 + i];//最後一個OT不累加
                                    gameInfo.AwayBoard.Add(FullAwayBoard[4 + i].ToString());//OT1 OT2 OT3 ...
                                }

                                gameInfo.AwayBoard.Add((num - sum).ToString());//剩下的OT分數
                            }
                        }
                    }
                }

                foreach (HtmlAgilityPack.HtmlNode numDoc in game.SelectNodes("div/div[@class='team home']/ul[@class='score']/li"))
                {
                    int num = 0;
                    if (int.TryParse(numDoc.InnerText, out num))
                    {
                        if (gameInfo.HomeBoard.Count < 4)//沒有OT
                            gameInfo.HomeBoard.Add(numDoc.InnerText);
                        else
                        {
                            int otDiff = FullHomeBoard.Count - gameInfo.HomeBoard.Count;//OT數差別
                            if (FullHomeBoard.Count == 0 || otDiff == 0)//尚未取得完整比分資料 或者是最後一個比分則為總分
                                gameInfo.HomeBoard.Add(numDoc.InnerText);
                            else
                            {
                                int sum = 0;
                                for (int i = 0; i < otDiff - 1; i++)
                                {
                                    sum += FullHomeBoard[4 + i];//最後一個OT不累加
                                    gameInfo.HomeBoard.Add(FullHomeBoard[4 + i].ToString());//OT1 OT2 OT3 ...
                                }

                                gameInfo.HomeBoard.Add((num - sum).ToString());//剩下的OT分數
                            }
                        }
                    }
                }
                // 總分
                if (gameInfo.AwayBoard.Count > 0)
                {
                    gameInfo.AwayPoint = gameInfo.AwayBoard[gameInfo.AwayBoard.Count - 1];
                    gameInfo.AwayBoard.RemoveAt(gameInfo.AwayBoard.Count - 1);
                    gameInfo.HomePoint = gameInfo.HomeBoard[gameInfo.HomeBoard.Count - 1];
                    gameInfo.HomeBoard.RemoveAt(gameInfo.HomeBoard.Count - 1);
                }
            }

            if (gameInfo.Status.IndexOf("final") != -1)
            {
                gameInfo.GameStates = "E";
            }
            else if (gameInfo.Quarter > 0)
            {
                gameInfo.GameStates = "S";
            }

            return gameInfo;
        }
        private List <MonitoringItem> ParsingAlbumType(HtmlAgilityPack.HtmlDocument doc)
        {
            List <MonitoringItem> lstItem = new List <MonitoringItem>();

            HtmlAgilityPack.HtmlNode mainArea = doc.GetElementbyId("main-area");
            if (mainArea != null)
            {
                var ulArticleBoard = mainArea.SelectNodes("ul").FirstOrDefault(x => CommonHelper.HasClass(x, "article-album-sub"));
                if (ulArticleBoard != null)
                {
                    foreach (var liArticle in ulArticleBoard.SelectNodes("li"))
                    {
                        string articleUrl = liArticle.SelectSingleNode("a").GetAttributeValue("href", "").Replace("&amp;", "&");
                        string articleId  = "";

                        foreach (var param in articleUrl.Split('&'))
                        {
                            string[] arrParam = param.Split('=');
                            string   paramKey = arrParam[0];

                            if (paramKey == "articleid" && arrParam.Length == 2)
                            {
                                articleId = arrParam[1];
                                break;
                            }
                        }

                        string articleTitle = CommonHelper.GetSingleNode(liArticle, "dl", "dt").InnerText.Trim();

                        string articlePrice = "0";
                        var    ddPrice      = liArticle.SelectSingleNode("dl").SelectNodes("dd").FirstOrDefault(x => CommonHelper.HasClass(x, "price"));
                        if (ddPrice != null)
                        {
                            articlePrice = new string(ddPrice.InnerText.Where(x => Char.IsDigit(x)).ToArray());
                        }

                        int itemPrice = 0;
                        Int32.TryParse(articlePrice, out itemPrice);


                        lstItem.Add(new MonitoringItem()
                        {
                            ItemId        = articleId,
                            ItemTitle     = articleTitle,
                            ItemUrlPc     = string.Format(ItemDetailBaseUrlDesktop, articleId),
                            ItemUrlMobile = string.Format(ItemDetailBaseUrlMobile, articleId),
                            ItemPrice     = itemPrice,
                            ItemDate      = DateTime.Now
                        });
                    }
                }
                else
                {
                    FuncLog($"could not find article area");
                }
            }
            else
            {
                FuncLog($"could not find main-area");
            }

            return(lstItem);
        }
Exemple #10
0
        /// <summary>
        /// Updates the preview.
        /// </summary>
        protected void UpdatePreview()
        {
            var templateDoc = new HtmlAgilityPack.HtmlDocument();

            templateDoc.LoadHtml(ceEmailTemplate.Text);

            // only show the template logo uploader if there is a div with id='template-logo'
            // then update the help-message on the loader based on the template-logo's data-instructions attribute and width and height
            // this gets called when the codeeditor is done initializing and when the cursor blurs out of the template code editor
            var templateLogoNode = templateDoc.GetElementbyId("template-logo");

            if (templateLogoNode != null)
            {
                string helpText = null;
                if (templateLogoNode.Attributes.Contains("data-instructions"))
                {
                    helpText = templateLogoNode.Attributes["data-instructions"].Value;
                }

                if (helpText.IsNullOrWhiteSpace())
                {
                    helpText = "The Logo that can be included in the contents of the message";
                }

                string helpWidth  = null;
                string helpHeight = null;
                if (templateLogoNode.Attributes.Contains("width"))
                {
                    helpWidth = templateLogoNode.Attributes["width"].Value;
                }

                if (templateLogoNode.Attributes.Contains("height"))
                {
                    helpHeight = templateLogoNode.Attributes["height"].Value;
                }

                if (helpWidth.IsNotNullOrWhiteSpace() && helpHeight.IsNotNullOrWhiteSpace())
                {
                    helpText += string.Format(" (Image size: {0}px x {1}px)", helpWidth, helpHeight);
                }

                imgTemplateLogo.Help = helpText;
            }

            pnlTemplateLogo.Visible = templateLogoNode != null;

            // take care of the lava fields stuff
            var lavaFieldsNode = templateDoc.GetElementbyId("lava-fields");

            if (lavaFieldsNode == null)
            {
                lavaFieldsNode = templateDoc.CreateElement("noscript");
                lavaFieldsNode.Attributes.Add("id", "lava-fields");
            }
            else if (lavaFieldsNode.ParentNode.Name == "body")
            {
                // if the lava-fields is a in the body (from pre-v9 template), remove it from body, and let it get added to head instead
                lavaFieldsNode.Attributes.Remove("style");
                lavaFieldsNode.Remove();
                lavaFieldsNode.Name = "noscript";
            }

            var templateDocLavaFieldLines = lavaFieldsNode.InnerText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim()).Where(a => a.IsNotNullOrWhiteSpace()).ToList();

            // dictionary of keys and default values from Lava Fields KeyValueList control
            var lavaFieldsDefaultDictionary = kvlMergeFields.Value.AsDictionary();

            // add any new lava fields that were added to the KeyValueList editor
            foreach (var keyValue in lavaFieldsDefaultDictionary)
            {
                string pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key);
                if (!templateDocLavaFieldLines.Any(a => Regex.IsMatch(a, pattern)))
                {
                    templateDocLavaFieldLines.Add("{% assign " + keyValue.Key + " = '" + keyValue.Value + "' %}");
                }
            }

            // remove any lava fields that are not in the KeyValueList editor
            foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines.ToList())
            {
                var found = false;
                foreach (var keyValue in lavaFieldsDefaultDictionary)
                {
                    var pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key);
                    if (!Regex.IsMatch(templateDocLavaFieldLine, pattern))
                    {
                        continue;
                    }

                    found = true;
                    break;
                }

                // if not found, delete it
                if (!found)
                {
                    templateDocLavaFieldLines.Remove(templateDocLavaFieldLine);
                }
            }

            // dictionary of keys and values from the lava fields in the 'lava-fields' div
            var lavaFieldsTemplateDictionary = new Dictionary <string, string>();

            foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines)
            {
                var match = Regex.Match(templateDocLavaFieldLine, @"{% assign (.*)\=(.*) %}");
                if (match.Groups.Count != 3)
                {
                    continue;
                }

                var key   = match.Groups[1].Value.Trim().RemoveSpaces();
                var value = match.Groups[2].Value.Trim().Trim('\'');

                // If this is a postback, there will be a control that holds the value
                var lavaValueControl = phLavaFieldsControls.FindControl("lavaValue_" + key) as RockTextBox;
                if (lavaValueControl != null && lavaValueControl.Text != value)
                {
                    value = lavaValueControl.Text;
                }

                lavaFieldsTemplateDictionary.Add(key, value);
            }

            if (lavaFieldsTemplateDictionary.Any())
            {
                var lavaAssignsHtml = new StringBuilder();
                lavaAssignsHtml.AppendLine();
                lavaAssignsHtml.AppendLine("    {% comment %}  Lava Fields: Code-Generated from Template Editor {% endcomment %}");
                foreach (var lavaFieldsTemplateItem in lavaFieldsTemplateDictionary)
                {
                    lavaAssignsHtml.AppendLine(string.Format("    {{% assign {0} = '{1}' %}}", lavaFieldsTemplateItem.Key, lavaFieldsTemplateItem.Value));
                }

                lavaAssignsHtml.Append("  ");

                lavaFieldsNode.InnerHtml = lavaAssignsHtml.ToString();

                if (lavaFieldsNode.ParentNode == null)
                {
                    var headNode = templateDoc.DocumentNode.SelectSingleNode("//head");
                    if (headNode != null)
                    {
                        // prepend a linefeed so that it is after the lava node (to make it pretty printed)
                        headNode.PrependChild(templateDoc.CreateTextNode("\r\n"));

                        headNode.PrependChild(lavaFieldsNode);

                        // prepend a indented linefeed so that it ends up prior the lava node (to make it pretty printed)
                        headNode.PrependChild(templateDoc.CreateTextNode("\r\n  "));
                    }
                }
            }
            else if (lavaFieldsNode.ParentNode != null)
            {
                if (lavaFieldsNode.NextSibling != null && lavaFieldsNode.NextSibling.Name == "#text")
                {
                    // remove the extra line endings
                    lavaFieldsNode.NextSibling.InnerHtml = lavaFieldsNode.NextSibling.InnerHtml.TrimStart(' ', '\r', '\n');
                }

                lavaFieldsNode.Remove();
            }

            hfLavaFieldsState.Value = lavaFieldsTemplateDictionary.ToJson(Newtonsoft.Json.Formatting.None);

            ceEmailTemplate.Text = templateDoc.DocumentNode.OuterHtml;

            CreateDynamicLavaValueControls();

            var mergeFields         = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage);
            var resolvedPreviewHtml = ceEmailTemplate.Text.ResolveMergeFields(mergeFields);

            if (cbCssInliningEnabled.Checked)
            {
                resolvedPreviewHtml = resolvedPreviewHtml.ConvertHtmlStylesToInlineAttributes();
            }

            ifEmailPreview.Attributes["srcdoc"] = resolvedPreviewHtml;
            pnlEmailPreview.Visible             = true;
            upnlEmailPreview.Update();
        }
        List<Show> Grab(GrabParametersBase p)
        {
            var pp = (GrabParameters)p;

            var url = GetUrl(pp);
            _logger.WriteEntry(string.Format("Grabbing rashut2 {0} for date {1}", pp.Channel, pp.Date.ToString("d")), LogType.Info);
            var wr = WebRequest.Create(string.Format(url, pp.Date.ToString(DateFormat)));
            var res = (HttpWebResponse)wr.GetResponse();
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(res.GetResponseStream());

            var nodes = doc.DocumentNode.SelectNodes("//comment()");
            if (nodes != null)
            {
                foreach (HtmlAgilityPack.HtmlNode comment in nodes)
                {
                    if (!comment.InnerText.StartsWith("DOCTYPE"))
                        comment.ParentNode.RemoveChild(comment);
                }
            }

            int cellDelta = 0;
            var tbl = doc.GetElementbyId("table5");
            if (pp.Channel == Channel.Channel10)
            {
                tbl = doc.GetElementbyId("table1");
                cellDelta = 1;
            }

            const int childStart = 9;
            var shows = new List<Show>();
            for (int i = childStart; i < tbl.ChildNodes.Count; i += 2)
            {
                var show = new Show();
                var d = Convert.ToDateTime(Tools.CleanupText(tbl.ChildNodes[i].ChildNodes[1].InnerText));
                show.StartTime = pp.Date.AddHours(d.Hour).AddMinutes(d.Minute);
                if (d.Hour < 6) // data is shown from 6 (AM) till next day 6 (AM) so after midnight we need to increase the date
                    show.StartTime = show.StartTime.AddDays(1);
                try
                {
                    show.StartTime = TimeZoneInfo.ConvertTimeToUtc(show.StartTime, TimeZoneInfo.Local);
                }
                catch (Exception ex) // error on the verge of daylight saving start
                {
                    _logger.WriteEntry(ex.Message, LogType.Error);
                    continue;
                }

                show.Title = Tools.CleanupText(tbl.ChildNodes[i].ChildNodes[3 + cellDelta].InnerText);
                var episodeName = Tools.CleanupText(tbl.ChildNodes[i].ChildNodes[5 + cellDelta].InnerText);
                var episodeNumber = Tools.CleanupText(tbl.ChildNodes[i].ChildNodes[7 + cellDelta].InnerText);
                var genere = Tools.CleanupText(tbl.ChildNodes[i].ChildNodes[9 + cellDelta].InnerText);
                show.Description = string.Empty;
                if (!string.IsNullOrEmpty(episodeName))
                    show.Description += string.Format("שם הפרק : {0}\n", episodeName);
                if (!string.IsNullOrEmpty(episodeNumber))
                {
                    show.Description += string.Format("מספר הפרק : {0}\n", episodeNumber);
                    int num;
                    if (int.TryParse(episodeNumber, out num))
                        show.Episode = num;
                }
                if (!string.IsNullOrEmpty(genere))
                    show.Description += string.Format("סוג תכנית : {0}\n", genere);
                shows.Add(show);
            }

            for (int i = shows.Count - 1; i >= 0; i--)
            {
                var show = shows[i];
                if (show.Description != null)
                    show.Description = show.Description.Trim();
                show.Channel = pp.Channel.ToString();
                if (i == shows.Count - 1)
                    show.EndTime = show.StartTime.AddHours(1);
                else
                    show.EndTime = shows[i + 1].StartTime;
            }

            return shows;
        }
Exemple #12
0
        public override int Follow()
        {
            // 沒有資料就離開
            if (string.IsNullOrEmpty(this.DownHome.Data)) return 0;

            int result = 0;
            //BasicInfo gameInfo = null;
            DateTime gameDate = this.GameDate;
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            //string xPath = "/html[1]/body[1]/table[2]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[2]/table[2]/tbody[1]/tr[2]/td[1]/iframe[1]";
            //2015.05.10  04:47改为直接使用ID查找
            // 載入資料
            document.LoadHtml(this.DownHome.Data);
            // 資料位置
            HtmlAgilityPack.HtmlNode nodeGame = document.GetElementbyId("timebf");//document.DocumentNode.SelectSingleNode(xPath);
            // 判斷資料
            if (nodeGame != null)
            {
                #region 下載比賽資料

                // 取出網址
                string webUrl = nodeGame.GetAttributeValue("src", "");
                // 正確的網址
                webUrl = this.DownHome.Uri.ToString() + webUrl;
                // 下載比賽資料
                if (this.DownHomeData.Count == 0)
                {
                    this.DownHomeData.Add(new BasicDownload(this.Sport, webUrl, Encoding.GetEncoding(936)));
                    this.DownHomeData[0].DownloadString();
                }

                #endregion 下載比賽資料

                #region 下載提示資料

                if (this.DownHomeData.Count == 1)
                {
                    this.DownHomeData.Add(new BasicDownload(this.Sport, string.Format(spboUrl + "/s/i.xml"), Encoding.GetEncoding(936)));
                    this.DownHomeData[1].DownloadString();
                }

                #endregion 下載提示資料

                if (!string.IsNullOrEmpty(this.DownHomeData[0].Data))
                {
                    // 載入資料
                    document.LoadHtml(this.DownHomeData[0].Data);

                    #region 取出日期

                    string date = document.DocumentNode.SelectSingleNode("/html[1]/script[1]").InnerText.Trim();
                    string regstr = @"(?i)(?<=<td.*?.*?>)[^<]+(?=日</td>)"; // 提取td的文字
                    Regex reg = new Regex(regstr, RegexOptions.None);
                    if (reg.Match(date).Success)
                    {
                        string gameDateStr = reg.Match(date).Groups[0].Value.Replace("月", "/");
                        // 轉換日期
                        if (!DateTime.TryParse(DateTime.Now.ToString("yyyy") + "/" + gameDateStr, out gameDate))
                        {
                            gameDate = this.GameDate;
                        }
                        // 日期比今天還大,可能是跨年,扣掉一年
                        if (gameDate.Date > DateTime.Now.Date)
                        {
                            gameDate = gameDate.AddYears(-1);
                        }
                    }

                    #endregion 取出日期

                    #region 處理比賽資料

                    if (this.DownHomeData[0].HasChanged)
                    {
                        this.DownHomeData[0].HasChanged = false;

                        string doc = document.DocumentNode.SelectSingleNode("/html[1]").InnerText.Trim();
                        if (string.IsNullOrWhiteSpace(doc))
                        {
                            return 0;
                        }
                        string[] data = doc.Split(new string[] { "var" }, StringSplitOptions.RemoveEmptyEntries);
                        // 判斷資料
                        if (data.Length > 0)
                        {
                            data[0] = data[0].Replace("bf=\"", "");
                            data[0] = data[0].Replace("\";", "");
                            data[0] = data[0].Trim();
                            data = data[0].Split(new string[] { "!" }, StringSplitOptions.RemoveEmptyEntries);

                            ConcurrentDictionary<string, BasicInfo> dicGame = new ConcurrentDictionary<string, BasicInfo>();
                            // 資料
                            int OrderBy = 1;//按照来源网排序
                            foreach (string d in data)
                            {
                                string[] info = d.Split(new string[] { "," }, StringSplitOptions.None);
                                // 資料錯誤就往下處理
                                if (info.Length < 29 || info[14].Trim() == "") continue;
                                // 排除非足球比賽
                                if (info[0] == "NBA" || info[0] == "WNBA" || info[0] == "NCAA" || info[0] == "EBA" ||
                                                info[0] == "STAR" || info[0] == "EuroB" || info[0] == "WORLD" || info[0] == "CBA" ||
                                                info[0] == "AsiaB" || info[0] == "AmerB" || info[0] == "ABA" || info[0] == "KBA" ||
                                                info[0] == "SBA" || info[0] == "WYB" || info[0] == "OlymB")
                                    continue;

                                BasicInfo game = new BasicInfo(0, this.GameType, gameDate, GetMd5Str(string.Concat(info[0].Trim(), gameDate.ToString("yyyyMMdd"), info[5].Trim(), info[6].Trim())));

                                #region 設定

                                game.AllianceName = info[0]; //AL
                                game.AC = info[1];
                                game.GameStates = info[3]; //KO
                                game.Status = this.GetUP(info[2], info[4]);//UP
                                game.Home = info[5];//NA
                                game.Away = info[6];//NB
                                game.HomePoint = info[11];//OA
                                game.AwayPoint = info[12];//OB
                                game.HomeBoard.Add("");//RA
                                game.AwayBoard.Add("");//RB
                                game.WN = 0;
                                game.NAR = "";
                                game.NBR = "";
                                //game["DA"] = info[17];
                                game.ZA = info[21];
                                game.ZB = info[23];
                                game.ZC = info[22];
                                webIDData[info[14]] = game.WebID; //记录来源网ID 和我们自己生成的ID的键值对 key:来源网ID val:md5ID
                                #endregion 設定

                                #region 半場

                                string[] nums = info[13].Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                                // 判斷半場分數
                                if (nums.Length == 2)
                                {
                                    game.HomeBoard[0] = nums[0].Trim();
                                    game.AwayBoard[0] = nums[1].Trim();
                                }

                                #endregion 半場

                                #region 紅牌

                                if (!string.IsNullOrEmpty(info[8]))
                                {
                                    game.NAR = string.Format("<span>{0}</span>", info[8]);
                                }
                                if (!string.IsNullOrEmpty(info[9]))
                                {
                                    game.NBR = string.Format("<span>{0}</span>", info[9]);
                                }

                                #endregion 紅牌

                                #region 輸贏

                                int teamA = 0;
                                int teamB = 0;
                                if (int.TryParse(game.HomePoint, out teamA) &&
                                    int.TryParse(game.AwayPoint, out teamB) &&
                                    game.Status.IndexOf("完") != -1)
                                {
                                    if (teamA > teamB) game.WN = 1;
                                    if (teamA < teamB) game.WN = 2;
                                }

                                #endregion 輸贏

                                #region 盤口

                                if (info[24] != "")
                                {
                                    string key = info[14] + "+" + info[17] + "+" + info[24];
                                    // 日期不同就清除下載資料
                                    if (this.DownAnalysisDate != gameDate.Date)
                                    {
                                        this.DownAnalysisDate = gameDate.Date;//日期

                                        foreach (KeyValuePair<string, BasicDownload> real in this.DownAnalysisData)
                                            real.Value.Dispose();//釋放資源

                                        this.DownAnalysisData.Clear();
                                        this.AlreadyEndingData.Clear();

                                        // 強制更新 下載昨天資料
                                        foreach (BasicDownload real in this.DownReal)
                                        {
                                            real.FileWrite = false;
                                            real.DownloadString();
                                        }
                                    }

                                    //若已完賽 則加入完賽容器中
                                    //2015-6-2 新增判斷
                                    //至少下载成功过一次的key才add到已完赛容器
                                    //防止第一次启动,导致当下已完赛的走势图不显示
                                    if (game.Status.IndexOf("完") != -1 &&
                                        this.DownAnalysisData.ContainsKey(key) &&
                                        this.DownAnalysisData[key].Data != null &&
                                        !this.AlreadyEndingData.Contains(key))
                                    {
                                        this.AlreadyEndingData.Add(key);//若已完賽 則加入完賽容器中
                                    }

                                    // 加入下載
                                    if (!this.DownAnalysisData.ContainsKey(key))//未在排程中 則加入
                                    {
                                        string url = @"http://www8.spbo.com/pl_sb_rq.plex?id=" + info[24] + "&z=" + info[5] + "&k=" + info[6];
                                        //來源網domain被綁架,暫時使用備用來源 http://www8.spbo1.com/
                                        Console.WriteLine("新加入 " + url);
                                        this.DownAnalysisData[key] = new BasicDownload(this.Sport, url);
                                        this.DownAnalysisData[key].FileWrite = false;
                                        //this.DownAnalysisData[key].DownloadAnalysisString();
                                    }
                                }
                                if (game.ZC != "")
                                {
                                    decimal dAway = 0;
                                    decimal dHome = 0;
                                    decimal.TryParse(game.ZA, out dAway); if (dAway > 0) dAway += 0.01m;
                                    decimal.TryParse(game.ZB, out dHome); if (dHome > 0) dHome += 0.01m;
                                    game.ZA = dAway.ToString("n2");
                                    game.ZB = dHome.ToString("n2");
                                }

                                #endregion 盤口

                                #region 黃牌

                                game.CA = info[25];
                                game.CB = info[26];

                                #endregion 黃牌

                                #region 排名

                                game.SA = info[27];
                                game.SB = info[28];

                                #endregion 排名

                                #region OrderBy排序逻辑
                                game.PR = OrderBy;
                                OrderBy++;
                                #endregion OrderBy排序逻辑

                                // 加入
                                dicGame[game.WebID] = game; // 原本是 info[17]
                            }

                            #region 處理提示資料

                            if (!string.IsNullOrEmpty(this.DownHomeData[1].Data))
                            {
                                BasicInfo message = new BasicInfo(0, "message", gameDate, "m_" + gameDate.ToString("yyyyMMdd"));
                                message.HomeBoard.Add("");// 这2个add是为了
                                message.AwayBoard.Add("");// 防止报错
                                message.Record = "-1";// 当 gametype=message  記錄 我們自己生成的 md5 webid
                                message.PR = -10;
                                System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
                                xml.LoadXml(this.DownHomeData[1].Data);
                                string[] goal = xml.DocumentElement.InnerText.Split(new string[] { "__" }, StringSplitOptions.None);
                                //string[] goal = "16__1__7701810135*1*1 - 0_".Split(new string[] { "__" }, StringSplitOptions.None);
                                if (goal.Length == 3)
                                {
                                    foreach (string str in goal[2].Split('_'))
                                    {
                                        string[] txt = str.Split('*');

                                        if (txt.Length < 3) continue;

                                        //根據來源網中的webid 找到 BasicInfo
                                        var obj = (from c in webIDData where c.Key == (txt[0]) select c.Value).ToList();

                                        if (obj.Count > 0)
                                        {
                                            BasicInfo game = dicGame[obj[0]];

                                            string al = game.AllianceName;
                                            // 找到訊息
                                            if (al != "NBA" && al != "WNBA" && al != "NCAA" && al != "EBA" &&
                                                al != "STAR" && al != "EuroB" && al != "WORLD" && al != "CBA" &&
                                                al != "AsiaB" && al != "AmerB" && al != "ABA" && al != "KBA" &&
                                                al != "SBA" && al != "WYB" && al != "OlymB")
                                            {
                                                string Home = game.Home;
                                                string Away = game.Away;
                                                // 判斷
                                                if (txt[1] == "1")
                                                    Home = "<font color=#FF0000>" + Home + "</font>";
                                                else
                                                    Away = "<font color=#FF0000>" + Away + "</font>";
                                                // 訊息
                                                message.Status += al + ":" + Home + "<font color=blue>&nbsp;" + txt[2] + "&nbsp;</font>" + Away;
                                                message.Record = game.WebID;
                                            }
                                        }
                                    }
                                }
                                // 加入
                                dicGame[message.WebID] = message;
                            }

                            #endregion 處理提示資料

                            // 建立比賽資料
                            //gameInfo = null;
                            //gameInfo = new BasicInfo(this.AllianceID, this.GameType, gameDate, gameDate.ToString("yyyy-MM-dd"));
                            //gameInfo.Away = "足球";
                            //gameInfo.Home = "跟盤";
                            //gameInfo.Status = json.ToString(Formatting.None);

                            dicGameData[gameDate.ToString("yyyyMMdd")] = dicGame;
                            // 加入
                            //this.GameData[gameInfo.WebID] = gameInfo;
                            // 累計
                            result++;
                        }
                    }

                    #endregion 處理比賽資料

                    // 分析資料 SA
                    result += this.FollowAnalysisData(gameDate);
                }
            }

            if (!string.IsNullOrEmpty(this.DownHomeData[0].Data))
            {
                // 儲存跟盤網頁的當天日期
                if (this.DownHomeDate == null ||
                    this.DownHomeDate.Value.Date != gameDate.Date)
                {
                    this.DownHomeDate = gameDate;
                    this.UpdateSetFootballDate(frmMain.ConnectionString, gameDate.Date);
                }
                // 昨天
                if (this.DownReal[0].HasChanged)
                {
                    this.DownReal[0].HasChanged = false;
                    result += this.FollowYesterday(this.DownReal[0].Data, gameDate.AddDays(-1));
                }

                // 往後 7 天
                for (int i = 1; i <= 7; i++)
                {
                    if (this.DownReal[i].HasChanged)
                    {
                        this.DownReal[i].HasChanged = false;
                        result += this.FollowTomorrow(this.DownReal[i].Data, gameDate.Date.AddDays(i));
                    }
                }
            }

            //result = this.GameData.Count;
            result = dicGameData.Count;
            // 傳回
            return result;
        }
        //Parser

        public static AnimalRecord HtmlDocumentToAnimalRecord(HtmlAgilityPack.HtmlDocument d)
        {
            // ReSharper disable UseObjectOrCollectionInitializer
            AnimalRecord r = new AnimalRecord();

            // ReSharper restore UseObjectOrCollectionInitializer

            try
            {
                // ReSharper disable InconsistentNaming
                // ReSharper disable UnusedVariable
                char[] _s       = new[] { ' ' };
                char[] _colon   = new[] { ':' };
                char[] _comma   = new[] { ',' };
                char[] _comma_s = new[] { ',', ' ' };
                // ReSharper restore UnusedVariable
                // ReSharper restore InconsistentNaming

                //Title
                r.ReportTitle = d.DocumentNode.SelectSingleNode("//head/title").InnerText.Trim();
                //Animal Subsection
                r.ANum        = d.GetElementbyId("cphWorkArea_lblAnimalNumber").InnerText.Replace("Animal:", "").Trim();
                r.DatePrinted =
                    DateTime.Parse(d.GetElementbyId("cphWorkArea_lblPrintStamp").InnerText.Replace("Printed:", ""));
                //r.Logo
                //Animal Details Subsection
                r.ARN           = d.GetElementbyId("cphWorkArea_lblARN").InnerText.Trim();
                r.Name          = d.GetElementbyId("cphWorkArea_lblName").InnerText.Trim();
                r.AnimalSpecies = d.GetElementbyId("cphWorkArea_lblSpecies").InnerText.Trim();
                string[] description = d.GetElementbyId("cphWorkArea_lblLine1").InnerText.Split(_comma);
                r.AnimalType    = description[0].Trim();
                r.AnimalSubType = description.Length >= 5 ? description[1].Trim() : "No Subtype Listed";
                r.Color         = description[description.Length - 3].Trim();
                r.Size          = description[description.Length - 2].Trim();
                try
                {
                    r.WeightInLbs =
                        double.Parse(Regex.Match(description[description.Length - 1].Trim(), @"\d+\.?\d*").Value);
                }
                catch (Exception)
                {
                    r.WeightInLbs = -1;
                }
                r.AnimalGender          = d.GetElementbyId("cphWorkArea_lblGender").InnerText.Trim();
                r.AgeRangeWhenCollected = ParseAgeRangeWhenCollected(d.GetElementbyId("cphWorkArea_lblAgeGroup").InnerText.Trim());

                var reportAgeAndSpayedElement = d.GetElementbyId("cphWorkArea_lblLine2");
                if (reportAgeAndSpayedElement.ChildNodes.Count > 2) //Normal Case
                {
                    r.AgeAtReportPrint = reportAgeAndSpayedElement.ChildNodes[0].InnerText.Trim();
                    r.Spayed           = d.GetElementbyId("cphWorkArea_lblLine2").ChildNodes[4].InnerText.Trim().ToLower() ==
                                         "yes";
                    r.DateOfBirth = DateTime.Parse(d.GetElementbyId("cphWorkArea_lblLine2").ChildNodes[2].InnerText.Trim());
                }
                else
                {
                    r.AgeAtReportPrint = "Unknown";
                    r.Spayed           = d.GetElementbyId("cphWorkArea_lblLine2").ChildNodes[1].InnerText.Trim().ToLower() ==
                                         "yes";
                    r.DateOfBirth = DateTime.MinValue;
                }

                //?
                r.Declawed = d.GetElementbyId("cphWorkArea_lblLine3").ChildNodes[1].InnerText.Trim().ToLower() != "none";
                r.Bitten   = d.GetElementbyId("cphWorkArea_lblLine4").ChildNodes[1].InnerText.Trim();
                var area   = d.GetElementbyId("cphWorkArea_dgLocation").InnerHtml;
                var split0 = area.Split(new[] { "APA!! Parvo-Dog" }, StringSplitOptions.None);
                var split1 = split0[2].Split(new[] { "<td>", "</td>" }, StringSplitOptions.RemoveEmptyEntries);
                r.IntakeDateTime = DateTime.Parse(split1[0]);

                r.OutcomeType = d.GetElementbyId("cphWorkArea_RepeaterOutcome_hlkOutcomeType_0").InnerText;
                r.DiedOfParvo = r.OutcomeType == "Died" &&
                                d.GetElementbyId("cphWorkArea_RepeaterOutcome_txOutcomeSubType_0").InnerText ==
                                "Parvo Virus";

                r.Adopted = r.OutcomeType == "Adoption";

                var timeInWardArea   = d.GetElementbyId("cphWorkArea_dgLocation");
                var timeInWardString = "";
                for (int i = 0; i < timeInWardArea.ChildNodes.Count; i++)
                {
                    if (timeInWardArea.ChildNodes[i].InnerText.Contains("APA!! Parvo-Dog"))
                    {
                        timeInWardString = timeInWardArea.ChildNodes[i - 1].ChildNodes[3].InnerText;
                        break;
                    }
                }

                r.ParvoICUDischargeDateTime = DateTime.Parse(timeInWardString);
                r.TimeInParvoICU            = r.ParvoICUDischargeDateTime.Subtract(r.IntakeDateTime);
            }
            catch (Exception)
            {
                errCount++;
                Console.WriteLine("Error A#=" + r.ANum + " this is error " + errCount);
                return(null);
            }

            return(r);
        }
Exemple #14
0
        private void MainBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Determinar en Que pagina Estoy.
            // Tomar Desicion // CASE
            // Darle a Pagina Anterior.
            if (cbGetCases.Checked)
            {
                int Activity = 0;

                var WPDoc        = new HtmlAgilityPack.HtmlDocument();
                var doc          = ((MainForm)Application.OpenForms[0]).MainBrowser.Document;
                var renderedHtml = doc.GetElementsByTagName("HTML")[0].OuterHtml;
                WPDoc.LoadHtml(renderedHtml);

                var SearchBtn    = doc.GetElementById("ctl00$cphBody$cmdSearch");
                var CancelBtn    = doc.GetElementById("ctl00$cphBody$cmdClear");
                var ViewElements = doc.GetElementById("cphBody_cmbPageSize");

                if (SearchBtn != null && CancelBtn != null)
                {
                    Activity = 1;
                }

                if (ViewElements != null)
                {
                    if (ViewElements.OuterHtml.IndexOf("selected=\"selected\" value=\"All\">") > 0)
                    {
                        Activity = 3;
                    }
                    else
                    {
                        Activity = 2;
                    }
                }

                if (renderedHtml.Contains("Modify your search criteria by selecting the Search Criteria tab"))
                {
                    Activity = 4;
                }

                switch (Activity)
                {
                //ctl00$cphBody$gvSearch$ctl09$txtParameter: 01 / 01 / 2013
                //ctl00$cphBody$gvSearch$ctl10$txtParameter: 02 / 01 / 2013
                //ctl00$cphBody$gvSearch$ctl11$cmbParameterPostBack: 101
                //ctl00$cphBody$gvSearch$ctl12$cmbParameterNoPostBack: 146
                //ctl00$cphBody$gvSearch$ctl13$cmbParameterNoPostBack: 96

                case 1:
                {
                    var BeginDate = doc.GetElementById("cphBody_gvSearch_txtParameter_7");
                    var EndDate   = doc.GetElementById("cphBody_gvSearch_txtParameter_8");
                    var CourtType = doc.GetElementById("cphBody_gvSearch_cmbParameterPostBack_9");
                    CourtType.SetAttribute("Value", "101");
                    var CaseType = doc.GetElementById("cphBody_gvSearch_cmbParameterNoPostBack_10");
                    Thread.Sleep(2000);
                    // var SearchDate = GetMeDate();
                    SelectNewDayRange();
                    BeginDate.SetAttribute("Value", StartDay.ToString("MM/dd/yyyy"));
                    EndDate.SetAttribute("Value", EndDay.ToString("MM/dd/yyyy"));

                    CaseType.SetAttribute("Value", "146");

                    SearchBtn.InvokeMember("Click");
                    logclick("Search");
                    break;
                }

                case 2:
                {
                    ViewElements.SetAttribute("Value", "All");
                    ViewElements.InvokeMember("onChange");
                    // MainBrowser.Refresh(WebBrowserRefreshOption.Completely);
                    logclick("Search");
                    break;
                }

                case 3:
                {
                    PalmCaseInfoClass CInfo = new PalmCaseInfoClass();
                    CInfo.County = County;
                    // Tomar Casos en el Dia;
                    var CasosDiaStr = doc.GetElementById("cphBody_lblRecordsReturned");
                    if (CasosDiaStr != null)
                    {
                        CInfo.NumberOfCases = Convert.ToInt32(CasosDiaStr.InnerText);
                        var wrkint = CInfo.NumberOfCases;
                        if (wrkint == 200)
                        {
                            StartDay.AddDays(AdicionarDias * -1);
                            StartDay.AddDays(-1);
                            EndDay = StartDay;
                            EndDay.AddDays(AdicionarDias);
                            AdicionarDias = AdicionarDias - 3;
                            MainBrowser.Navigate("https://applications.mypalmbeachclerk.com/eCaseView/search.aspx");
                            logclick("Main Page");
                            break;
                        }
                        else
                        {
                            var casosxdia = wrkint / AdicionarDias;
                            var amplitud  = casosxdia * 3;
                            var cabe      = (200 - amplitud);
                            if (wrkint > cabe)
                            {
                                AdicionarDias++;
                            }
                        }
                    }

                    var TablaCasos   = WPDoc.GetElementbyId("cphBody_gvResults");
                    var CasesInfoRow = TablaCasos.Descendants("tr").ToList();
                    foreach (var Crow in CasesInfoRow)
                    {
                        if (!Crow.InnerText.Contains("Arrest Date"))
                        {
                            var      CasesInfoColumn = Crow.Descendants("td").ToList();
                            int      Num             = 0;
                            string[] AColInfo        = new string[7];
                            foreach (var Ccol in CasesInfoColumn)
                            {
                                AColInfo[Num] = Ccol.InnerText;
                                Num++;
                            }
                            pbICases WC = new pbICases();
                            WC.CaseNumber = AColInfo[0];
                            WC.Courts     = AColInfo[1];
                            WC.CaseType   = AColInfo[2];
                            try
                            {
                                WC.FileDate = Convert.ToDateTime(AColInfo[4]);
                            }
                            catch
                            {
                                WC.FileDate = Convert.ToDateTime("2008-01-01");
                            }

                            if (!string.IsNullOrEmpty(AColInfo[5]))
                            {
                                if (AColInfo[5].IndexOf(" V ") > 0)
                                {
                                    WC.PrimaryParty   = AColInfo[5].Substring(0, AColInfo[5].IndexOf(" V "));
                                    WC.SecondaryParty = AColInfo[5].Substring(AColInfo[5].IndexOf(" V ") + 3);
                                }
                                else
                                {
                                    WC.PrimaryParty   = AColInfo[5];
                                    WC.SecondaryParty = AColInfo[5];
                                }
                            }

                            WC.CaseStatus = AColInfo[6];

                            CInfo.ListaCasos.Add(WC);
                            CInfo.FileDate = WC.FileDate;
                        }
                    }

                    // Salvar en Async y Threadding.
                    SaveCases(CInfo);
                    // Slow the speed
                    Thread.Sleep(24000);


                    // cphBody_lbSearch  // Volver a la pantalla de Busqueda
                    //var SearchLink = doc.GetElementById("ctl00$cphBody$cmdSearch");
                    //SearchBtn.InvokeMember("Click");
                    MainBrowser.Navigate("https://applications.mypalmbeachclerk.com/eCaseView/search.aspx");
                    logclick("Main Page");
                    break;
                }

                case 4:
                {
                    MainBrowser.Navigate("https://applications.mypalmbeachclerk.com/eCaseView/search.aspx");
                    logclick("Main Page");
                    break;
                }
                }
            }
        }
Exemple #15
0
        public static void GetWindowsSearchResults(string searchEntry)
        {
            string           scope            = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "/root";
            string           searchHTML       = "<html><head><meta charset=\"UTF-8\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"root\\includes\\css.css\"></head><body><div class=\"main\">";
            Regex            regex            = new Regex(@"([a-fA-F0-9]{64})");
            string           connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
            HashSet <string> imgExtensions    = new HashSet <string>(StringComparer.OrdinalIgnoreCase)
            {
                ".jpg", ".jpeg", ".jpe", ".gif", ".png", ".tiff", ".tif", ".svg", ".svgz", ".xbm", ".bmp", ".ico"
            };

            OleDbConnection connection = new OleDbConnection(connectionString);
            string          query      = @"SELECT TOP 1000 System.ItemFolderPathDisplay FROM SystemIndex WHERE scope ='file:" + scope + "' and FREETEXT('" + searchEntry.Replace("'", "").Replace("\"", "").Replace("\\", "") + "')";
            OleDbCommand    command    = new OleDbCommand(query, connection);

            connection.Open();
            HashSet <string> result = new HashSet <string>();
            OleDbDataReader  reader = command.ExecuteReader();

            while (reader.Read())
            {
                string searchString = reader.GetString(0);
                Match  match        = regex.Match(searchString);
                if (match.Success)
                {
                    result.Add(searchString);
                }
            }
            connection.Close();
            if (result.Count > 0)
            {
                foreach (string folderPath in result)
                {
                    var signature  = "ANONYMOUS";
                    var img        = "";
                    var msg        = "";
                    var date       = "";
                    var blockchain = "";


                    Match  match = regex.Match(folderPath);
                    string s     = match.Value;

                    try
                    {
                        var doc = new HtmlAgilityPack.HtmlDocument();
                        doc.Load(folderPath + "\\index.htm");

                        try
                        {
                            img        = doc.GetElementbyId("img0").InnerText;
                            searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan='5'><a href='root/" + s + "/index.htm'><img src='root/" + s + "/" + img + "' Width = '80px'/></a></th><th></th></tr>";
                        }
                        catch { searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan='5'></th><th></th></tr>"; }
                        try { signature = doc.GetElementbyId("signature").InnerText; }
                        catch { }
                        try { blockchain = doc.GetElementbyId("blockchain").InnerText; }
                        catch { }
                        searchHTML = searchHTML + "<tr><td>" + blockchain + " - " + signature + "</td></tr>";
                        try { date = doc.GetElementbyId("block-date").InnerText; }
                        catch { }
                        try { msg = doc.GetElementbyId("msg1").InnerText; }
                        catch { }
                        searchHTML = searchHTML + "<tr><td><a href='root/" + s + "/index.htm'>" + date + " - " + msg.PadRight(50).Substring(0, 49) + "...</a></td></tr>";

                        if (msg.Length > 500)
                        {
                            searchHTML = searchHTML + "<tr><td>" + msg.Substring(0, 499) + "</td></tr>";
                        }
                        else
                        {
                            searchHTML = searchHTML + "<tr><td>" + msg + "</td></tr>";
                        }


                        searchHTML = searchHTML + "<tr><td><a href='root/" + s + "/index.htm'>" + s + "</a></td></tr></table></div></div>";
                    }
                    catch { }
                }

                searchHTML = searchHTML + "</div></body></html>";
            }
            File.WriteAllText("search.htm", searchHTML);
        }
Exemple #16
0
        private string GetDescription(HtmlAgilityPack.HtmlDocument Html)
        {
            var description = Html.GetElementbyId("productDescription");

            if (description == null)
            {
                try
                {
                    description = Html.GetElementbyId("pd-available").NextSibling.NextSibling;

                    string javatoparse = description.InnerText;

                    var frame = GetJavaIFrame(javatoparse);

                    var htmlcode = WebUtility.UrlDecode(frame);

                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(htmlcode);

                    description = doc.GetElementbyId("productDescription");

                }
                catch (Exception)
                {

                }

            }

            var descriptiontext = "";

            if (description != null)
            {
                descriptiontext = description.InnerText;
            }

            return descriptiontext;
        }
Exemple #17
0
        public static void GetLatestArchives()
        {
            string scope       = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\root";
            string monitorHTML = "<html><head><meta charset=\"UTF-8\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"root\\includes\\css.css\"></head><body><div class=\"main\">";

            Regex            regex            = new Regex(@"([a-fA-F0-9]{64})");
            string           connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
            HashSet <string> imgExtensions    = new HashSet <string>(StringComparer.OrdinalIgnoreCase)
            {
                ".jpg", ".jpeg", ".jpe", ".gif", ".png", ".tiff", ".tif", ".svg", ".svgz", ".xbm", ".bmp", ".ico"
            };

            OleDbConnection connection = new OleDbConnection(connectionString);

            string       query   = @"SELECT TOP 50 System.ItemFolderPathDisplay FROM SystemIndex WHERE scope ='file:" + scope + "' AND System.FileName = 'index.htm' ORDER BY System.DateModified DESC";
            OleDbCommand command = new OleDbCommand(query, connection);

            connection.Open();
            HashSet <string> result = new HashSet <string>();
            OleDbDataReader  reader = command.ExecuteReader();

            while (reader.Read())
            {
                string searchString = reader.GetString(0);
                Match  match        = regex.Match(searchString);
                if (match.Success)
                {
                    result.Add(match.Value);
                }
            }
            connection.Close();
            if (result.Count > 0)
            {
                var uniqueResults = result.Distinct();
                foreach (string s in uniqueResults)
                {
                    var signature = "";
                    var img       = "";

                    var msg        = "";
                    var date       = "";
                    var blockchain = "";
                    var profiles   = "";
                    var doc        = new HtmlAgilityPack.HtmlDocument();
                    try
                    {
                        doc.Load(scope + "\\" + s + "\\index.htm");
                    }
                    catch { break; }

                    try { profiles = doc.GetElementbyId("profiles").InnerHtml.Replace(@"../", @"root/"); }
                    catch { }

                    try
                    {
                        img         = doc.GetElementbyId("img0").InnerText;
                        monitorHTML = monitorHTML + "<div class=\"item\"><div class=\"content\">" + profiles + "<table><tr><th rowspan=\"5\"><a href=\"" + s + "/index.htm\"><img src=\"root/" + s + "/" + img + "\"/></a></th><th></th></tr>";
                    }
                    catch { monitorHTML = monitorHTML + "<div class=\"item\"><div class=\"content\">" + profiles + "<table><tr><th rowspan=\"5\"></th><th></th></tr>"; }

                    try { signature = doc.GetElementbyId("signature").InnerText; }
                    catch { }
                    try { blockchain = doc.GetElementbyId("blockchain").InnerText; }
                    catch { }
                    monitorHTML = monitorHTML + "<tr><td>" + blockchain + " - " + signature + "</td></tr>";
                    try { date = doc.GetElementbyId("block-date").InnerText; }
                    catch { }
                    try { msg = doc.GetElementbyId("msg1").InnerText; }
                    catch { }
                    monitorHTML = monitorHTML + "<tr><td><a href=\"root/" + s + "/index.htm\">" + msg.PadRight(50).Substring(0, 49) + "</a></td></tr>";

                    if (msg.Length > 500)
                    {
                        monitorHTML = monitorHTML + "<tr><td>" + date + " : " + msg.Substring(0, 499) + "...</td></tr>";
                    }
                    else
                    {
                        monitorHTML = monitorHTML + "<tr><td>" + date + " : " + msg + "</td></tr>";
                    }


                    monitorHTML = monitorHTML + "<tr><td><a href=\"root/" + s + "/index.htm\"><font size=\"1\">" + s + "</font></a></td></tr></table></div></div>";
                }
                monitorHTML = monitorHTML + "</div></body></html>";
            }
            else
            {
                monitorHTML = monitorHTML + "<div class=\"item\"><div class=\"content\">Nothing found</div></div></div></body></html>";
            }


            File.WriteAllText("monitor.htm", monitorHTML);
        }
Exemple #18
0
        private int FollowByWeb()
        {
            // 沒有資料就離開
            if (string.IsNullOrEmpty(this.DownHome.Data)) return 0;

            int result = 0;
            BasicInfo gameInfo = null;
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            //string xPath = "/html[1]/body[1]/div[1]/div[2]/div[3]/div[8]/table[1]";
            // 載入資料
            document.LoadHtml(this.DownHome.Data);
            // 資料位置
            HtmlAgilityPack.HtmlNode contentNode = document.GetElementbyId("contents");
            if (contentNode == null) { return 0; }

            HtmlAgilityPack.HtmlNode nodeGames = contentNode.SelectSingleNode("//div[contains(@class,'NpbSchedule')]/table");

            // 判斷資料
            if (nodeGames != null && nodeGames.ChildNodes != null)
            {
                DateTime gameDate = this.GameDate;
                DateTime gameTime = this.GameDate;
                string gameDateStr = null;

                // 資料
                foreach (HtmlAgilityPack.HtmlNode game in nodeGames.ChildNodes)
                {
                    // 不是資料就往下處理
                    if (game.Name != "tr") continue;

                    string webID = null;
                    string webUrl = null;
                    string webStatus = null;
                    int timeIndex = 8;
                    int idIndex = 6;
                    int awayIndex = 0;
                    int homeIndex = 4;

                    #region 取得日期
                    if (game.ChildNodes.Count == 15)
                    {
                        gameDateStr = game.ChildNodes[1].InnerText.Replace("月", "/").Replace("日", "").Trim();
                        // 截斷日期
                        if (gameDateStr.IndexOf("(") != -1)
                            gameDateStr = DateTime.Now.ToString("yyyy") + "/" + gameDateStr.Substring(0, gameDateStr.IndexOf("(")).Trim();
                        // 判斷日期,失敗就往下處理
                        if (!DateTime.TryParse(gameDateStr, out gameDate))
                        {
                            gameDateStr = null;
                            continue;
                        }
                        timeIndex = 11;
                        idIndex = 9;
                        awayIndex = 3;
                        homeIndex = 7;
                    }
                    // 沒有日期就往下處理
                    if (string.IsNullOrEmpty(gameDateStr)) continue;
                    // 錯誤的陣列就往下處理
                    if (timeIndex >= game.ChildNodes.Count) continue;
                    #endregion
                    #region 取得時間
                    // 判斷日期,錯誤就離開
                    string timeStr = game.ChildNodes[timeIndex].InnerText;
                    // 取出資料
                    timeStr = timeStr.Substring(0, timeStr.IndexOf(" "));
                    if (!DateTime.TryParse(gameDate.ToString("yyyy/MM/dd") + " " + timeStr, out gameTime)) continue;
                    // 判斷是否為今天,不是今天就往下處理
                    if (this.GameDate.Date != gameTime.Date)
                    {
                        gameDateStr = null;
                        continue;
                    }
                    #endregion
                    #region 跟盤 ID
                    webID = game.ChildNodes[idIndex].ChildNodes[0].GetAttributeValue("href", "");
                    webStatus = game.ChildNodes[idIndex].ChildNodes[0].InnerText;
                    Uri uri = null;
                    // 錯誤處理
                    try
                    {
                        uri = new Uri(@"http://www.a.com" + webID);
                        // 判斷是否有資料
                        if (uri.Segments.Length == 4)
                        {
                            webID = uri.Segments[3].Replace("/", "");
                            if (webStatus == "中止")
                            {
                                webUrl = string.Format(sWebUrl5, webID);
                            }
                            else
                            {
                                webUrl = string.Format(sWebUrl6, webID);
                            }
                        }
                    }
                    catch { webID = null; } // 錯誤,清除跟盤 ID
                    // 沒有跟盤 ID 就往下處理
                    if (webID == null || string.IsNullOrEmpty(webID.Trim()))
                    {
                        gameDateStr = null;
                        continue;
                    }
                    #endregion

                    // 建立比賽資料
                    gameInfo = null;
                    gameInfo = new BasicInfo(this.AllianceID, this.GameType, gameTime, webID);
                    gameInfo.IsBall = true; // 賽程的主客隊與資料是相反的
                    gameInfo.Away = game.ChildNodes[homeIndex].InnerText;
                    gameInfo.AwayPoint = "";
                    gameInfo.Home = game.ChildNodes[awayIndex].InnerText;
                    gameInfo.HomePoint = "";
                    gameInfo.GameStates = (webStatus == "中止") ? ("P") : ("X");

                    #region 下載比賽資料,比賽時間 10 分鐘前就開始處理
                    if (!this.DownReal.ContainsKey(webID) &&
                        GetUtcKr(DateTime.Now) >= gameTime.AddMinutes(-10))
                    {
                        this.DownReal[webID] = new BasicDownload(this.Sport, webUrl, webID);
                        this.DownReal[webID].DownloadString();
                    }
                    #endregion
                    #region 處理比賽資料
                    if (this.DownReal.ContainsKey(webID) &&
                        !string.IsNullOrEmpty(this.DownReal[webID].Data))
                    {
                        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                        HtmlAgilityPack.HtmlNode node = null;

                        // 讀取資料
                        doc.LoadHtml(this.DownReal[webID].Data);

                        // 判斷是中止
                        if (gameInfo.GameStates == "P")
                        {
                            string findxpath = FindXPath(doc.DocumentNode, "yjSNLiveBattlereview");
                            if (!string.IsNullOrEmpty(findxpath))
                            {
                                node = doc.DocumentNode.SelectSingleNode(findxpath);
                                if (node != null && node.ChildNodes.Count > 0)
                                {
                                    // 原因
                                    gameInfo.TrackerText = node.ChildNodes[node.ChildNodes.Count - 2].InnerText;
                                }
                            }
                        }
                        else
                        {
                            #region 分數
                            node = doc.DocumentNode.SelectSingleNode(FindXPath(doc.DocumentNode, "scoreboard"));
                            if (node != null && node.ChildNodes.Count >= 1)
                            {
                                // Away
                                foreach (HtmlAgilityPack.HtmlNode data in node.ChildNodes[1].ChildNodes[1].ChildNodes[2].ChildNodes)
                                {
                                    // 不是資料就往下處理
                                    if (data.Name != "td")
                                        continue;
                                    // 分數
                                    gameInfo.AwayBoard.Add(data.InnerText.Replace("&nbsp;", ""));
                                }
                                gameInfo.AwayPoint = gameInfo.AwayBoard[gameInfo.AwayBoard.Count - 3];
                                gameInfo.AwayH = gameInfo.AwayBoard[gameInfo.AwayBoard.Count - 2];
                                gameInfo.AwayE = gameInfo.AwayBoard[gameInfo.AwayBoard.Count - 1];
                                gameInfo.AwayBoard.RemoveAt(gameInfo.AwayBoard.Count - 1);
                                gameInfo.AwayBoard.RemoveAt(gameInfo.AwayBoard.Count - 1);
                                gameInfo.AwayBoard.RemoveAt(gameInfo.AwayBoard.Count - 1);
                                // Home
                                foreach (HtmlAgilityPack.HtmlNode data in node.ChildNodes[1].ChildNodes[1].ChildNodes[4].ChildNodes)
                                {
                                    // 不是資料就往下處理
                                    if (data.Name != "td")
                                        continue;
                                    gameInfo.HomeBoard.Add(data.InnerText.Replace("&nbsp;", ""));
                                }
                                gameInfo.HomePoint = gameInfo.HomeBoard[gameInfo.HomeBoard.Count - 3];
                                gameInfo.HomeH = gameInfo.HomeBoard[gameInfo.HomeBoard.Count - 2];
                                gameInfo.HomeE = gameInfo.HomeBoard[gameInfo.HomeBoard.Count - 1];
                                gameInfo.HomeBoard.RemoveAt(gameInfo.HomeBoard.Count - 1);
                                gameInfo.HomeBoard.RemoveAt(gameInfo.HomeBoard.Count - 1);
                                gameInfo.HomeBoard.RemoveAt(gameInfo.HomeBoard.Count - 1);
                            }
                            // 移除無用的分數
                            if (gameInfo.Quarter > 0)
                            {
                                int index = gameInfo.AwayBoard.Count - 1;
                                while (index >= 0)
                                {
                                    if (gameInfo.AwayBoard[index] == "-")
                                        gameInfo.AwayBoard[index] = "0";

                                    if (gameInfo.HomeBoard[index] == "-")
                                        gameInfo.HomeBoard[index] = "0";

                                    if (string.IsNullOrEmpty(gameInfo.AwayBoard[index]))
                                        gameInfo.AwayBoard.RemoveAt(index);
                                    if (string.IsNullOrEmpty(gameInfo.HomeBoard[index]))
                                        gameInfo.HomeBoard.RemoveAt(index);
                                    index--;
                                }
                                gameInfo.GameStates = "S";
                            }
                            #endregion
                            #region BSO
                            node = doc.DocumentNode.SelectSingleNode(FindXPath(doc.DocumentNode, "sbo"));
                            if (node != null && node.ChildNodes.Count >= 1)
                            {
                                string txt = null;
                                int bStart = 0;
                                int bEnd = 0;
                                // B
                                txt = node.ChildNodes[3].ChildNodes[3].ChildNodes[1].InnerHtml.Replace("\n", "");
                                bStart = txt.IndexOf("<b>");
                                bEnd = txt.IndexOf("</b>");
                                if (bStart != -1 && bEnd != -1)
                                {
                                    gameInfo.BallB = txt.Substring(bStart + 3, bEnd - bStart - 3).Length;
                                    if (gameInfo.BallB > 3)
                                        gameInfo.BallB = 0;
                                }
                                // S
                                txt = node.ChildNodes[3].ChildNodes[3].ChildNodes[3].InnerHtml.Replace("\n", "");
                                bStart = txt.IndexOf("<b>");
                                bEnd = txt.IndexOf("</b>");
                                if (bStart != -1 && bEnd != -1)
                                {
                                    gameInfo.BallS = txt.Substring(bStart + 3, bEnd - bStart - 3).Length;
                                    if (gameInfo.BallS > 2)
                                        gameInfo.BallS = 0;
                                }
                                // O
                                txt = node.ChildNodes[3].ChildNodes[3].ChildNodes[5].InnerHtml.Replace("\n", "");
                                bStart = txt.IndexOf("<b>");
                                bEnd = txt.IndexOf("</b>");
                                if (bStart != -1 && bEnd != -1)
                                {
                                    gameInfo.BallO = txt.Substring(bStart + 3, bEnd - bStart - 3).Length;
                                    if (gameInfo.BallO > 2)
                                    {
                                        gameInfo.BallB = 0;
                                        gameInfo.BallS = 0;
                                        gameInfo.BallO = 0;
                                    }
                                }
                            }
                            #endregion
                            #region Bases
                            node = doc.DocumentNode.SelectSingleNode(FindXPath(doc.DocumentNode, "base"));
                            if (node != null && node.ChildNodes.Count >= 1)
                            {
                                if (!string.IsNullOrEmpty(FindXPath(doc.DocumentNode, "base1")))
                                {
                                    gameInfo.Bases += 1;
                                }
                                if (!string.IsNullOrEmpty(FindXPath(doc.DocumentNode, "base2")))
                                {
                                    gameInfo.Bases += 2;
                                }
                                if (!string.IsNullOrEmpty(FindXPath(doc.DocumentNode, "base3")))
                                {
                                    gameInfo.Bases += 4;
                                }
                            }
                            #endregion
                            #region 狀態
                            node = doc.DocumentNode.SelectSingleNode(FindXPath(doc.DocumentNode, "livenavi"));
                            if (node != null)
                            {
                                if (node.InnerText.IndexOf("試合前") != -1)
                                {
                                    gameInfo.GameStates = "X";
                                    gameInfo.BallB = 0;
                                    gameInfo.BallS = 0;
                                    gameInfo.BallO = 0;
                                    gameInfo.Bases = 0;
                                    gameInfo.AwayPoint = "";
                                    gameInfo.AwayBoard.Clear();
                                    gameInfo.AwayH = null;
                                    gameInfo.AwayE = null;
                                    gameInfo.HomePoint = "";
                                    gameInfo.HomeBoard.Clear();
                                    gameInfo.HomeH = null;
                                    gameInfo.HomeE = null;
                                }
                                if (node.InnerText.IndexOf("試合終了") != -1)
                                {
                                    gameInfo.GameStates = "E";
                                    gameInfo.BallB = 0;
                                    gameInfo.BallS = 0;
                                    gameInfo.BallO = 0;
                                    gameInfo.Bases = 0;
                                }
                            }
                            // 比賽結束
                            node = doc.DocumentNode.SelectSingleNode(FindXPath(doc.DocumentNode, "afterdata"));
                            if (node != null && !string.IsNullOrEmpty(node.InnerText))
                            {
                                gameInfo.GameStates = "E";
                                gameInfo.BallB = 0;
                                gameInfo.BallS = 0;
                                gameInfo.BallO = 0;
                                gameInfo.Bases = 0;
                            }
                            #endregion
                        }
                    #endregion
                    }

                    if (base.CheckGame(gameInfo))//檢查比分是否合法
                    {
                        this.GameData[gameInfo.WebID] = gameInfo;// 加入
                        result++;// 累計
                    }
                }
            }
            // 傳回
            return result;
        }
Exemple #19
0
        /// <summary>
        /// 转换数据
        /// </summary>
        /// <returns></returns>
        public override TygModel.书名表 Convert()
        {
            DateTime updateTime = DateTime.Parse("2000-01-01");


            //看看分类表里有没有这个分类如果没有则进行分类添加


            //分类表
            var classItems = Skybot.Cache.RecordsCacheManager.Instance.Tygdb.分类表.Where(p => p.分类名称.Trim() == 类别.Trim());

            //当前分类
            TygModel.分类表 classItem = null;
            //如果分类不存在
            if (classItems.Count() == 0)
            {
                try
                {
                    classItem = new TygModel.分类表()
                    {
                        分类标识 = 类别.Trim(),
                        分类名称 = 类别.Trim(),
                        分类说明 = 类别.Trim(),
                        备注   = "来自 86zw.com",
                        通用分类 = 类别.Trim()
                    };
                    Skybot.Cache.RecordsCacheManager.Instance.Tygdb.AddTo分类表(classItem);
                    //保存分类
                    Skybot.Cache.RecordsCacheManager.Instance.Tygdb.SaveChanges();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message + (ex.StackTrace != null ? ex.StackTrace : ""));
                }
            }
            else
            {
                classItem = classItems.FirstOrDefault();
            }



            TygModel.书名表 book = new TygModel.书名表()
            {
                分类表      = classItem,
                分类标识     = classItem.分类标识,
                分类表ID    = classItem.ID,
                GUID     = Guid.NewGuid(),
                采集用的URL1 = 小说目录URL,
                采集用的URL2 = 小说简介URL,
                创建时间     = DateTime.Now,
                最新章节     = 最新章节,
                作者名称     = 作者,
                说明       = "",
                书名       = 小说名称.Replace("》", "").Replace("《", ""),
                最后更新时间   = updateTime,
                完本       = 状态.Trim() == "完结" ? true : false,
                配图       = "/images/noimg.gif",
            };
            //修改配图或者说明

            if (小说简介URL != null)
            {
                System.Diagnostics.Debug.WriteLine("获取配图:" + 小说简介URL);
                //初始化一个DOM
                HtmlAgilityPack.HtmlDocument dom = new HtmlAgilityPack.HtmlDocument();
                dom.LoadHtml(小说简介URL.GetWeb());

                //信息说明字段
                HtmlAgilityPack.HtmlNode DesriptionContent = dom.GetElementbyId("CrbtrTop");
                //采集时间的xpath表达式 2011-11-18
                HtmlAgilityPack.HtmlNode node = dom.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[2]/div[2]/div[3]/div[2]/div[1]/ul[1]/li[6]");
                if (node != null)
                {
                    if (DateTime.TryParse(node.InnerText, out updateTime))
                    {
                        book.最后更新时间 = updateTime;
                    }
                }
                //说明
                HtmlAgilityPack.HtmlNode summary = dom.GetElementbyId("CrbsSum");

                if (summary != null)
                {
                    book.说明 = summary.InnerHtml.Length > 4000 ?new Tong.TongUse().ForMatText(summary.InnerText, 0, 3800) : summary.InnerHtml;
                }

                //图片
                HtmlAgilityPack.HtmlNode listContent = dom.GetElementbyId("CrbtlBookImg");

                if (listContent != null)
                {
                    //可能的原素
                    List <PossiblyResultElement> possiblyResultElements = new List <PossiblyResultElement>();


                    //开始循环子原素
                    SingleListPageAnalyse.AnalyseMaxATagNearest(listContent, possiblyResultElements, 0, new PossiblyResultElement()
                    {
                        ParentPossiblyResult = null,
                        CurrnetHtmlElement   = listContent,
                        LayerIndex           = -1,
                        ContainTagNum        = 0
                    });
                    //计算当前所有HTML原素中的img原素
                    var PageimgElements = from img in possiblyResultElements
                                          where img.CurrnetHtmlElement.Name == "img"
                                          select img;

                    try
                    {
                        if (PageimgElements.Count() > 0)
                        {
                            string imgurl = PageimgElements.First().CurrnetHtmlElement.Attributes["src"].Value;
                            if (!imgurl.ToLower().Contains("images/noimg.gif"))
                            {
                                try
                                {
                                    imgurl = new Uri(new Uri(小说简介URL), imgurl).ToString();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine(DateTime.Now + ex.Message + "|||||" + ex.StackTrace);
                                    imgurl = "/images/noimg.gif";
                                }
                            }

                            System.Diagnostics.Debug.WriteLine("获取配图:" + 小说简介URL + "  完成" + imgurl);

                            book.配图 = imgurl.Trim().Contains("/images/noimg.gif") ? "/images/noimg.gif" : imgurl;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now + ex.Message + "|||||" + ex.StackTrace);
                    }
                }
            }



            return(book);
        }
Exemple #20
0
        public override int Follow()
        {
            // 沒有資料就離開
            if (string.IsNullOrEmpty(this.DownHome.Data)) return 0;

            int result = 0;
            BasicInfo gameInfo = null;
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

            // 載入資料
            document.LoadHtml(this.DownHome.Data);
            //document.Load(@"C:\Users\Administrator\Desktop\ahl.txt");//本機資料測試
            // 資料位置
            //string xPath = "/html[1]/body[1]/div[1]/div[3]/div[1]/div[1]/div[2]/div[3]";
            //HtmlAgilityPack.HtmlNode nodeGames = document.DocumentNode.SelectSingleNode(xPath);

            HtmlAgilityPack.HtmlNode nodeGames = document.GetElementbyId("AHLscoreBox");
            // 判斷資料
            if (nodeGames != null && nodeGames.ChildNodes != null)
            {
                DateTime gameDate = this.GameDate;
                DateTime gameTime = this.GameDate;
                //string gameDateStr = null;
                int gameQuarter = 0;
                // 資料
                foreach (HtmlAgilityPack.HtmlNode game in nodeGames.ChildNodes)
                {

                    string webID = null;
                    #region 跟盤 ID
                    HtmlAgilityPack.HtmlNodeCollection GameDateInfo = game.SelectNodes("div[@class='final-hd-link']/a");
                    if (GameDateInfo != null && GameDateInfo.Count > 0)
                    {

                        var href = GameDateInfo[0].GetAttributeValue("href", "");
                        if (string.IsNullOrEmpty(href))//取到空值
                            continue;

                        try
                        {
                            if (!href.Contains("http"))
                                href = "http://" + href;

                            Uri uri = new Uri(href);
                            // 判斷是否有資料
                            if (uri.Query != null && !string.IsNullOrEmpty(uri.Query))
                            {
                                HttpRequest req = new HttpRequest("", uri.AbsoluteUri, uri.Query.Substring(1));
                                // 判斷資料
                                if (req["game_id"] != null && !string.IsNullOrEmpty(req["game_id"].Trim()))//已開賽
                                {
                                    webID = req["game_id"];
                                }
                                else if (req["file_path"] != null && !string.IsNullOrEmpty(req["file_path"].Trim()))//未開賽
                                {
                                    webID = req["file_path"];
                                    if (webID.IndexOf("/") != -1)
                                    {
                                        webID = webID.Substring(webID.IndexOf("/") + 1).Trim();
                                    }
                                    if (webID.IndexOf("-") != -1)
                                    {
                                        webID = webID.Substring(0, webID.IndexOf("-")).Trim();
                                    }
                                }
                            }
                        }
                        catch { }

                    }
                    else
                        continue;

                    // 沒有跟盤 ID 就往下處理
                    if (webID == null || string.IsNullOrEmpty(webID.Trim())) continue;
                    #endregion

                    // 建立比賽資料,時間以台灣為主
                    DateTime GameTime;
                    if (diffTime > 0)
                        GameTime = this.GameDate.AddHours(diffTime);
                    else
                    {
                        TimeSpan ts = DateTime.Now - this.GameDate;
                        GameTime = this.GameDate.AddHours(ts.TotalHours);
                    }

                    gameInfo = null;
                    gameInfo = new BasicInfo(this.AllianceID, this.GameType, GameTime, webID);
                    gameQuarter = 0;

                    #region 處理比賽資料
                    #region 狀態
                    gameInfo.Status = game.ChildNodes[1].InnerText.ToLower().Trim();
                    gameInfo.Status = gameInfo.Status.ToLower().Trim();
                    // 判斷目前局數
                    if (gameInfo.Status.IndexOf("1st") != -1) gameQuarter = 1;
                    if (gameInfo.Status.IndexOf("2nd") != -1) gameQuarter = 2;
                    if (gameInfo.Status.IndexOf("3rd") != -1) gameQuarter = 3;
                    if (gameInfo.Status.IndexOf("ot") != -1) gameQuarter = 4;
                    // 判斷
                    if (gameInfo.Status.IndexOf("final") != -1)
                    {
                        gameInfo.GameStates = "E";
                        gameInfo.Status = "結束";
                        gameQuarter = 10;
                    }
                    else if (gameQuarter > 0) // 有局數才有比賽
                    {
                        // 取代文字
                        gameInfo.GameStates = "S";
                        // 取代文字
                        gameInfo.Status = gameInfo.Status.Replace("half", "");
                        gameInfo.Status = gameInfo.Status.Replace("halftime", "");
                        gameInfo.Status = gameInfo.Status.Replace("qtr", "");
                        gameInfo.Status = gameInfo.Status.Replace("1st", "");
                        gameInfo.Status = gameInfo.Status.Replace("2nd", "");
                        gameInfo.Status = gameInfo.Status.Replace("3rd", "");
                        gameInfo.Status = gameInfo.Status.Replace("4th", "");
                        gameInfo.Status = gameInfo.Status.Replace("ot", "");
                        gameInfo.Status = gameInfo.Status.Replace("2ot", "");
                        gameInfo.Status = gameInfo.Status.Trim();
                        if (gameInfo.Status == "00:00")
                        {
                            gameInfo.Status = "結束";
                        }
                    }
                    #endregion
                    HtmlAgilityPack.HtmlNode info = null;
                    // 判斷資料格式
                    if (game.ChildNodes[5].ChildNodes.Count == 5)
                    {
                        #region 比賽未開始,只有隊伍名稱
                        // Away
                        info = game.ChildNodes[5].ChildNodes[1];
                        gameInfo.Away = info.ChildNodes[1].InnerText;
                        // Home
                        info = game.ChildNodes[5].ChildNodes[3];
                        gameInfo.Home = info.ChildNodes[1].InnerText;
                        #endregion
                    }
                    else
                    {
                        #region Away
                        info = game.ChildNodes[5].ChildNodes[3];
                        gameInfo.Away = info.ChildNodes[1].InnerText;
                        gameInfo.AwayPoint = info.ChildNodes[info.ChildNodes.Count - 10].InnerText;
                        // 分數
                        for (int i = 3; i < info.ChildNodes.Count - 10; i += 2)
                        {
                            if (info.ChildNodes[i].InnerText != null && !string.IsNullOrEmpty(info.ChildNodes[i].InnerText.Trim()) &&
                                gameInfo.AwayBoard.Count < gameQuarter)
                            {
                                gameInfo.AwayBoard.Add(info.ChildNodes[i].InnerText.Trim());
                            }
                        }
                        #endregion
                        #region Home
                        info = game.ChildNodes[5].ChildNodes[5];
                        gameInfo.Home = info.ChildNodes[1].InnerText;
                        gameInfo.HomePoint = info.ChildNodes[info.ChildNodes.Count - 8].InnerText;
                        // 分數
                        for (int i = 3; i < info.ChildNodes.Count - 8; i += 2)
                        {
                            if (info.ChildNodes[i].InnerText != null && !string.IsNullOrEmpty(info.ChildNodes[i].InnerText.Trim()) &&
                                gameInfo.HomeBoard.Count < gameQuarter)
                            {
                                gameInfo.HomeBoard.Add(info.ChildNodes[i].InnerText.Trim());
                            }
                        }
                        #endregion
                    }
                    #region 處理隊伍名稱
                    Dictionary<string, string> webName = this.GetWebName();
                    // Away
                    gameInfo.Away = gameInfo.Away.Replace("\n", "");
                    gameInfo.Away = gameInfo.Away.Replace("\t", "");
                    gameInfo.Away = gameInfo.Away.Trim();
                    // 刪除無用資料
                    if (gameInfo.Away.IndexOf("(") != -1)
                    {
                        gameInfo.Away = gameInfo.Away.Substring(0, gameInfo.Away.IndexOf("(")).Trim();
                    }
                    // 變更名稱
                    if (webName.ContainsKey(gameInfo.Away))
                    {
                        gameInfo.Away = webName[gameInfo.Away];
                    }
                    // Home
                    gameInfo.Home = info.ChildNodes[1].InnerText;
                    gameInfo.Home = gameInfo.Home.Replace("\n", "");
                    gameInfo.Home = gameInfo.Home.Replace("\t", "");
                    gameInfo.Home = gameInfo.Home.Trim();
                    // 刪除無用資料
                    if (gameInfo.Home.IndexOf("(") != -1)
                    {
                        gameInfo.Home = gameInfo.Home.Substring(0, gameInfo.Home.IndexOf("(")).Trim();
                    }
                    // 變更名稱
                    if (webName.ContainsKey(gameInfo.Home))
                    {
                        gameInfo.Home = webName[gameInfo.Home];
                    }
                    #endregion
                    #endregion

                    // 加入
                    this.GameData[gameInfo.WebID] = gameInfo;
                    // 累計
                    result++;
                }
            }
            // 傳回
            return result;
        }
Exemple #21
0
        public static byte[] GeneratePDFWithHeaderFooter(string HtmlString, string headerHtmlId, string footerHtmlId)
        {
            string pdfConverterLicenseKey = "fvDg8eDx4+jx6P/h8eLg/+Dj/+jo6Og=";

            byte[] pdfBytes = null;

            PdfConverter pdfConverter = new PdfConverter();

            pdfConverter.LicenseKey = pdfConverterLicenseKey;
            pdfConverter.PdfDocumentOptions.EmbedFonts   = false;
            pdfConverter.PdfDocumentOptions.TopMargin    = 10;
            pdfConverter.PdfDocumentOptions.RightMargin  = 10;
            pdfConverter.PdfDocumentOptions.LeftMargin   = 10;
            pdfConverter.PdfDocumentOptions.BottomMargin = 30;

            var headerBlock = "";
            var footerBlock = "";

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            TextReader htmlReader            = new StringReader(HtmlString.Replace("&nbsp;", " "));

            doc.Load(htmlReader);

            // Install a handler where to change the header and footer in first page
            //pdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent);


            //Header control
            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            headerBlock = doc.GetElementbyId(headerHtmlId).InnerHtml;



            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 600, headerBlock, "");

            //headerHtml.FitHeight = true;  //用了會變小
            pdfConverter.PdfHeaderOptions.HeaderHeight = 180;
            headerHtml.FitWidth   = true;
            headerHtml.EmbedFonts = true;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);
            pdfConverter.PdfHeaderOptions.PageNumberingStartIndex = 1;


            //footer control
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            footerBlock = doc.GetElementbyId(footerHtmlId).InnerHtml;
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 570, footerBlock, "");

            pdfConverter.PdfFooterOptions.FooterHeight = 250;
            footerHtml.FitWidth   = true;
            footerHtml.EmbedFonts = true;
            pdfConverter.PdfFooterOptions.AddElement(footerHtml);
            pdfConverter.PdfFooterOptions.PageNumberingStartIndex         = 2;
            pdfConverter.PdfFooterOptions.PageNumberingPageCountIncrement = 1;


            HtmlString = HtmlString.Replace("id=\"" + headerHtmlId + "\"", "id=\"" + headerHtmlId + "\"" + " style ='display:none;'");
            HtmlString = HtmlString.Replace("id=\"" + footerHtmlId + "\"", "id=\"" + footerHtmlId + "\"" + " style ='display:none;'");
            pdfBytes   = pdfConverter.GetPdfBytesFromHtmlString(HtmlString);

            return(pdfBytes);
        }