public void BypassArrayList() { Uri proxy1 = new Uri("http://proxy.contoso.com"); Uri proxy2 = new Uri("http://proxy2.contoso.com"); WebProxy p = new WebProxy(proxy1, true); p.BypassArrayList.Add("http://proxy2.contoso.com"); p.BypassArrayList.Add("http://proxy2.contoso.com"); Assert.AreEqual(2, p.BypassList.Length, "#1"); Assert.IsTrue(!p.IsBypassed(new Uri("http://www.google.com")), "#2"); Assert.IsTrue(p.IsBypassed(proxy2), "#3"); Assert.AreEqual(proxy2, p.GetProxy(proxy2), "#4"); p.BypassArrayList.Add("?^!@#$%^&}{]["); Assert.AreEqual(3, p.BypassList.Length, "#10"); try { Assert.IsTrue(!p.IsBypassed(proxy2), "#11"); Assert.IsTrue(!p.IsBypassed(new Uri("http://www.x.com")), "#12"); Assert.AreEqual(proxy1, p.GetProxy(proxy2), "#13"); // hmm... although #11 and #13 succeeded before (#3 resp. #4), // it now fails to bypass, and the IsByPassed and GetProxy // methods do not fail.. so when an illegal regular // expression is added through this property it's ignored. // probably an ms.net bug?? :( } catch (ArgumentException) { Assert.Fail("#15: illegal regular expression"); } }
//</snippet3> // if construct with glocabl select // if use system = true then if proxy = Globalproxy.Select - the returned instance // will have its values set // by IE settings. If you do webProxy get default roxy reads manual setting (proxy address and // bypass - doesn't matter what the config file has. //<snippet4> // The following method explicitly identifies // the script to be downloaded and used to select the proxy. public static void CheckScriptedProxyForRequest(Uri resource, Uri script) { WebProxy proxy = new WebProxy(); // See what proxy is used for resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see whether a proxy was selected. if (resourceProxy == null) { Console.WriteLine("No proxy selected for {0}.", resource); return; } else { Console.WriteLine("proxy returned for {0}:", resource); // DIRECT in script is returned as a null Uri object. if (resourceProxy == null) { Console.WriteLine("DIRECT"); } else { Console.WriteLine("{0}", resourceProxy.ToString()); } } }
private static GeoResponse GetGeoResponse(string url) { GeoResponse res = null; try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse)); WebProxy proxy = request.Proxy as WebProxy; if (proxy != null) { string proxyuri = proxy.GetProxy(request.RequestUri).ToString(); request.UseDefaultCredentials = true; request.Proxy = new WebProxy(proxyuri, false) { Credentials = CredentialCache.DefaultCredentials }; } Stream stream = request.GetResponse().GetResponseStream(); res = (GeoResponse)serializer.ReadObject(stream); } catch (Exception ex) { MessageBox.Show("Unable to contact https://maps.googleapis.com error was : " + ex.Message, "FTAnalyzer"); } return(res); }
/// <summary> /// Авторизация и получение токена /// </summary> /// <param name="params">Данные авторизации</param> public void Authorize(ApiAuthParams @params) { //подключение браузера через прокси if (@params.Host != null) { Browser.Proxy = WebProxy.GetProxy(@params.Host, @params.Port, @params.ProxyLogin, @params.ProxyPassword); } //если токен не задан - обычная авторизация if (@params.AccessToken == null) { AuthorizeWithAntiCaptcha( @params.ApplicationId, @params.Login, @params.Password, @params.Settings, @params.TwoFactorAuthorization, @params.CaptchaSid, @params.CaptchaKey ); // Сбросить после использования @params.CaptchaSid = null; @params.CaptchaKey = ""; } //если токен задан - авторизация с помощью токена полученного извне else { TokenAuth(@params.AccessToken, @params.UserId, @params.TokenExpireTime); } _ap = @params; }
/// <inheritdoc /> public void Authorize(IApiAuthParams @params) { // подключение браузера через прокси if (@params.Host != null) { _logger?.Debug(message: "Настройка прокси"); Browser.Proxy = WebProxy.GetProxy(host: @params.Host, port: @params.Port, proxyLogin: @params.ProxyLogin, proxyPassword: @params.ProxyPassword); RestClient.Proxy = Browser.Proxy; } // если токен не задан - обычная авторизация if (@params.AccessToken == null) { AuthorizeWithAntiCaptcha(authParams: @params); // Сбросить после использования @params.CaptchaSid = null; @params.CaptchaKey = ""; } // если токен задан - авторизация с помощью токена полученного извне else { TokenAuth(accessToken: @params.AccessToken, userId: @params.UserId, expireTime: @params.TokenExpireTime); } _ap = @params; _logger?.Debug(message: "Авторизация прошла успешно"); }
static void Main(string[] args) { Console.WriteLine("test .NET proxy w/ default network credentials"); string winProxyAddress = Environment.GetEnvironmentVariable("WIN_PROXY"); if (winProxyAddress == null) { Console.WriteLine("*** error - WIN_PROXY env varibale missing, please set e.g.:"); Console.WriteLine(" $ set WIN_PROXY=http://proxy.bigcorp:57416"); Environment.Exit(1); // note: 0 is OK, 1..N is ERROR } Console.WriteLine(" WIN_PROXY=" + winProxyAddress); // todo/fix: // check if DefaultWebProxy is null first!!!!! WebProxy proxy = new WebProxy(winProxyAddress); proxy.Credentials = CredentialCache.DefaultNetworkCredentials; Console.WriteLine(" set proxy"); WebRequest.DefaultWebProxy = proxy; HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.orf.at"); Console.WriteLine(" req.RequestUri: " + req.RequestUri); WebProxy p = (WebProxy)req.Proxy; if (p != null) { Console.WriteLine("Proxy.BypassProxyOnLocal: " + p.BypassProxyOnLocal); Console.WriteLine("Proxy: " + p.GetProxy(req.RequestUri)); } else { Console.WriteLine("Proxy is null; no proxy will be used"); } Console.WriteLine("before GetResponse"); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Console.WriteLine("after GetResponse"); StreamReader reader = new StreamReader(res.GetResponseStream()); string line = null; int lineno = 0; while ((line = reader.ReadLine()) != null) { lineno++; if (lineno <= 10) { Console.WriteLine("[" + lineno + "] " + line); // print first couple of lines } } } // method main
public static void WebProxy_InvalidArgs_Throws() { var p = new WebProxy(); AssertExtensions.Throws <ArgumentNullException>("destination", () => p.GetProxy(null)); AssertExtensions.Throws <ArgumentNullException>("host", () => p.IsBypassed(null)); Assert.ThrowsAny <ArgumentException>(() => p.BypassList = new string[] { "*.com" }); }
public void GetProxy_ShouldReturnValuePassedToCtor() { var uri = new Uri("http://proxy-example.com:9090"); var proxy = new WebProxy(uri, true); Assert.True(proxy.GetProxy(new Uri("https://airbrake.io/")) == uri); }
public void GetProxy_IsSameForStringAndUriConstructors() { WebProxy proxy1 = new WebProxy("http://localhost:3000"); WebProxy proxy2 = new WebProxy(new Uri("http://localhost:3000")); Uri uri = new Uri("http://0.0.0.0"); Assert.AreEqual(proxy1.GetProxy(uri).OriginalString, proxy2.GetProxy(uri).OriginalString); }
//</snippet5> public static void CheckScriptedProxyForRequest2(Uri resource, Uri script) { WebProxy proxy = new WebProxy(); // if use ssystem = true then if proxy = Glocalproxy.Select - the returned instance // will have its values set // by IE settings. If you do webProxy get defaultProxy reads manual setting (proxy address and // bypass - doesn't matter what the config file has. // if construct with global select // See what proxy is used for resource. Uri resourceProxy = proxy.GetProxy(resource); Console.WriteLine("GetProxy returned for {0} is {1}.", resource, resourceProxy); }
/// <summary> /// Gets the system up stream proxy. /// </summary> /// <param name="sessionEventArgs">The <see cref="SessionEventArgs"/> instance containing the event data.</param> /// <returns><see cref="ExternalProxy"/> instance containing valid proxy configuration from PAC/WAPD scripts if any exists.</returns> private Task <ExternalProxy> GetSystemUpStreamProxy(SessionEventArgs sessionEventArgs) { // Use built-in WebProxy class to handle PAC/WAPD scripts. var systemProxyResolver = new WebProxy(); var systemProxyUri = systemProxyResolver.GetProxy(sessionEventArgs.WebSession.Request.RequestUri); // TODO: Apply authorization var systemProxy = new ExternalProxy { HostName = systemProxyUri.Host, Port = systemProxyUri.Port }; return(Task.FromResult(systemProxy)); }
public void ProxyTest() { var target = new FeedConfigItem { ProxyHost = "1.2.3.4", ProxyPass = "******", ProxyType = HttpProxyHelper.ProxyType.Custom, ProxyUser = "******", ProxyAuth = true, ProxyPort = 3848 }; IWebProxy expected = new WebProxy { Address = new Uri("http://1.2.3.4:3848"), Credentials = new NetworkCredential("proxyusername", "ProxyPassword", "proxydomain") }; var actual = target.Proxy; Assert.AreEqual(expected.GetProxy(new Uri("http://www.google.com")), actual.GetProxy(new Uri("http://www.google.com"))); Assert.AreEqual(expected.Credentials.GetCredential(new Uri("http://www.google.com"), "").Domain, actual.Credentials.GetCredential(new Uri("http://www.google.com"), "").Domain); Assert.AreEqual(expected.Credentials.GetCredential(new Uri("http://www.google.com"), "").UserName, actual.Credentials.GetCredential(new Uri("http://www.google.com"), "").UserName); Assert.AreEqual(expected.Credentials.GetCredential(new Uri("http://www.google.com"), "").Password, actual.Credentials.GetCredential(new Uri("http://www.google.com"), "").Password); }
//</snippet1> //<snippet6> // The following method creates a Web proxy that uses // Web proxy auto-discovery. public static void CheckAutoProxyForRequest(Uri resource) { WebProxy proxy = new WebProxy(); // See what proxy is used for the resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see if a proxy was selected. if (resourceProxy == resource) { Console.WriteLine("No proxy for {0}", resource); } else { Console.WriteLine("Proxy for {0} is {1}", resource.OriginalString, resourceProxy.ToString()); } }
//</snippet10> //<snippet11> public static void CheckDefaultProxyForRequest(Uri resource) { WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy(); // See what proxy is used for resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see whether a proxy was selected. if (resourceProxy == resource) { Console.WriteLine("No proxy for {0}", resource); } else { Console.WriteLine("Proxy for {0} is {1}", resource.ToString(), resourceProxy.ToString()); } }
public static string GetProxy(string url) { WebProxy proxy = WebProxy.GetDefaultProxy(); //WebProxy proxy = new WebProxy(); Uri resource = new Uri(url); Uri proxiedUri = proxy.GetProxy(resource); string proxiedHost = proxiedUri.Host; string resourceHost = resource.Host; if (resourceHost != proxiedHost) { return(proxiedHost); } else { return(null); } }
//<snippet3> // This method specifies a script that should // be used in the event that auto-discovery fails. public static void CheckAutoProxyAndScriptForRequest(Uri resource, Uri script) { WebProxy proxy = new WebProxy(); DisplayProxyProperties(proxy); // See what proxy is used for resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see whether a proxy was selected. if (resourceProxy == resource) { Console.WriteLine("No proxy for {0}", resource); } else { Console.WriteLine("Proxy for {0} is {1}", resource.OriginalString, resourceProxy.ToString()); } }
public static void CheckAutoGlobalProxyForRequest(Uri resource) { WebProxy proxy = new WebProxy(); // Display the proxy's properties. DisplayProxyProperties(proxy); // See what proxy is used for the resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see whether a proxy was selected. if (resourceProxy == resource) { Console.WriteLine("No proxy for {0}", resource); } else { Console.WriteLine("Proxy for {0} is {1}", resource.OriginalString, resourceProxy.ToString()); } }
private bool ValidateProxyFields() { // we'll validate proxy as well //var protocol = cmbProtocol.SelectedItem.ToString(); var host = txtProxyHost.Text; var port = txtProxyPort.Text; try { var proxyAddress = string.Format("http://{0}:{1}/", host, port); var proxy = new WebProxy(proxyAddress, true); proxy.GetProxy(new Uri("http://www.google.com")); return(true); } catch (Exception e) { MessageBox.Show("Invalid proxy, make sure the host and port are valid!", "Invalid proxy"); btnSave.DialogResult = DialogResult.None; return(false); } }
//</snippet2> // The following method creates a Web proxy that // has its initial values set by the Internet Explorer's // explicit proxy address and bypass list. // The proxy uses Internet Explorer's automatically detected // script if it found in the registry; otherwise, it tries to use // Web proxy auto-discovery to set the proxy used for // the request. public static void CheckAutoDefaultProxyForRequest(Uri resource) { WebProxy proxy = (WebProxy)WebRequest.DefaultWebProxy; //GlobalProxySelection.Select; // Display the proxy properties. DisplayProxyProperties(proxy); // See what proxy is used for resource. Uri resourceProxy = proxy.GetProxy(resource); // Test to see if a proxy was selected. if (resourceProxy == resource) { Console.WriteLine("No proxy for {0}", resource); } else { Console.WriteLine("Proxy for {0} is {1}", resource.OriginalString, resourceProxy.ToString()); } }
public static Socket createSocket(String targetHost, String targetPort) { WebProxy myProxy = (WebProxy)WebProxy.GetDefaultProxy(); Uri proxyUri = myProxy.GetProxy(new Uri("https://en.wikipedia.org/wiki/Main_Page")); Console.WriteLine("connecting by default proxy {0}", proxyUri); myProxy.Credentials = CredentialCache.DefaultCredentials; var request = WebRequest.Create("http://" + targetHost + ":" + targetPort); request.Proxy = myProxy; request.Method = "CONNECT"; var response = request.GetResponse(); var responseStream = response.GetResponseStream(); Debug.Assert(responseStream != null); const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance; var rsType = responseStream.GetType(); var connectionProperty = rsType.GetProperty("Connection", Flags); var connection = connectionProperty.GetValue(responseStream, null); var connectionType = connection.GetType(); var networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags); var networkStream = networkStreamProperty.GetValue(connection, null); var nsType = networkStream.GetType(); var socketProperty = nsType.GetProperty("Socket", Flags); Socket socket = (Socket)socketProperty.GetValue(networkStream, null); Console.WriteLine("proxy tunnel established"); return(socket); }
public static void WebProxy_BypassList_ContainsUrl_IsBypassed() { var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" }); Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com"))); }
public static void WebProxy_BypassList_DoesntContainUrl_NotBypassed() { var p = new WebProxy("http://microsoft.com"); Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com"))); }
/// <summary> /// Авторизация и получение токена /// </summary> /// <param name="appId">Идентификатор приложения</param> /// <param name="emailOrPhone">Email или телефон</param> /// <param name="password">Пароль</param> /// <param name="code">Делегат получения кода для двух факторной авторизации</param> /// <param name="captchaSid">Идентификатор капчи</param> /// <param name="captchaKey">Текст капчи</param> /// <param name="settings">Права доступа для приложения</param> /// <param name="host">Имя узла прокси-сервера.</param> /// <param name="port">Номер порта используемого Host.</param> /// <param name="proxyLogin">Логин для прокси-сервера.</param> /// <param name="proxyPassword">Пароль для прокси-сервера</param> /// <exception cref="VkApiAuthorizationException"></exception> private void Authorize(ulong appId, string emailOrPhone, string password, Settings settings, Func <string> code, long?captchaSid = null, string captchaKey = null, string host = null, int?port = null, string proxyLogin = null, string proxyPassword = null) { StopTimer(); LastInvokeTime = DateTimeOffset.Now; var authorization = Browser.Authorize(appId, emailOrPhone, password, settings, code, captchaSid, captchaKey, WebProxy.GetProxy(host, port, proxyLogin, proxyPassword)); if (!authorization.IsAuthorized) { throw new VkApiAuthorizationException($"Invalid authorization with {emailOrPhone} - {password}", emailOrPhone, password); } var expireTime = (Convert.ToInt32(authorization.ExpiresIn) - 10) * 1000; SetTimer(expireTime); AccessToken = authorization.AccessToken; UserId = authorization.UserId; }
public Uri GetProxy(Uri destination) { return(proxy.GetProxy(destination)); }
public static void BypassList_ContainsUrl_IsBypassed() { var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" }); Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com"))); }
public static void InvalidArgs_Throws() { var p = new WebProxy(); Assert.Throws<ArgumentNullException>("destination", () => p.GetProxy(null)); Assert.Throws<ArgumentNullException>("host", () => p.IsBypassed(null)); Assert.Throws<ArgumentNullException>("c", () => p.BypassList = null); Assert.Throws<ArgumentException>(() => p.BypassList = new string[] { "*.com" }); }
public Uri GetProxy(Uri destination) { Debug.WriteLine(string.Format("Proxying '{0}'.", destination.AbsoluteUri)); return(m_inner.GetProxy(destination)); }
public static void BypassList_DoesntContainUrl_NotBypassed() { var p = new WebProxy("http://microsoft.com"); Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com"))); }