public string GetNewShortUrl(string sourceUrl, IWebProxy webProxy) { if (sourceUrl == null) throw new ArgumentNullException("sourceUrl"); // fallback will be source url string result = sourceUrl; //Added 11/3/2007 scottckoon //20 is the shortest a tinyURl can be (http://tinyurl.com/a) //so if the sourceUrl is shorter than that, don't make a request to TinyURL if (sourceUrl.Length > 20 && !IsShortenedUrl(sourceUrl)) { // tinyurl doesn't like urls w/o protocols so we'll ensure we have at least http string requestUrl = string.Format(this.requestTemplate,(EnsureMinimalProtocol(sourceUrl))); WebRequest request = HttpWebRequest.Create(requestUrl); request.Proxy = webProxy; try { using (Stream responseStream = request.GetResponse().GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.ASCII); result = reader.ReadToEnd(); } } catch { // eat it and return original url } } //scottckoon - It doesn't make sense to return a TinyURL that is longer than the original. if (result.Length > sourceUrl.Length) { result = sourceUrl; } return result; }
public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { if (uri == null) { throw new ArgumentNullException("uri"); } if (LaunchedFromVS()) { throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_CannotPromptForCedentials")); } string message = credentialType == CredentialType.ProxyCredentials ? LocalizedResourceManager.GetString("Credentials_ProxyCredentials") : LocalizedResourceManager.GetString("Credentials_RequestCredentials"); Console.WriteLine(message, uri.OriginalString); Console.Write(LocalizedResourceManager.GetString("Credentials_UserName")); string username = Console.ReadLine(); Console.Write(LocalizedResourceManager.GetString("Credentials_Password")); SecureString password = ReadLineAsSecureString(); var credentials = new NetworkCredential { UserName = username, SecurePassword = password }; return credentials; }
public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { if (uri == null) { throw new ArgumentNullException("uri"); } string message = credentialType == CredentialType.ProxyCredentials ? LocalizedResourceManager.GetString("Credentials_ProxyCredentials") : LocalizedResourceManager.GetString("Credentials_RequestCredentials"); Console.WriteLine(message, uri.OriginalString); Console.Write(LocalizedResourceManager.GetString("Credentials_UserName")); string username = Console.ReadLine(); Console.Write(LocalizedResourceManager.GetString("Credentials_Password")); using (SecureString password = new SecureString()) { Console.ReadSecureString(password); var credentials = new NetworkCredential { UserName = username, SecurePassword = password }; return credentials; } }
public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType , bool retrying) { if (Credentials.ContainsKey(uri)) return Credentials[uri]; return provider.GetCredentials(uri, proxy, credentialType, retrying); }
// // Create - creates internal WebProxy that stores proxy info // protected override void Create(Object obj) { if (obj == null) m_IWebProxy = new WebProxy(); else m_IWebProxy = ((DefaultProxyHandlerWrapper)obj).WebProxy; }
public HttpRequest(string requestUrl, IWebProxy webProxy) { AllowAutoRedirect = true; ContentType = null; this.requestUrl = requestUrl; Proxy = webProxy; }
/// <summary> /// new, proxy and cookie passed explicitly /// </summary> /// <param name="proxy"></param> /// <param name="cookieContainer"></param> public PttRequestFactory(IWebProxy proxy, CookieContainer cookieContainer = null) { _proxy = proxy; _cookieContainer = cookieContainer ?? new CookieContainer(); _viewStateValue = ""; _eventValidationValue = ""; }
public PublisherAPI(IWebProxy proxy) { this.publisherService = new PublisherService(); this.publisherService.Proxy = proxy; this.publisherService.EnableDecompression = true; this.publisherService.UserAgent = Constants.UserAgent; }
public FrmProxyAuth(FrmMain frmMain, IWebProxy proxy) { _frmMain = frmMain; _proxy = proxy; InitializeComponent(); }
/// <summary> /// Requests the Correios' website for the given CEP's address, scraps the HTML and returns it. /// </summary> /// <param name="cep">CEP of the address</param> /// <param name="proxy">Proxy to use for the request</param> /// <returns>The scraped address or null if no address was found for the given CEP</returns> /// <exception cref="ArgumentNullException">If the given proxy is null</exception> /// <exception cref="ScrapException">If an unexpected HTML if found</exception> public static Endereco Scrap(string cep, IWebProxy proxy) { if (proxy == null) throw new ArgumentNullException("proxy"); return Parse(Request(cep, proxy)); }
/// <summary> /// Generates the authorize URI. /// Then call GetTokens(string) after get the pin code. /// </summary> /// <returns> /// The authorize URI. /// </returns> /// <param name="consumerKey"> /// Consumer key. /// </param> /// <param name="consumerSecret"> /// Consumer secret. /// </param> /// <param name="oauthCallback"> /// <para>For OAuth 1.0a compliance this parameter is required. The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account. Set this to oob for out-of-band pin mode. This is also how you specify custom callbacks for use in desktop/mobile applications.</para> /// <para>Always send an oauth_callback on this step, regardless of a pre-registered callback.</para> /// </param> /// <param name="proxy"> /// Proxy information for the request. /// </param> public static OAuthSession Authorize(string consumerKey, string consumerSecret, string oauthCallback = "oob", IWebProxy proxy = null) { // Note: Twitter says, // "If you're using HTTP-header based OAuth, you shouldn't include oauth_* parameters in the POST body or querystring." var prm = new Dictionary<string,object>(); if (!string.IsNullOrEmpty(oauthCallback)) prm.Add("oauth_callback", oauthCallback); var header = Tokens.Create(consumerKey, consumerSecret, null, null) .CreateAuthorizationHeader(MethodType.Get, RequestTokenUrl, prm); var dic = from x in Request.HttpGet(RequestTokenUrl, prm, header, "CoreTweet", proxy).Use() from y in new StreamReader(x).Use() select y.ReadToEnd() .Split('&') .Where(z => z.Contains('=')) .Select(z => z.Split('=')) .ToDictionary(z => z[0], z => z[1]); return new OAuthSession() { RequestToken = dic["oauth_token"], RequestTokenSecret = dic["oauth_token_secret"], ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Proxy = proxy }; }
private BoxManager(IRequestAuthenticator requestAuthenticator, IWebProxy proxy, BoxManagerOptions options, string onBehalfOf = null) : this() { requestAuthenticator.SetOnBehalfOf(onBehalfOf); _restClient = new BoxRestClient(requestAuthenticator, proxy, options); _uploadClient = new BoxUploadClient(requestAuthenticator, proxy, options); }
//IWebProxy does not give access to the underlying WebProxy it returns type WebProxyWrapper //the underlying webproxy is needed in order to use the proxy address, the following uses reflecion to cast to WebProxy static WebProxy ConvertToWebProxy(IWebProxy proxyWrapper) { PropertyInfo propertyInfo = proxyWrapper.GetType().GetProperty("WebProxy", BindingFlags.NonPublic | BindingFlags.Instance); WebProxy wProxy = (WebProxy)propertyInfo.GetValue(proxyWrapper, null); return wProxy; }
protected HttpProvider(Uri uri) { _originalUri = uri; _headers = new WebHeaderCollection(true); _allowAutoRedirect = true; _proxy = GlobalProxySelection.Select; }
public TokenProvider(string clientId, string clientSecret, IWebProxy webProxy = null, BoxManagerOptions options = BoxManagerOptions.None) { _clientId = clientId; _clientSecret = clientSecret; _requestHelper = new RequestHelper(); _restClient = new BoxRestClient(null, webProxy, options); }
public static void OneTimeSetup(TestContext tctx) { if (!Directory.Exists(DEFAULT_BASE_LOCAL_STORE)) Directory.CreateDirectory(DEFAULT_BASE_LOCAL_STORE); //_baseLocalStore = $"{DEFAULT_BASE_LOCAL_STORE}-{DateTime.Now.ToString("yyMMdd-HHmmss")}"; //if (!Directory.Exists(_baseLocalStore)) // Directory.CreateDirectory(_baseLocalStore); if (File.Exists(WEB_PROXY_CONFIG)) { _wpConfig = WebProxyConfig.Load(WEB_PROXY_CONFIG); if (_wpConfig != null && _wpConfig.UseProxy) { _proxy = new WebProxy(_wpConfig.HostName, _wpConfig.HostPort); if (_wpConfig.AcceptAllServerCerts) { System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; }; } } } }
public Config(string userName, string password, string outDir, bool downloadAll, Document.DownloadType[] docExpType, Document.DownloadType[] sprdExpType, Document.DownloadType[] presExpType, Document.DownloadType[] drawExpType, IWebProxy webproxy, bool bypassHttpsChecks, bool debugMode, int? dateDiff, bool appsMode, string appsDomain, string appsOAuthSecret, bool appsOnlyOAuth) { this.userName = userName; this.password = password; this.outDir = outDir; this.downloadAll = downloadAll; this.docExpType = docExpType; this.sprdExpType = sprdExpType; this.presExpType = presExpType; this.drawExpType = drawExpType; this.iwebproxy = webproxy; this.bypassHttpsChecks = bypassHttpsChecks; this.debugMode = debugMode; this.dateDiff = dateDiff; this.appsMode = appsMode; this.appsDomain = appsDomain; this.appsOAuthSecret = appsOAuthSecret; this.appsOnlyOAuth = appsOnlyOAuth; }
public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, CredentialType credentialType) { if (!_config.Information.IsInteractive) { return CredentialCache.DefaultCredentials; } string message = credentialType == CredentialType.ProxyCredentials ? "Please provide proxy credentials:" : "Please provide credentials for: {0}".format_with(uri.OriginalString); this.Log().Info(ChocolateyLoggers.Important, message); Console.Write("User name: "); string username = Console.ReadLine(); Console.Write("Password: "); var password = Console.ReadLine(); //todo: set this up as secure //using (var securePassword = new SecureString()) //{ // foreach (var letter in password.to_string()) // { // securePassword.AppendChar(letter); // } var credentials = new NetworkCredential { UserName = username, Password = password, //SecurePassword = securePassword }; return credentials; // } }
public ConnectAPI(IWebProxy proxy) { this.connectService = new ConnectService(); this.connectService.Proxy = proxy; this.connectService.EnableDecompression = true; this.connectService.UserAgent = Constants.UserAgent; }
public WebClientWrapper() { if (TrustLevelChecker.IsFullTrust() && Environment.Version.Major < 4) return; proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; }
public TweetCollection GetSearchResults(string searchText, IWebProxy webProxy) { TweetCollection tweets = new TweetCollection(); string tweetscanUrl = "http://tweetscan.com/trss.php?s=" + searchText; HttpWebRequest request = WebRequest.Create(tweetscanUrl) as HttpWebRequest; // Add configured web proxy request.Proxy = webProxy; //try //{ // Get the Web Response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Load the response data into a XmlDocument XmlDocument doc = new XmlDocument(); doc.Load(reader); // Get statuses with XPath XmlNodeList nodes = doc.SelectNodes("/rss/channel/item"); foreach (XmlNode node in nodes) { Tweet tweet = new Tweet(); tweet.Id = double.Parse(node.SelectSingleNode("tweetid").InnerText); tweet.Text = HttpUtility.HtmlDecode(node.SelectSingleNode("text").InnerText); string dateString = node.SelectSingleNode("pubdate").InnerText; if (!string.IsNullOrEmpty(dateString)) { tweet.DateCreated = DateTime.Parse(dateString); } User user = new User(); user.Name = node.SelectSingleNode("username").InnerText; user.ScreenName = node.SelectSingleNode("screenname").InnerText; user.ImageUrl = node.SelectSingleNode("image").InnerText; tweet.User = user; tweets.Add(tweet); } tweets.SaveToDisk(); } //} //catch { ////TODO: not sure what kind of errors are thrown by tweetcan // // eat it. //} return tweets; }
public void Add(IWebProxy proxy) { var webProxy = proxy as WebProxy; if (webProxy != null) { _cache.TryAdd(webProxy.Address, webProxy); } }
protected TokenClientBase(string id, string secret, string endpointUrl, IWebProxy proxy) { this.endpointUrl = endpointUrl; this.clientId = id; // base 64 encode client and secret for the Authorization header credentials = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(id + ":" + secret)); this.proxy = proxy; }
public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { var cp = MonoDevelop.Core.WebRequestHelper.CredentialProvider; if (cp == null) return null; return cp.GetCredentials (uri, proxy, (MonoDevelop.Core.Web.CredentialType)credentialType, retrying); }
protected HttpWebClientProtocol () { allowAutoRedirect = false; clientCertificates = null; cookieContainer = null; proxy = null; // FIXME userAgent = String.Format ("Mono Web Services Client Protocol {0}", Environment.Version); }
public void RemoveProxy(IWebProxy proxy) { if (proxy == null) return; if (_proxies.Contains(proxy)) _proxies.Remove(proxy); }
public RestSharpClient(string baseUrl, int connectionTimeout, IWebProxy proxy, ILogger logger) { this.adapter = new RestSharpAdapter(); this.baseUrl = baseUrl; this.connectionTimeout = connectionTimeout; this.proxy = proxy; this.logger = logger; }
public GoogleMusicClient() { MACaddress = (from nic in NetworkInterface.GetAllNetworkInterfaces() where nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback select nic.GetPhysicalAddress().ToString()).FirstOrDefault(); Proxy = WebRequest.GetSystemWebProxy(); ErrorHandler = null; }
public static void Clear() { UserAgent = new List<string>(); HttpHeader = null; HttpCookie = null; Proxy = null; Setting = null; }
public MySpaceID(string apiDomain, string consumerKey, string consumerSecret, int timeout, IWebProxy proxy) { ApiDomain = apiDomain; ConsumerKey = consumerKey; ConsumerSecret = consumerSecret; Timeout = timeout; Proxy = proxy; }
private async Task <IOutlookSynchronizer> CreateGoogleContactSynchronizer(Options options, AvailableSynchronizerComponents componentsToFill) { var atypeRepository = new OutlookContactRepository <IGoogleContactContext> ( _outlookSession, options.OutlookFolderEntryId, options.OutlookFolderStoreId, _daslFilterProvider, _queryFolderStrategy); componentsToFill.OutlookContactRepositoryForGoogle = atypeRepository; IWebProxy proxy = options.ProxyOptions != null?CreateProxy(options.ProxyOptions) : null; var googleApiExecutor = new GoogleApiOperationExecutor(await OAuth.Google.GoogleHttpClientFactory.LoginToContactsService(options.UserName, proxy)); var mappingParameters = GetMappingParameters <ContactMappingConfiguration> (options); var atypeIdEqulityComparer = EqualityComparer <string> .Default; var btypeIdEqualityComparer = EqualityComparer <string> .Default; const int chunkSize = 100; var btypeRepository = new GoogleContactRepository( googleApiExecutor, options.UserName, mappingParameters, btypeIdEqualityComparer, new ChunkedExecutor(chunkSize)); componentsToFill.GoogleContactRepository = btypeRepository; componentsToFill.GoogleApiOperationExecutor = googleApiExecutor; var entityMapper = new GoogleContactEntityMapper(mappingParameters); var entityRelationDataFactory = new GoogleContactRelationDataFactory(); var syncStateFactory = new EntitySyncStateFactory <string, DateTime, ContactItemWrapper, string, GoogleContactVersion, GoogleContactWrapper, IGoogleContactContext> ( entityMapper, entityRelationDataFactory, ExceptionHandler.Instance); var storageDataDirectory = _profileDataDirectoryFactory(options.Id); var storageDataAccess = new EntityRelationDataAccess <string, DateTime, GoogleContactRelationData, string, GoogleContactVersion> (storageDataDirectory); componentsToFill.GoogleContactsEntityRelationDataAccess = storageDataAccess; var atypeWriteRepository = BatchEntityRepositoryAdapter.Create(atypeRepository); var synchronizer = new Synchronizer <string, DateTime, ContactItemWrapper, string, GoogleContactVersion, GoogleContactWrapper, IGoogleContactContext> ( atypeRepository, btypeRepository, atypeWriteRepository, btypeRepository, InitialSyncStateCreationStrategyFactory <string, DateTime, ContactItemWrapper, string, GoogleContactVersion, GoogleContactWrapper, IGoogleContactContext> .Create( syncStateFactory, syncStateFactory.Environment, options.SynchronizationMode, options.ConflictResolution, e => new GoogleContactConflictInitialSyncStateCreationStrategyAutomatic(e)), storageDataAccess, entityRelationDataFactory, new InitialGoogleContactEntityMatcher(btypeIdEqualityComparer), atypeIdEqulityComparer, btypeIdEqualityComparer, _totalProgressFactory, EqualityComparer <DateTime> .Default, new GoogleContactVersionComparer(), syncStateFactory); var googleContactContextFactory = new GoogleContactContextFactory(googleApiExecutor, btypeIdEqualityComparer, options.UserName, chunkSize); componentsToFill.GoogleContactContextFactory = googleContactContextFactory; return(new OutlookSynchronizer <string, GoogleContactVersion> ( new ContextCreatingSynchronizerDecorator <string, DateTime, ContactItemWrapper, string, GoogleContactVersion, GoogleContactWrapper, IGoogleContactContext> ( synchronizer, googleContactContextFactory))); }
/// <summary> /// Выполнить запрос. /// </summary> /// <param name="url">URL.</param> /// <param name="webProxy">Хост.</param> /// <returns>Результат</returns> public static WebCallResult MakeCall(string url, IWebProxy webProxy = null) { var call = new WebCall(url, new Cookies(), webProxy); return(call.MakeRequest(webProxy)); }
public static Bitmap DownloadImage(string imageUrl, IWebProxy proxy, ICredentials credentials) { return(DownloadImage(imageUrl, proxy, credentials, String.Empty, String.Empty)); }
public static byte[] DownloadRaw(string url, IWebProxy proxy, ICredentials credentials) { return(DownloadRaw(url, null, proxy, credentials, String.Empty, String.Empty)); }
async Task <TransportBase> CreateClientWebSocketTransportAsync(TimeSpan timeout, IWebProxy proxy) { UriBuilder webSocketUriBuilder = new UriBuilder { Scheme = WebSocketConstants.Scheme, Host = _uri.Host, Port = _uri.Port }; var websocket = await CreateClientWebSocketAsync(webSocketUriBuilder.Uri, timeout, proxy).ConfigureAwait(false); return(new ClientWebSocketTransport( websocket, null, null)); }
public static HttpWebRequest CreateWebRequest(HttpMethod method, string url, NameValueCollection headers = null, CookieCollection cookies = null, string contentType = null, long contentLength = 0) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); string accept = null; string referer = null; string userAgent = ShareXResources.UserAgent; if (headers != null) { if (headers["Accept"] != null) { accept = headers["Accept"]; headers.Remove("Accept"); } if (headers["Content-Length"] != null) { if (long.TryParse(headers["Content-Length"], out contentLength)) { request.ContentLength = contentLength; } headers.Remove("Content-Length"); } if (headers["Content-Type"] != null) { contentType = headers["Content-Type"]; headers.Remove("Content-Type"); } if (headers["Referer"] != null) { referer = headers["Referer"]; headers.Remove("Referer"); } if (headers["User-Agent"] != null) { userAgent = headers["User-Agent"]; headers.Remove("User-Agent"); } request.Headers.Add(headers); } request.Accept = accept; request.ContentType = contentType; request.CookieContainer = new CookieContainer(); if (cookies != null) { request.CookieContainer.Add(cookies); } request.Method = method.ToString(); IWebProxy proxy = HelpersOptions.CurrentProxy.GetWebProxy(); if (proxy != null) { request.Proxy = proxy; } request.Referer = referer; request.UserAgent = userAgent; if (contentLength > 0) { request.AllowWriteStreamBuffering = HelpersOptions.CurrentProxy.IsValidProxy(); if (method == HttpMethod.GET) { request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); } request.ContentLength = contentLength; request.Pipelined = false; request.Timeout = -1; } else { request.KeepAlive = false; } return(request); }
public Feed(Uri url, FeedAuthTypes authtype, string username, string password, IWebProxy proxy) { UpdateInterval = 10; HasError = false; Loaded = false; feedproxy = proxy; FeedUri = url; feedauthtype = authtype; feedusername = username; feedpassword = password; }
public NativeMessageHandler(bool throwOnCaptiveNetwork, TLSConfig tLSConfig, NativeCookieHandler cookieHandler = null, IWebProxy proxy = null) { this.throwOnCaptiveNetwork = throwOnCaptiveNetwork; var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; this.TLSConfig = tLSConfig; // System.Net.ServicePointManager.SecurityProtocol provides a mechanism for specifying supported protocol types // for System.Net. Since iOS only provides an API for a minimum and maximum protocol we are not able to port // this configuration directly and instead use the specified minimum value when one is specified. configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_2; if (!TLSConfig.DangerousAcceptAnyServerCertificateValidator && TLSConfig.Pins != null && TLSConfig.Pins.Count > 0) { this.CertificatePinner = new CertificatePinner(); foreach (var pin in TLSConfig.Pins) { this.CertificatePinner.AddPins(pin.Hostname, pin.PublicKeys); } } SetClientCertificate(TLSConfig.ClientCertificate); // NSUrlSessionConfiguration.DefaultSessionConfiguration uses the default NSHttpCookieStorage.SharedStorage // PR: Proxy has been supported on iOS #19 if (proxy != null && proxy is WebProxy) { var webProxy = proxy as WebProxy; NSObject[] values = { NSObject.FromObject(webProxy.Address.Host), NSNumber.FromInt32(webProxy.Address.Port), NSNumber.FromInt32(1) }; NSObject[] keys = { NSObject.FromObject("HTTPSProxy"), NSObject.FromObject("HTTPSPort"), NSObject.FromObject("HTTPSEnable") }; var proxyDict = NSDictionary.FromObjectsAndKeys(values, keys); configuration.ConnectionProxyDictionary = proxyDict; if (webProxy.Credentials != null) { var credentials = (NetworkCredential)webProxy.Credentials; var authData = string.Format("{0}:{1}", credentials.UserName, credentials.Password); var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData)); NSObject[] hValues = { NSObject.FromObject(authHeaderValue) }; NSObject[] hKeys = { NSObject.FromObject("Proxy-Authorization") }; var headers = NSDictionary.FromObjectsAndKeys(hValues, hKeys); configuration.HttpAdditionalHeaders = headers; } } var urlSessionDelegate = new DataTaskDelegate(this); session = NSUrlSession.FromConfiguration(configuration, (INSUrlSessionDelegate)urlSessionDelegate, null); }
/// <summary> /// Initializes a new instance of the <see cref="SendGridClient"/> class. /// </summary> /// <param name="webProxy">Web proxy.</param> /// <param name="apiKey">Your SendGrid API key.</param> /// <param name="host">Base url (e.g. https://api.sendgrid.com)</param> /// <param name="requestHeaders">A dictionary of request headers</param> /// <param name="version">API version, override AddVersion to customize</param> /// <param name="urlPath">Path to endpoint (e.g. /path/to/endpoint)</param> /// <returns>Interface to the SendGrid REST API</returns> public SendGridClient(IWebProxy webProxy, string apiKey, string host = "https://api.sendgrid.com", Dictionary <string, string> requestHeaders = null, string version = "v3", string urlPath = null) : this(apiKey, host, requestHeaders, version, urlPath) { this.WebProxy = webProxy; }
public abstract Task OpenConnectionAsync(AmqpClientConnection connection, TimeSpan timeout, bool useWebSocket, IWebProxy proxy, RemoteCertificateValidationCallback remoteCertificateValidationCallback);
public static Bitmap DownloadImage(string imageUrl, IWebProxy proxy) { return(DownloadImage(imageUrl, proxy, null)); }
public DelegatingHandlerImpl(IWebProxy proxy) { this.Proxy = proxy; }
private async Task <IOutlookSynchronizer> CreateGoogleTaskSynchronizer(Options options) { var mappingParameters = GetMappingParameters <TaskMappingConfiguration> (options); var atypeRepository = new OutlookTaskRepository(_outlookSession, options.OutlookFolderEntryId, options.OutlookFolderStoreId, _daslFilterProvider, mappingParameters, _queryFolderStrategy); IWebProxy proxy = options.ProxyOptions != null?CreateProxy(options.ProxyOptions) : null; var tasksService = await OAuth.Google.GoogleHttpClientFactory.LoginToGoogleTasksService(options.UserName, proxy); TaskList taskList; try { taskList = tasksService.Tasklists.Get(options.CalenderUrl).Execute(); } catch (Google.GoogleApiException) { s_logger.ErrorFormat($"Profile '{options.Name}' (Id: '{options.Id}'): task list '{options.CalenderUrl}' not found."); throw; } var btypeRepository = new GoogleTaskRepository(tasksService, taskList); var relationDataFactory = new GoogleTaskRelationDataFactory(); var syncStateFactory = new EntitySyncStateFactory <string, DateTime, TaskItemWrapper, string, string, Task, int> ( new GoogleTaskMapper(), relationDataFactory, ExceptionHandler.Instance); var storageDataDirectory = _profileDataDirectoryFactory(options.Id); var btypeIdEqualityComparer = EqualityComparer <string> .Default; var atypeIdEqualityComparer = EqualityComparer <string> .Default; var atypeWriteRepository = BatchEntityRepositoryAdapter.Create(atypeRepository); var btypeWriteRepository = BatchEntityRepositoryAdapter.Create(btypeRepository); var synchronizer = new Synchronizer <string, DateTime, TaskItemWrapper, string, string, Task, int> ( atypeRepository, btypeRepository, atypeWriteRepository, btypeWriteRepository, InitialSyncStateCreationStrategyFactory <string, DateTime, TaskItemWrapper, string, string, Task, int> .Create( syncStateFactory, syncStateFactory.Environment, options.SynchronizationMode, options.ConflictResolution, e => new GoogleTaskConflictInitialSyncStateCreationStrategyAutomatic(e)), new EntityRelationDataAccess <string, DateTime, GoogleTaskRelationData, string, string> (storageDataDirectory), relationDataFactory, new InitialGoogleTastEntityMatcher(btypeIdEqualityComparer), atypeIdEqualityComparer, btypeIdEqualityComparer, _totalProgressFactory, EqualityComparer <DateTime> .Default, EqualityComparer <string> .Default, syncStateFactory); return(new OutlookSynchronizer <string, string> ( new NullContextSynchronizerDecorator <string, DateTime, TaskItemWrapper, string, string, Task>(synchronizer))); }
public AccountClient(string accesskey, string sercetkey, string host, IWebProxy proxy = null) : base(proxy) { _urlBuilder = new HuobiPrivateUrlBuilder(accesskey, sercetkey, host); }
public async Task OpenAsync(TimeSpan timeout, bool useWebSocket, X509Certificate2 clientCert, RemoteCertificateValidationCallback certificateValidationCallback, IWebProxy proxy) { if (Logging.IsEnabled) { Logging.Enter(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}"); } var hostName = _uri.Host; var tcpSettings = new TcpTransportSettings { Host = hostName, Port = _uri.Port != -1 ? _uri.Port : AmqpConstants.DefaultSecurePort }; TransportSettings = new TlsTransportSettings(tcpSettings) { TargetHost = hostName, Certificate = clientCert, CertificateValidationCallback = certificateValidationCallback }; TransportBase transport; if (useWebSocket) { transport = await CreateClientWebSocketTransportAsync(timeout, proxy).ConfigureAwait(false); SaslTransportProvider provider = _amqpSettings.GetTransportProvider <SaslTransportProvider>(); if (provider != null) { if (Logging.IsEnabled) { Logging.Info(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: Using SaslTransport"); } _sentHeader = new ProtocolHeader(provider.ProtocolId, provider.DefaultVersion); ByteBuffer buffer = new ByteBuffer(new byte[AmqpConstants.ProtocolHeaderSize]); _sentHeader.Encode(buffer); _tcs = new TaskCompletionSource <TransportBase>(); var args = new TransportAsyncCallbackArgs(); args.SetBuffer(buffer.Buffer, buffer.Offset, buffer.Length); args.CompletedCallback = OnWriteHeaderComplete; args.Transport = transport; bool operationPending = transport.WriteAsync(args); if (Logging.IsEnabled) { Logging.Info(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: Sent Protocol Header: {_sentHeader.ToString()} operationPending: {operationPending} completedSynchronously: {args.CompletedSynchronously}"); } if (!operationPending) { args.CompletedCallback(args); } transport = await _tcs.Task.ConfigureAwait(false); await transport.OpenAsync(timeout).ConfigureAwait(false); } } else { var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings); transport = await tcpInitiator.ConnectTaskAsync(timeout).ConfigureAwait(false); } AmqpConnection = new AmqpConnection(transport, _amqpSettings, AmqpConnectionSettings); AmqpConnection.Closed += OnConnectionClosed; await AmqpConnection.OpenAsync(timeout).ConfigureAwait(false); _isConnectionClosed = false; }
/// <summary>Initializes the pools.</summary> public HttpConnectionPoolManager(HttpConnectionSettings settings) { _settings = settings; _maxConnectionsPerServer = settings._maxConnectionsPerServer; _pools = new ConcurrentDictionary <HttpConnectionKey, HttpConnectionPool>(); // As an optimization, we can sometimes avoid the overheads associated with // storing connections. This is possible when we would immediately terminate // connections anyway due to either the idle timeout or the lifetime being // set to zero, as in that case the timeout effectively immediately expires. // However, we can only do such optimizations if we're not also tracking // connections per server, as we use data in the associated data structures // to do that tracking. bool avoidStoringConnections = settings._maxConnectionsPerServer == int.MaxValue && (settings._pooledConnectionIdleTimeout == TimeSpan.Zero || settings._pooledConnectionLifetime == TimeSpan.Zero); // Start out with the timer not running, since we have no pools. // When it does run, run it with a frequency based on the idle timeout. if (!avoidStoringConnections) { if (settings._pooledConnectionIdleTimeout == Timeout.InfiniteTimeSpan) { const int DefaultScavengeSeconds = 30; _cleanPoolTimeout = TimeSpan.FromSeconds(DefaultScavengeSeconds); } else { const int ScavengesPerIdle = 4; const int MinScavengeSeconds = 1; TimeSpan timerPeriod = settings._pooledConnectionIdleTimeout / ScavengesPerIdle; _cleanPoolTimeout = timerPeriod.TotalSeconds >= MinScavengeSeconds ? timerPeriod : TimeSpan.FromSeconds(MinScavengeSeconds); } bool restoreFlow = false; try { // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); restoreFlow = true; } _cleaningTimer = new Timer(s => ((HttpConnectionPoolManager)s).RemoveStalePools(), this, Timeout.Infinite, Timeout.Infinite); } finally { // Restore the current ExecutionContext if (restoreFlow) { ExecutionContext.RestoreFlow(); } } } // Figure out proxy stuff. if (settings._useProxy) { _proxy = settings._proxy ?? SystemProxyInfo.ConstructSystemProxy(); if (_proxy != null) { _proxyCredentials = _proxy.Credentials ?? settings._defaultProxyCredentials; } } }
async Task <ClientWebSocket> CreateClientWebSocketAsync(Uri websocketUri, TimeSpan timeout, IWebProxy webProxy) { var websocket = new ClientWebSocket(); // Set SubProtocol to AMQPWSB10 websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10); websocket.Options.KeepAliveInterval = WebSocketConstants.KeepAliveInterval; websocket.Options.SetBuffer(WebSocketConstants.BufferSize, WebSocketConstants.BufferSize); //Check if we're configured to use a proxy server try { if (webProxy != DefaultWebProxySettings.Instance) { // Configure proxy server websocket.Options.Proxy = webProxy; if (Logging.IsEnabled) { Logging.Info(this, $"{nameof(CreateClientWebSocketAsync)} Setting ClientWebSocket.Options.Proxy"); } } } catch (PlatformNotSupportedException) { // .NET Core 2.0 doesn't support WebProxy configuration - ignore this setting. if (Logging.IsEnabled) { Logging.Error(this, $"{nameof(CreateClientWebSocketAsync)} PlatformNotSupportedException thrown as .NET Core 2.0 doesn't support proxy"); } } if (TransportSettings.Certificate != null) { websocket.Options.ClientCertificates.Add(TransportSettings.Certificate); } // Attempt to set a certificate validation callback if underlying WebSocket options instance supports it. // Otherwise, a global certificate validator will be used. if (TransportSettings.CertificateValidationCallback != null) { var prop = websocket.Options.GetType().GetProperty("RemoteCertificateValidationCallback"); if (prop != null) { if (Logging.IsEnabled) { Logging.Info(this, $"{nameof(CreateClientWebSocketAsync)} Setting ClientWebSocket.Options.RemoteCertificateValidationCallback"); } prop.SetValue(websocket.Options, TransportSettings.CertificateValidationCallback); } } using (var cancellationTokenSource = new CancellationTokenSource(timeout)) { await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token).ConfigureAwait(false); } return(websocket); }
public Client(NetworkCredential credential = null, TimeSpan?uploadTimeout = null, IWebProxy proxy = null) { var handler = new HttpClientHandler(); if (proxy != null && handler.SupportsProxy) { handler.Proxy = proxy; } if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; } if (credential != null) { handler.Credentials = credential; handler.PreAuthenticate = true; } _client = new HttpClient(handler); _client.DefaultRequestHeaders.ExpectContinue = false; if (uploadTimeout != null) { _uploadClient = new HttpClient(handler); _uploadClient.DefaultRequestHeaders.ExpectContinue = false; _uploadClient.Timeout = uploadTimeout.Value; } }
public FakeServiceWithFailedAddLogItemMethod(Uri uri, string project, string password, IWebProxy proxy) : base(uri, project, password, proxy) { }
public static Bitmap DownloadImage(string imageUrl, byte[] postBytes, IWebProxy proxy) { try { HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(imageUrl); wReq.Method = "POST"; if (proxy != null) { wReq.Proxy = proxy; } if (postBytes != null) { wReq.ContentLength = postBytes.Length; try { Stream postStream = wReq.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); postStream.Flush(); postStream.Close(); } catch (Exception e) { //log("[email protected]_ServletExec:\n"+e.Message,""); LastErrorMessage = e.Message; return(null); } } HttpWebResponse wresp = (HttpWebResponse)wReq.GetResponse(); int Bytes2Read = 3500000; Byte[] b = new Byte[Bytes2Read]; DateTime t1 = DateTime.Now; Stream stream = wresp.GetResponseStream(); MemoryStream memStream = new MemoryStream(); while (Bytes2Read > 0) { int len = stream.Read(b, 0, Bytes2Read); if (len == 0) { break; } memStream.Write(b, 0, len); } memStream.Position = 0; Bitmap bm = (Bitmap)Image.FromStream(memStream); memStream.Close(); memStream.Dispose(); return(bm); } catch (Exception ex) { LastErrorMessage = ex.Message; return(null); } }
/// <summary> /// Verifies whether the user's response to the recaptcha request is correct. /// </summary> /// <returns>Returns the result as a value of the <see cref="RecaptchaVerificationResult"/> enum.</returns> public Task <RecaptchaVerificationResult> VerifyRecaptchaResponseTaskAsync() { if (string.IsNullOrEmpty(_Challenge)) { return(FromTaskResult <RecaptchaVerificationResult>(RecaptchaVerificationResult.ChallengeNotProvided)); } if (string.IsNullOrEmpty(Response)) { return(FromTaskResult <RecaptchaVerificationResult>(RecaptchaVerificationResult.NullOrEmptyCaptchaSolution)); } Task <RecaptchaVerificationResult> result = Task <RecaptchaVerificationResult> .Factory.StartNew(() => { string privateKey = RecaptchaKeyHelper.ParseKey(PrivateKey); string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", privateKey, this.UserHostAddress, this._Challenge, this.Response); byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData); Uri verifyUri = null; if (!UseSsl) { verifyUri = new Uri("http://www.google.com/recaptcha/api/verify", UriKind.Absolute); } else { verifyUri = new Uri("https://www.google.com/recaptcha/api/verify", UriKind.Absolute); } try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(verifyUri); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = postDataBuffer.Length; webRequest.Method = "POST"; IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; webRequest.Proxy = proxy; Stream requestStream = webRequest.GetRequestStream(); requestStream.Write(postDataBuffer, 0, postDataBuffer.Length); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); string[] responseTokens = null; using (StreamReader sr = new StreamReader(webResponse.GetResponseStream())) { responseTokens = sr.ReadToEnd().Split('\n'); } if (responseTokens.Length == 2) { Boolean success = responseTokens[0].Equals("true", StringComparison.CurrentCulture); if (success) { return(RecaptchaVerificationResult.Success); } else { if (responseTokens[1].Equals("incorrect-captcha-sol", StringComparison.CurrentCulture)) { return(RecaptchaVerificationResult.IncorrectCaptchaSolution); } else if (responseTokens[1].Equals("invalid-site-private-key", StringComparison.CurrentCulture)) { return(RecaptchaVerificationResult.InvalidPrivateKey); } else if (responseTokens[1].Equals("invalid-request-cookie", StringComparison.CurrentCulture)) { return(RecaptchaVerificationResult.InvalidCookieParameters); } } } return(RecaptchaVerificationResult.UnknownError); } catch (Exception ex) { throw ex; } }); return(result); }
public static byte[] DownloadRaw(string url, IWebProxy proxy) { return(DownloadRaw(url, null, proxy, null, String.Empty, String.Empty)); }
public static MemoryStream DownloadStream(string url, IWebProxy proxy, ICredentials credentials) { return(DownloadStream(url, proxy, credentials, String.Empty, String.Empty)); }
public static string DownloadXml(string url, IWebProxy proxy) { return(DownloadXml(url, proxy, String.Empty, String.Empty)); }
//Fonction: On telecharge un flux XML qui indique les périphériques + infos du poste public void DownloadXML() { Program.LogFich.Info("[PeripheriqueManager] DownloadXML() - [DEBUT] Telechargement xml [" + Functions.getHost() + "]"); string getVars = "?machine=" + Functions.getHost(); string adresse = url.ToString() + getVars; Program.LogFich.Info("URL=" + adresse); string nomfichier; string[] tmp; tmp = url.ToString().Split('/'); nomfichier = tmp[tmp.Length - 3]; //-----------xml telechargement------------------ string stringHtml = null; try { if (!SandBox.Properties.Settings.Default.cookieHttpOnly) { WebClient wc = new WebClient(); //wc.UseDefaultCredentials = true; wc.Credentials = CredentialCache.DefaultNetworkCredentials; // Proxy IWebProxy wp = WebRequest.GetSystemWebProxy(); wp.Credentials = CredentialCache.DefaultNetworkCredentials; wc.Proxy = wp; var cookies = webBrowser.Document.Cookie; wc.Headers.Add(HttpRequestHeader.Cookie, cookies); stringHtml = wc.DownloadString(adresse); wc.Dispose(); } else { Uri urlTemp = webBrowser.Url; main_form.pageready = false; webBrowser.Navigate(adresse); //await main_form.PageLoad(10); //main_form.WaitForPageLoad(); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); //System.Threading.Thread.Sleep(100); } ; stringHtml = webBrowser.Document.Body.InnerText; //webBrowser.Navigate(urlTemp); } } catch (WebException we) { Program.LogFich.Error(we.ToString()); //MessageBox.Show(we.Message); return; } try { XmlDocument xml = new System.Xml.XmlDocument(); string clearXml = stringHtml; if (SandBox.Properties.Settings.Default.cookieHttpOnly) { clearXml = stringHtml.Replace(" <", "<").Replace("\r\n-", "").Replace("\r\n", "").Substring(stringHtml.IndexOf("?>") + 1).Trim(); } xml.LoadXml(clearXml); xml.Save(Environment.ExpandEnvironmentVariables("%TEMP%\\") + nomfichier + "_devices.xml"); } catch (Exception e) { Program.LogFich.Error(e.ToString()); MessageBox.Show(e.Message); } //-----------test xml local------------------- adresse = Environment.ExpandEnvironmentVariables("%TEMP%\\") + nomfichier + "_devices.xml"; try { //reader = new XmlTextReader(adresse); XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.CloseInput = true; reader = XmlReader.Create(adresse, xmlSettings); Program.LogFich.Info("[PeripheriqueManager] DownloadXML() - [FIN] Telechargement xml termine"); } catch (Exception e) { Program.LogFich.Info("[PeripheriqueManager] DownloadXML() - [FIN] Erreur de Telechargement" + e.ToString()); //DownloadXML(); MessageBox.Show(e.Message); } }
public static MemoryStream DownloadStream(string url, IWebProxy proxy) { return(DownloadStream(url, proxy, null)); }
public RESTClient <RS, ERS> Proxy(IWebProxy webProxy) { this.webProxy = webProxy; return(this); }
public SlackTaskClient(string token, IWebProxy proxySettings) : base(proxySettings) { APIToken = token; }
public static byte[] DownloadRaw(string url, byte[] postBytes, IWebProxy proxy, ICredentials credentials, string usr, string pwd) { try { HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(url); wReq.Credentials = credentials; if (proxy != null) { wReq.Proxy = proxy; } AppendAuthentification(wReq, usr, pwd); if (postBytes != null) { wReq.Method = "POST"; wReq.ContentLength = postBytes.Length; try { Stream postStream = wReq.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); postStream.Flush(); postStream.Close(); } catch (Exception e) { //log("[email protected]_ServletExec:\n"+e.Message,""); LastErrorMessage = e.Message; return(null); } } else { wReq.ContentLength = 0; } HttpWebResponse wresp = (HttpWebResponse)wReq.GetResponse(); int Bytes2Read = 3500000; Byte[] b = new Byte[Bytes2Read]; DateTime t1 = DateTime.Now; Stream stream = wresp.GetResponseStream(); MemoryStream memStream = new MemoryStream(); while (Bytes2Read > 0) { int len = stream.Read(b, 0, Bytes2Read); if (len == 0) { break; } memStream.Write(b, 0, len); } memStream.Position = 0; byte[] bytes = new byte[memStream.Length]; memStream.Read(bytes, 0, (int)memStream.Length); return(bytes); } catch (Exception ex) { LastErrorMessage = ex.Message; throw ex; //return null; } }
public async Task MultiProxy_PAC_Failover_Succeeds() { if (IsWinHttpHandler) { // PAC-based failover is only supported on Windows/SocketsHttpHandler return; } // Create our failing proxy server. // Bind a port to reserve it, but don't start listening yet. The first Connect() should fail and cause a fail-over. using Socket failingProxyServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); failingProxyServer.Bind(new IPEndPoint(IPAddress.Loopback, 0)); var failingEndPoint = (IPEndPoint)failingProxyServer.LocalEndPoint; using LoopbackProxyServer succeedingProxyServer = LoopbackProxyServer.Create(); string proxyConfigString = $"{failingEndPoint.Address}:{failingEndPoint.Port} {succeedingProxyServer.Uri.Host}:{succeedingProxyServer.Uri.Port}"; // Create a WinInetProxyHelper and override its values with our own. object winInetProxyHelper = Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.WinInetProxyHelper", true), true); winInetProxyHelper.GetType().GetField("_autoConfigUrl", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); winInetProxyHelper.GetType().GetField("_autoDetect", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, false); winInetProxyHelper.GetType().GetField("_proxy", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, proxyConfigString); winInetProxyHelper.GetType().GetField("_proxyBypass", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); // Create a HttpWindowsProxy with our custom WinInetProxyHelper. IWebProxy httpWindowsProxy = (IWebProxy)Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.HttpWindowsProxy", true), Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance, null, new[] { winInetProxyHelper, null }, null); Task <bool> nextFailedConnection = null; // Run a request with that proxy. Task requestTask = LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using HttpClientHandler handler = CreateHttpClientHandler(); using HttpClient client = CreateHttpClient(handler); handler.Proxy = httpWindowsProxy; // First request is expected to hit the failing proxy server, then failover to the succeeding proxy server. Assert.Equal("foo", await client.GetStringAsync(uri)); // Second request should start directly at the succeeding proxy server. // So, start listening on our failing proxy server to catch if it tries to connect. failingProxyServer.Listen(1); nextFailedConnection = WaitForNextFailedConnection(); Assert.Equal("bar", await client.GetStringAsync(uri)); }, async server => { await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "foo"); await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "bar"); }); // Wait for request to finish. await requestTask; // Triggers WaitForNextFailedConnection to stop, and then check // to ensure we haven't got any further requests against it. failingProxyServer.Dispose(); Assert.False(await nextFailedConnection); Assert.Equal(2, succeedingProxyServer.Requests.Count); async Task <bool> WaitForNextFailedConnection() { try { (await failingProxyServer.AcceptAsync()).Dispose(); return(true); } catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted) { // Dispose() of the loopback server will cause AcceptAsync() in EstablishConnectionAsync() to abort. return(false); } } }