//</SNIPPET3> //<SNIPPET4> private void CreateHyperlinkFromSelection() { if (webBrowser1.Document != null) { MSHTML.IHTMLDocument2 iDoc = (MSHTML.IHTMLDocument2)webBrowser1.Document.DomDocument; if (iDoc != null) { MSHTML.IHTMLSelectionObject iSelect = iDoc.selection; if (iSelect == null) { MessageBox.Show("Please select some text before using this command."); return; } MSHTML.IHTMLTxtRange txtRange = (MSHTML.IHTMLTxtRange)iSelect.createRange(); // Create the link. if (txtRange.queryCommandEnabled("CreateLink")) { Object o = null; txtRange.execCommand("CreateLink", true, o); } } } }
/***************************************************************************** * FUNCTION: ParseLiveData * Description: * Parameters: * pHtmlData - *****************************************************************************/ private void ParseLiveData(MSHTML.IHTMLDocument2 pHtmlData) { MSHTML.IHTMLElement2 docBody; MSHTML.IHTMLElement2 quoteElement, quoteElement2; MSHTML.IHTMLElementCollection searchCollection; List <String> values = null; try { docBody = (MSHTML.IHTMLElement2)pHtmlData.body; //build the array of column headers quoteElement = Helpers.FindHTMLElement(docBody, "div", "id", "quotes_summary_current_data"); if (quoteElement != null) { quoteElement2 = Helpers.FindHTMLElement(quoteElement, "div", "class", "inlineblock"); if (quoteElement2 != null) { searchCollection = quoteElement2.getElementsByTagName("span"); values = Helpers.ParseIHTMLElementCollection(searchCollection); this.live_price.Add(double.Parse(values[0])); this.live_chg = double.Parse(values[1]); this.live_chg_pct = double.Parse(values[2].Replace("%", "")); this.live_timestamps.Add(DateTime.Parse(values[3])); } } } catch (Exception e) { //TBD } }
public static void TestPOSTRequest() { WebRequest request; WebResponse response; StreamReader reader; GZipStream gzipStream; string responseText; MSHTML.HTMLDocument htmlresponse = new MSHTML.HTMLDocument(); MSHTML.IHTMLDocument2 webresponse = (MSHTML.IHTMLDocument2)htmlresponse; string body = "curr_id=24442&smlID=1169009&st_date=11%2F18%2F2016&end_date=11%2F18%2F2017&interval_sec=Daily&sort_col=date&sort_ord=DESC&action=historical_data"; try { request = WebRequest.Create("https://ca.investing.com/instruments/HistoricalDataAjax"); request.Credentials = CredentialCache.DefaultCredentials; ((HttpWebRequest)request).Accept = "*/*"; ((HttpWebRequest)request).Method = "POST"; ((HttpWebRequest)request).UserAgent = DEFAULT_USER_AGENT; ((HttpWebRequest)request).Referer = "http://ca.investing.com/equities/canada"; ((HttpWebRequest)request).Headers.Add("Accept-Encoding", "gzip,deflate"); ((HttpWebRequest)request).Headers.Add("X-Requested-With", "XMLHttpRequest"); ((HttpWebRequest)request).Timeout = 20000; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.ContentLength = body.Length; Stream rStream = request.GetRequestStream(); rStream.Write(body.Select(c => (byte)c).ToArray(), 0, body.Length); response = request.GetResponse(); if (response.Headers.Get("Content-Encoding").ToLower().Contains("gzip")) { gzipStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); reader = new StreamReader(gzipStream); } else { reader = new StreamReader(response.GetResponseStream()); } responseText = reader.ReadToEnd(); webresponse.write(responseText); while (webresponse.body == null) { System.Windows.Forms.Application.DoEvents(); } webresponse.close(); reader.Close(); response.Close(); } catch (Exception) { /* Do nothing */ //int stophere = 1; } }
/***************************************************************************** * FUNCTION: ManageDataConnections * Description: * Parameters: None *****************************************************************************/ private void ManageDataConnections() { String pUrl = TemplateRequestStr; MSHTML.HTMLDocument htmlresponse = new MSHTML.HTMLDocument(); MSHTML.IHTMLDocument2 webresponse = (MSHTML.IHTMLDocument2)htmlresponse; if (LockedForUpdate == false) { LockedForUpdate = true; //Disable timer ticks LiveSessionTimer.Stop(); SendMessage(this.ParentFormPtr, WM_UPDATING_DATA, IntPtr.Zero, IntPtr.Zero); /**** Download Data ****/ pUrl += "?noconstruct=1" + "&smlID=" + ActiveMarket.smlId + "&sid=" + ActiveMarket.sid + "&tabletype=price" + "&index_id=" + ActiveMarket.id; webresponse = Helpers.HTMLRequestResponse(pUrl); //Parse the downloaded HTML file if (HistoricalData == null) { HistoricalData = new ExchangeMarket(); } HistoricalData.parseHtmlLiveData(webresponse, pUrl, ActiveMarket.name); SendMessage(this.ParentFormPtr, WM_LIVEUPDATE, IntPtr.Zero, IntPtr.Zero); LockedForUpdate = false; LiveSessionTimer.Start(); } }
/***************************************************************************** * FUNCTION: UpdateLiveData * Description: * Parameters: * pLiveUrl - *****************************************************************************/ public Boolean UpdateLiveData(String pLiveUrl = "") { bool success = true; MSHTML.HTMLDocument htmlresponse = new MSHTML.HTMLDocument(); MSHTML.IHTMLDocument2 webresponse = (MSHTML.IHTMLDocument2)htmlresponse; try { if (pLiveUrl != "") { LiveDataAddress = pLiveUrl; } if (LiveDataAddress != "") { webresponse = Helpers.HTMLRequestResponse(LiveDataAddress); ParseLiveData(webresponse); } } catch (Exception e) { success = false; } return(success); }
void webBrowser1_Document_Body_KeyDown(object sender, HtmlElementEventArgs e) { if (e.KeyPressedCode == (int)Keys.Tab) { e.ReturnValue = false; } else if (e.KeyPressedCode == (int)Keys.F1) { e.ReturnValue = false; MSHTML.IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as MSHTML.IHTMLDocument2; MSHTML.IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { MSHTML.IHTMLTxtRange range = currentSelection.createRange() as MSHTML.IHTMLTxtRange; if (range != null) { if (range.text != null) { if (MainForm.tts == null) { MainForm.tts = new SpeechSynthesizer(); MainForm.tts.SetOutputToDefaultAudioDevice(); } MainForm.tts.SpeakAsyncCancelAll(); MainForm.tts.SpeakAsync(range.text); } } } } }
void WebBrowser1DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (WorkViewerSettings.Default.ColorScheme == 1) { MSHTML.IHTMLDocument2 doc = (MSHTML.IHTMLDocument2)webBrowser1.Document.DomDocument; MSHTML.IHTMLStyleSheet css = doc.createStyleSheet("", 0); css.cssText = @"*{background: #000000 !important; color: #FFFFFF !important;} a:link{color: orange !important;} a:visited{color: red !important;}"; } if (defaultScrollElementIndex != -1) { if (webBrowser1.Document.All.Count > defaultScrollElementIndex) { if (defaultScrollElementIndex > 0) { defaultScrollElementIndex -= 1; } HtmlElement el = webBrowser1.Document.All[defaultScrollElementIndex]; webBrowser1.Document.Window.ScrollTo(scrollX, getVerticalOffsetOfHtmlElement(el)); } defaultScrollElementIndex = -1; } else if (defaultScrollY != 0) { webBrowser1.Document.Window.ScrollTo(0, defaultScrollY); defaultScrollY = 0; } CanSaveURL = true; webBrowser1.Document.Body.KeyDown += webBrowser1_Document_Body_KeyDown;; webBrowser1.Document.Body.KeyUp += webBrowser1_Document_Body_KeyUp; webBrowser1.Focus(); }
public static MSHTML.IHTMLDocument2 HTMLRequestResponse(String pUrl) { WebRequest request; WebResponse response; StreamReader reader; GZipStream gzipStream; string responseText; MSHTML.HTMLDocument htmlresponse = new MSHTML.HTMLDocument(); MSHTML.IHTMLDocument2 webresponse = (MSHTML.IHTMLDocument2)htmlresponse; try { if (pUrl != "") { request = WebRequest.Create(pUrl); request.Credentials = CredentialCache.DefaultCredentials; ((HttpWebRequest)request).Accept = "*/*"; ((HttpWebRequest)request).UserAgent = DEFAULT_USER_AGENT; ((HttpWebRequest)request).Referer = "http://ca.investing.com/equities/canada"; ((HttpWebRequest)request).Headers.Add("Accept-Encoding", "gzip,deflate,br"); ((HttpWebRequest)request).Headers.Add("X-Requested-With", "XMLHttpRequest"); ((HttpWebRequest)request).KeepAlive = true; ((HttpWebRequest)request).Timeout = 20000; response = request.GetResponse(); if (response.Headers.Get("Content-Encoding").ToLower().Contains("gzip")) { gzipStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); reader = new StreamReader(gzipStream); } else { reader = new StreamReader(response.GetResponseStream()); } responseText = reader.ReadToEnd(); webresponse.write(responseText); while (webresponse.body == null) { System.Windows.Forms.Application.DoEvents(); } webresponse.close(); reader.Close(); response.Close(); } } catch (Exception) { /* Do nothing */ //int stophere = 1; } return(webresponse); }
public void EditMode() { if (this.webBrowser1.Document != null) { MSHTML.IHTMLDocument2 doc = this.webBrowser1.Document.DomDocument as MSHTML.IHTMLDocument2; if (doc != null) { doc.designMode = "on"; } } }
//<SNIPPET3> private string GetLastModifiedDate() { if (webBrowser1.Document != null) { MSHTML.IHTMLDocument2 currentDoc = (MSHTML.IHTMLDocument2)webBrowser1.Document.DomDocument; return(currentDoc.lastModified); } else { return(""); } }
/***************************************************************************** * FUNCTION: parseHtmlLiveData * Description: * Parameters: * pHtmlData - *****************************************************************************/ public Boolean parseHtmlLiveData(MSHTML.IHTMLDocument2 pHtmlData, String pUrl, String pName) { Boolean success = true; MSHTML.IHTMLElement2 docBody; MSHTML.IHTMLElementCollection searchCollection; MSHTML.IHTMLElementCollection classProperties; MSHTML.IHTMLElementCollection hrefCollection; List <String> columnHeaders; List <String> equityData; string eq_url = ""; try { //Update configuration data this.liveDataUrl = pUrl; if (this.Name == "") { this.Name = pName; } docBody = (MSHTML.IHTMLElement2)pHtmlData.body; //build the array of column headers searchCollection = (MSHTML.IHTMLElementCollection)docBody.getElementsByTagName("th"); columnHeaders = Helpers.ParseIHTMLElementCollection(searchCollection); //build each equity class docBody = (MSHTML.IHTMLElement2)docBody.getElementsByTagName("tbody").item(0); searchCollection = (MSHTML.IHTMLElementCollection)docBody.getElementsByTagName("tr"); if (this.constituents == null) { this.constituents = new List <Equity>(); } foreach (MSHTML.IHTMLElement2 item in searchCollection) { classProperties = item.getElementsByTagName("td"); hrefCollection = item.getElementsByTagName("a"); //Get the full URL address for the particular equity foreach (MSHTML.IHTMLElement href in hrefCollection) { eq_url = (String)href.getAttribute("href"); if (eq_url.Contains("/equities/")) { eq_url = eq_url.Replace("about:", ""); break; } else { eq_url = ""; } } eq_url = (new Uri(pUrl)).DnsSafeHost + eq_url; equityData = Helpers.ParseIHTMLElementCollection(classProperties); UpdateConstituentData(columnHeaders, equityData, eq_url); } success = true; } catch (Exception e) { Console.WriteLine(e.Message); success = false; } return(success); }
/***************************************************************************** * FUNCTION: updateDataManagerConfig * Description: * Parameters: None *****************************************************************************/ private bool updateDataManagerConfig() { bool success = true; int index1, index2; //Web Request / Response locals String baseUrl, subUrl, responseText, parseText; WebRequest request; WebResponse response; MSHTML.HTMLDocument htmlresponse = new MSHTML.HTMLDocument(); MSHTML.IHTMLDocument2 webresponse = (MSHTML.IHTMLDocument2)htmlresponse; //Xml objects XmlDocument configFile = new XmlDocument(); XmlNodeList nodeList, keyNodeList, subNodeList, configMarketsNodeList, configOptionNodeList; XmlDocument KeyElement = new XmlDocument(); XmlNode marketNode; StreamReader reader; List <String> listOfMarkets; List <String> listOfOptions; string application_path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); string config_path = Path.Combine(application_path, MyMarketAnalyzer.Properties.Resources.DataManagerConfigPath); config_path = new Uri(config_path).LocalPath; configFile.Load(config_path); nodeList = configFile.SelectNodes("Datamanager/Live/Markets/Schema"); index1 = -1; index2 = -1; parseText = ""; try { baseUrl = nodeList[0].Attributes.GetNamedItem("url").InnerText; request = WebRequest.Create(baseUrl); request.Credentials = CredentialCache.DefaultCredentials; ((HttpWebRequest)request).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; ((HttpWebRequest)request).UserAgent = DEFAULT_USER_AGENT; ((HttpWebRequest)request).Timeout = 20000; response = request.GetResponse(); reader = new StreamReader(response.GetResponseStream()); responseText = reader.ReadToEnd(); reader.Close(); response.Close(); //write response to string webresponse.write(responseText); //begin search for the menu items we want keyNodeList = GetConfiguredItems(responseText, configFile, "Datamanager/Live/Markets/Schema/"); configMarketsNodeList = configFile.SelectNodes("Datamanager/Live/Markets/Data/Market"); listOfMarkets = new List <string>(); for (int i = 0; i < configMarketsNodeList.Count; i++) { listOfMarkets.Add(configMarketsNodeList[i].Attributes.GetNamedItem("name").InnerText); } //For each geographic location, get the list of available markets / indexes foreach (XmlNode subNode in keyNodeList) { if (subNode.InnerXml != "") { index1 = subNode.OuterXml.IndexOf("href=\"", 0) + 6; index2 = subNode.OuterXml.IndexOf("\"", index1); parseText = subNode.OuterXml.Substring(index1, index2 - index1); subUrl = (new Uri(new Uri(baseUrl), parseText)).ToString(); if (parseText.Substring(0, 1) != "/") { parseText = "/" + parseText; } if (listOfMarkets.Contains(subNode.InnerXml)) { marketNode = configMarketsNodeList[listOfMarkets.IndexOf(subNode.InnerXml)]; } else { marketNode = configFile.CreateNode("element", "Market", ""); XmlAttribute atHref = configFile.CreateAttribute("href"); atHref.Value = parseText; XmlAttribute atName = configFile.CreateAttribute("name"); atName.Value = subNode.InnerText; marketNode.Attributes.Append(atHref); marketNode.Attributes.Append(atName); configFile.SelectNodes("Datamanager/Live/Markets/Data")[0].InsertAfter(marketNode, configMarketsNodeList[configMarketsNodeList.Count - 1]); } responseText = ""; request = WebRequest.Create(subUrl); request.Credentials = CredentialCache.DefaultCredentials; ((HttpWebRequest)request).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; ((HttpWebRequest)request).UserAgent = DEFAULT_USER_AGENT; ((HttpWebRequest)request).Timeout = 20000; response = request.GetResponse(); reader = new StreamReader(response.GetResponseStream()); responseText = reader.ReadToEnd(); reader.Close(); response.Close(); //write response to string webresponse.write(responseText); subNodeList = GetConfiguredItems(responseText, configFile, "Datamanager/Live/Markets/Data/Schema/"); listOfOptions = new List <string>(); configOptionNodeList = null; if (marketNode.HasChildNodes) { configOptionNodeList = marketNode.SelectNodes("option"); for (int i = 0; i < configOptionNodeList.Count; i++) { listOfOptions.Add(configOptionNodeList[i].Attributes.GetNamedItem("id").InnerText); } } foreach (XmlNode optionNode in subNodeList) { //Only add options that aren't already in the list (based on id) if (!listOfOptions.Contains(optionNode.Attributes.GetNamedItem("id").InnerText)) { XmlNode newOption = configFile.ImportNode(optionNode, true); if (configOptionNodeList == null) { marketNode.AppendChild(newOption); } else { marketNode.InsertAfter(newOption, configOptionNodeList[configOptionNodeList.Count - 1]); } } } } } configFile.Save(config_path); } catch (Exception e) { success = false; } return(success); }