public CachingProxy(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory, IOptions <CachingProxyConfig> config, ProxyHttpClient httpClient) { myLogger = loggerFactory.CreateLogger(GetType().FullName); myLogger.LogWarning("Initialising. Config:\n" + config.Value); myNext = next; myHttpClient = httpClient; myMinimumFreeDiskSpaceMb = config.Value.MinimumFreeDiskSpaceMb; myLocalCachePath = config.Value.LocalCachePath; if (myLocalCachePath == null) { throw new ArgumentNullException("", "LocalCachePath could not be null"); } if (!Directory.Exists(myLocalCachePath)) { throw new ArgumentException("LocalCachePath doesn't exist: " + myLocalCachePath); } myRemoteServers = new RemoteServers(config.Value.Prefixes.ToList(), config.Value.ContentTypeValidationPrefixes.ToList()); foreach (var remoteServer in myRemoteServers.Servers) { // force reconnection (and DNS re-resolve) every two minutes ServicePointManager.FindServicePoint(remoteServer.RemoteUri).ConnectionLeaseTimeout = 120000; } myContentTypeProvider = new FileExtensionContentTypeProvider(); myCacheFileProvider = new CacheFileProvider(myLocalCachePath); var staticFileOptions = new StaticFileOptions { FileProvider = myCacheFileProvider, ServeUnknownFileTypes = true, HttpsCompression = HttpsCompressionMode.DoNotCompress, ContentTypeProvider = myContentTypeProvider, OnPrepareResponse = ctx => { SetStatusHeader(ctx.Context, CachingProxyStatus.HIT); AddEternalCachingControl(ctx.Context); } }; myStaticFileMiddleware = new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory); myBlacklistRegex = !string.IsNullOrWhiteSpace(config.Value.BlacklistUrlRegex) ? new Regex(config.Value.BlacklistUrlRegex, RegexOptions.Compiled) : null; myRedirectToRemoteUrlsRegex = !string.IsNullOrWhiteSpace(config.Value.RedirectToRemoteUrlsRegex) ? new Regex(config.Value.RedirectToRemoteUrlsRegex, RegexOptions.Compiled) : null; }
/// <summary> /// Creates the TLS stream. /// </summary> /// <param name="uri">The URI.</param> /// <param name="underlyingStream">The underlying stream.</param> /// <returns></returns> public static NetworkStream CreateTlsStream(Uri uri, Stream underlyingStream) { // public TlsStream(string destinationHost, NetworkStream networkStream, // X509CertificateCollection clientCertificates, ServicePoint servicePoint, // object initiatingRequest, ExecutionContext executionContext) var networkStream = (NetworkStream)underlyingStream; var servicePoint = ServicePointManager.FindServicePoint(uri); ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; return((NetworkStream)Activator.CreateInstance(TlsStreamType, uri.Host, networkStream, null, servicePoint, null, null)); }
static public void Initialize() { ServicePointManager.SetTcpKeepAlive(true,30000,30000); client = new TcpClient(); client.Connect(CONN_STRING,10100); isConnected = true; NetworkStream stream = client.GetStream(); stream.BeginRead(readBytes,0,readBytes.Length,new AsyncCallback(ReadAsync),stream); }
public override void ConfigureServicePointManager() { try { ServicePoint = ServicePointManager.FindServicePoint(new Uri(Identifier)); ServicePoint.ConnectionLimit = Settings.MaxConcurrentTranslations; } catch { } }
public AzureStorageService(IConfigService configService) { _configService = configService; var connectionString = _configService.AzureWebJobsStorage; _cloudStorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString); ServicePointManager.FindServicePoint(_cloudStorageAccount.QueueEndpoint).UseNagleAlgorithm = false; ServicePointManager.FindServicePoint(_cloudStorageAccount.TableEndpoint).UseNagleAlgorithm = false; _cloudQueues = new Dictionary <string, CloudQueue>(); _cloudTables = new Dictionary <string, CloudTable>(); }
public DownloadService(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("OpenWeatherApi"); _dataDirectory = Environment.GetEnvironmentVariable("DATA_DIRECTORY"); _endpoint = Environment.GetEnvironmentVariable("WEATHER_API_ENDPOINT"); _endpointAuthorization = Environment.GetEnvironmentVariable("WEATHER_API_ENDPOINT_KEY"); _maxConcurrency = Convert.ToInt32(Environment.GetEnvironmentVariable("MAX_CONCURRENCY")); _semaphore = new SemaphoreSlim(_maxConcurrency); ServicePointManager.FindServicePoint(new Uri(_endpoint)).ConnectionLimit = _maxConcurrency; }
public OAuthManager(IHttpListenerManager listenerManager, DesktopConsumer consumer, MessageReceivingEndpoint serviceEndPoint) { _listenerManager = listenerManager; _consumer = consumer; _serviceEndPoint = serviceEndPoint; // Trying to fix https://github.com/flickr-downloadr/flickr-downloadr-gtk/issues/15 // From the comment in this SO answer: // http://stackoverflow.com/questions/1186682/expectation-failed-when-trying-to-update-twitter-status/2025073#2025073 ServicePointManager.FindServicePoint(_serviceEndPoint.Location).Expect100Continue = false; }
private void InitTableAccess(CloudStorageAccount storageAccount, string tableName) { _storageAccount = storageAccount; TableServicePoint = ServicePointManager.FindServicePoint(_storageAccount.TableEndpoint); TableServicePoint.UseNagleAlgorithm = false; TableServicePoint.Expect100Continue = false; TableServicePoint.ConnectionLimit = 500; var tableClient = storageAccount.CreateCloudTableClient(); _table = tableClient.GetTableReference(tableName); }
private static void SetServicePointProperties(Uri uri) { var servicePoint = ServicePointManager.FindServicePoint(uri); var idleTimeMilliSeconds = 2 * 60 * 60 * 1000; servicePoint.MaxIdleTime = idleTimeMilliSeconds; servicePoint.ConnectionLimit = 50; servicePoint.SetTcpKeepAlive(true, idleTimeMilliSeconds, 10_000); }
protected HttpClient ConfigureHttpClient() { #if BCL45 var httpMessageHandler = new WebRequestHandler(); if (this.Config.ReadWriteTimeout.HasValue) { // ReadWriteTimeout value is set to ClientConfig.MaxTimeout for S3 and Glacier. // Use default value (300 seconds) for other services. httpMessageHandler.ReadWriteTimeout = (int)this.Config.ReadWriteTimeout.Value.TotalMilliseconds; } #else var httpMessageHandler = new HttpClientHandler(); #endif #if BCL // Make one time configuration changes to the service point if (!configuredServicePoint) { lock (SERVICE_POINT_LOCK) { var point = ServicePointManager.FindServicePoint(this.Config.DetermineServiceURL(), httpMessageHandler.Proxy); if (point != null) { point.ConnectionLimit = this.Config.ConnectionLimit; point.UseNagleAlgorithm = this.Config.UseNagleAlgorithm; point.MaxIdleTime = this.Config.MaxIdleTime; } configuredServicePoint = true; } } if (this.Config.ProxyHost != null && this.Config.ProxyPort != 0) { WebProxy proxy = new WebProxy(this.Config.ProxyHost, this.Config.ProxyPort); httpMessageHandler.Proxy = proxy; } #endif if (httpMessageHandler.Proxy != null && Config.ProxyCredentials != null) { httpMessageHandler.Proxy.Credentials = Config.ProxyCredentials; } var httpClient = new HttpClient(httpMessageHandler); if (this.Config.Timeout.HasValue) { // Timeout value is set to ClientConfig.MaxTimeout for S3 and Glacier. // Use default value (100 seconds) for other services. httpClient.Timeout = this.Config.Timeout.Value; } // Disable the Expect 100-continue header httpClient.DefaultRequestHeaders.ExpectContinue = false; return(httpClient); }
private static void setServicePoint(Uri uri) { ServicePoint serverPoint = ServicePointManager.FindServicePoint(uri); // 設定 30 秒沒有活動即關閉連線,預設 -1 (永不關閉) serverPoint.ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; // 停用 100-Continue // https://docs.microsoft.com/zh-tw/dotnet/api/system.net.servicepointmanager.expect100continue?view=netstandard-2.0 serverPoint.Expect100Continue = false; }
protected void SetupServicePoints(params string[] endpoints) { _servicePoints = new ServicePoint[endpoints.Length]; for (int i = 0; i < endpoints.Length; i++) { var endpoint = endpoints[i]; var servicePoint = ServicePointManager.FindServicePoint(new Uri(endpoint)); _servicePoints[i] = servicePoint; } }
public static IDisposable Expect100Continue(Uri uri) { #if !DNXCORE50 var servicePoint = ServicePointManager.FindServicePoint(uri); servicePoint.Expect100Continue = true; return(new DisposableAction(() => servicePoint.Expect100Continue = false)); #else // TODO [ppekrol] How to do it now? return(new DisposableAction(() => { })); #endif }
public override void ConfigureServicePointManager() { try { ServicePoint = ServicePointManager.FindServicePoint(new Uri("https://translate.google.com")); ServicePoint.ConnectionLimit = Settings.MaxConcurrentTranslations; } catch { } }
private void SetThrottling() { this.logger.LogTrace("()"); Helper.SetThrottling(); ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(Configuration.TableClient.BaseUri); tableServicePoint.ConnectionLimit = 1000; this.logger.LogTrace("(-)"); }
private void SetConnectionLimits(Uri url) { var servicePoint = ServicePointManager.FindServicePoint(url); if (servicePoint != null) { servicePoint.ConnectionLimit = NumberOfConcurrentTransfers * ParallelTransferThreadCount; servicePoint.ConnectionLeaseTimeout = (int)_connectionTimeout.TotalMilliseconds; servicePoint.MaxIdleTime = (int)_connectionTimeout.TotalMilliseconds; } }
public override void ConfigureServicePointManager() { try { ServicePoint = ServicePointManager.FindServicePoint(new Uri(Identifier)); ServicePoint.ConnectionLimit = 100; } catch { } }
private void DownloadsSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e) { var newValue = Convert.ToInt32(e.NewValue); ServicePointManager.DefaultConnectionLimit = newValue; foreach (var i in ItemList) { var sp = ServicePointManager.FindServicePoint(new Uri(i.Url)); sp.ConnectionLimit = newValue; } }
private async Task <HtmlDocument> GetHtmlDocument() { var result = new HtmlDocument(); var stream = await _client.GetStreamAsync(Url); var manager = ServicePointManager.FindServicePoint(new Uri(new Uri(Url).GetLeftPart(UriPartial.Authority))); manager.ConnectionLeaseTimeout = 5 * 60 * 1000; result.Load(stream, Encoding.Default); return(result); }
public TableStorageWriter(string tableName) { this.tableName = tableName; var cs = CloudConfigurationManager.GetSetting("StorageConnectionString"); storageAccount = CloudStorageAccount.Parse(cs); ServicePointManager.FindServicePoint(storageAccount.TableEndpoint).UseNagleAlgorithm = false; operations = new ConcurrentQueue <Tuple <ITableEntity, TableOperation> >(); }
public RollbarDeployClient(RollbarConfig config, HttpClient httpClient = null) { Assumption.AssertNotNull(config, nameof(config)); this._config = config; this._httpClient = httpClient; var sp = ServicePointManager.FindServicePoint(new Uri(this._config.EndPoint)); sp.ConnectionLeaseTimeout = 60 * 1000; // 1 minute }
public void Stop() { SampleEventSourceWriter.Log.MessageMethod("Stopping Server."); for (int i = clients.Count(); i > 0; i--) { clients.ElementAt(i).getClient().Dispose(); } clients.Clear(); drawingClient = null; listener.Stop(); ServicePointManager.SetTcpKeepAlive(false,30000,30000); }
static DataProviderService() { // We need to not use an expect header as it causes problems when sending data to a REST service var profileUri = new Uri("http://api.eddp.co/profile"); var profileServicePoint = ServicePointManager.FindServicePoint(profileUri); profileServicePoint.Expect100Continue = false; var errorUri = new Uri("http://api.eddp.co/error"); var errorServicePoint = ServicePointManager.FindServicePoint(errorUri); errorServicePoint.Expect100Continue = false; }
static QueueTrigger() { httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(Aladin.Const.Domain); string accessToken = Environment.GetEnvironmentVariable("LINE_COMICS_ACCESS_TOKEN"); lineMessagingClient = new LineMessagingClient(accessToken); var sp = ServicePointManager.FindServicePoint(new Uri("https://api.line.me")); sp.ConnectionLeaseTimeout = 60 * 1000; }
public override void ActivateOptions() { base.ActivateOptions(); _baseUrl = new Uri(Url); ServicePointManager.FindServicePoint(_baseUrl).Expect100Continue = false; if (!string.IsNullOrEmpty(User) && !string.IsNullOrEmpty(Password)) { _credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(User + ":" + Password)); } }
public void TestBadCertificateHandler() { var ran = false; ServerInterface.SetBadCertificateHandler(_ => { ran = true; return(true); }); ServicePointManager.ServerCertificateValidationCallback(this, new System.Security.Cryptography.X509Certificates.X509Certificate(), new System.Security.Cryptography.X509Certificates.X509Chain(), System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors); Assert.IsTrue(ran); }
public string SwapForFreshConnection(string name, string url) { ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri(url)); try { servicePoint.CloseConnectionGroup(name); } catch (NotImplementedException) { // Workaround for Mono } return(GetConnectionGroupName()); }
private HttpClient InitClient() { var uri = new Uri(Config.Url); //http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/ var sp = ServicePointManager.FindServicePoint(uri); sp.ConnectionLeaseTimeout = 60 * 1000; return(new HttpClient { BaseAddress = uri }); }
protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; // Close all connection groups created by the current handler instance. Since every instance uses a // unique connection group name, disposing a handler will remove all these unique connection groups to // save resources. ServicePointManager.CloseConnectionGroups(_connectionGroupName); } base.Dispose(disposing); }
public void When_sending_a_request() { var endpoint = new Uri("http://foo.org/api"); ServicePointManager.FindServicePoint(endpoint).ConnectionLeaseTimeout.ShouldBe(-1); using IRestClient client = new RestClient(); client.SendAsync(new HttpRequestMessage(HttpMethod.Get, endpoint)); ServicePointManager.FindServicePoint(endpoint).ConnectionLeaseTimeout .ShouldBe(-1); }