コード例 #1
0
        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;
        }
コード例 #2
0
        /// <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));
        }
コード例 #3
0
ファイル: Client.cs プロジェクト: lmckamey/Group1Projects
        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);
        }
コード例 #4
0
 public override void ConfigureServicePointManager()
 {
     try
     {
         ServicePoint = ServicePointManager.FindServicePoint(new Uri(Identifier));
         ServicePoint.ConnectionLimit = Settings.MaxConcurrentTranslations;
     }
     catch
     {
     }
 }
コード例 #5
0
        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>();
        }
コード例 #6
0
        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;
        }
コード例 #7
0
 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;
 }
コード例 #8
0
        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);
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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;
        }
コード例 #12
0
        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;
            }
        }
コード例 #13
0
        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
        }
コード例 #14
0
 public override void ConfigureServicePointManager()
 {
     try
     {
         ServicePoint = ServicePointManager.FindServicePoint(new Uri("https://translate.google.com"));
         ServicePoint.ConnectionLimit = Settings.MaxConcurrentTranslations;
     }
     catch
     {
     }
 }
コード例 #15
0
        private void SetThrottling()
        {
            this.logger.LogTrace("()");

            Helper.SetThrottling();
            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(Configuration.TableClient.BaseUri);

            tableServicePoint.ConnectionLimit = 1000;

            this.logger.LogTrace("(-)");
        }
コード例 #16
0
        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;
            }
        }
コード例 #17
0
 public override void ConfigureServicePointManager()
 {
     try
     {
         ServicePoint = ServicePointManager.FindServicePoint(new Uri(Identifier));
         ServicePoint.ConnectionLimit = 100;
     }
     catch
     {
     }
 }
コード例 #18
0
        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;
            }
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        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> >();
        }
コード例 #21
0
        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
        }
コード例 #22
0
 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);
 }
コード例 #23
0
        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;
        }
コード例 #24
0
        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;
        }
コード例 #25
0
ファイル: GelfHttpAppender.cs プロジェクト: jonranes/gelf4net
        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));
            }
        }
コード例 #26
0
        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);
        }
コード例 #27
0
ファイル: Other.cs プロジェクト: jdpurcell/ChanThreadWatch
        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());
        }
コード例 #28
0
ファイル: SlooceApi.cs プロジェクト: steveadoo32/Slooce.NET
        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
            });
        }
コード例 #29
0
 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);
 }
コード例 #30
0
        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);
        }