Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Example #1
0
        private static HttpClient GetDefaultClient()
        {
            if (s_DefaultHttpClient == null)
            {
                var handler = new System.Net.Http.HttpClientHandler();
                try
                {
                    if (handler.SupportsAutomaticDecompression)
                    {
                        handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
                    }

                    s_DefaultHttpClient = new HttpClient(handler);
                }
                catch
                {
                    if (handler != null)
                    {
                        handler.Dispose();
                    }

                    throw;
                }
            }

            return(s_DefaultHttpClient);
        }
Example #2
0
        public bool StartUpload(string fileName,int assetId)
        {
            var handler = new HttpClientHandler() { UseDefaultCredentials = true };
            string url = "http://c0040597.itcs.hp.com:7860/Report/Upload";
            HttpClient client = new HttpClient(handler);

            MultipartFormDataContent form = new MultipartFormDataContent();
            form.Add(new StringContent(assetId.ToString()), "asset");
            byte[] fileContent = File.ReadAllBytes(fileName);

            form.Add(new ByteArrayContent(fileContent), "file", fileName);
            var task = client.PostAsync(url, form);

            task.Wait();
            var response = task.Result;

            client.Dispose();
            handler.Dispose();
            if (response.IsSuccessStatusCode)
                return true;
            return false;
        }
Example #3
0
    public static void DeCompressionTest(string url)
    {
        var clientHandler = new HttpClientHandler();
        clientHandler.AutomaticDecompression = DecompressionMethods.None;
        //clientHandler.AutomaticDecompression = DecompressionMethods.Deflate;
        clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        var httpClient = new HttpClient(clientHandler);
        httpClient.MaxResponseContentBufferSize = 256000;
        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        try{
        var responseTask = httpClient.GetAsync(url);
        responseTask.Wait();
            HttpResponseMessage response = responseTask.Result;
            response.EnsureSuccessStatusCode();

        if(response.Content != null) {
        var readTask = response.Content.ReadAsStringAsync();
        readTask.Wait();
        Console.WriteLine("*****");
        Console.WriteLine(readTask.Result);
        }
        else
        {
        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
        }
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
            return ;
        }
        finally{
        Console.WriteLine("disposing");
        clientHandler.Dispose();
        httpClient.Dispose();
        }
        return;
    }
Example #4
0
		private static HttpClient InitializeHttpClient(TimeSpan timeout)
		{
			HttpClient httpClient;
			var httpHandler = new HttpClientHandler();

			try
			{
				httpHandler.AllowAutoRedirect = false;
				httpHandler.MaxRequestContentBufferSize = 1024;
				httpHandler.UseCookies = false;
				httpHandler.UseDefaultCredentials = false;

				httpClient = new HttpClient(httpHandler, true);
			}
			catch
			{
				httpHandler.Dispose();
				throw;
			}

			httpClient.DefaultRequestHeaders.UserAgent.Clear();
			httpClient.DefaultRequestHeaders.UserAgent.Add(GetUserAgent());
			httpClient.Timeout = timeout;
			httpClient.MaxResponseContentBufferSize = 1024;
			return httpClient;
		}
Example #5
0
        public async Task<MultipartUploadResult> MultipartUpload(MultiUploadRequestData multiUploadObject,
            Action<HttpProcessData> uploadProcessCallback = null, CancellationToken? cancellationToken = null)
        {
            MultipartUploadResult result = null;

            HttpClientHandler hand = null;
           // ProgressMessageHandler processMessageHander = null;
            HttpClient localHttpClient = null;
            OssHttpRequestMessage httpRequestMessage = null;
            HttpResponseMessage response = null;

            try
            {
                hand = new HttpClientHandler();
              //  processMessageHander = new ProgressMessageHandler(hand);
                localHttpClient = new HttpClient();
                localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour); 

                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("partNumber", multiUploadObject.PartNumber);
                parameters.Add("uploadId", multiUploadObject.UploadId);

                httpRequestMessage = new OssHttpRequestMessage(multiUploadObject.Bucket, multiUploadObject.Key, parameters);

                httpRequestMessage.Method = HttpMethod.Put;
                httpRequestMessage.Headers.Date = DateTime.UtcNow;
                httpRequestMessage.Content = new StreamContent(multiUploadObject.Content);

                //if (uploadProcessCallback != null)
                //{
                //    processMessageHander.HttpSendProgress += (sender, e) =>
                //    {
                //        uploadProcessCallback(new HttpProcessData()
                //        {
                //            TotalBytes = e.TotalBytes,
                //            BytesTransferred = e.BytesTransferred,
                //            ProgressPercentage = e.ProgressPercentage
                //        });

                //    };
                //}


                OssRequestSigner.Sign(httpRequestMessage, networkCredential);

                if (cancellationToken != null)
                    response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
                else
                    response = await localHttpClient.SendAsync(httpRequestMessage);

                if (response.IsSuccessStatusCode == false)
                {
                    await ErrorResponseHandler.Handle(response);
                }
                var deseserializer = DeserializerFactory.GetFactory().CreateMultipartUploadDeserializer();
                result = deseserializer.Deserialize(response);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (hand != null)
                    hand.Dispose();

                //if (processMessageHander != null)
                //    processMessageHander.Dispose();

                if (localHttpClient != null)
                    localHttpClient.Dispose();

                if (httpRequestMessage != null)
                    httpRequestMessage.Dispose();


                if (response != null)
                    response.Dispose();
            }
            return result;

        }
Example #6
0
        public async Task<OssObject> GetObject(GetObjectRequest getObjectRequest,
            Action<HttpProcessData> downloadProcessCallback = null, CancellationToken? cancellationToken = null)
        {

            OssObject result = null;

            HttpClientHandler hand = null;
          //  ProgressMessageHandler processMessageHander = null;
            HttpClient localHttpClient = null;
            OssHttpRequestMessage httpRequestMessage = null;
            HttpResponseMessage response = null;

            try
            {
                hand = new HttpClientHandler();
           //     processMessageHander = new ProgressMessageHandler(hand);
                localHttpClient = new HttpClient();
                localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour); 

                httpRequestMessage = new OssHttpRequestMessage(getObjectRequest.BucketName, getObjectRequest.Key);
                getObjectRequest.ResponseHeaders.Populate(httpRequestMessage.Headers);
                getObjectRequest.Populate(httpRequestMessage.Headers);

                httpRequestMessage.Method = HttpMethod.Get;
                httpRequestMessage.Headers.Date = DateTime.UtcNow;

                OssRequestSigner.Sign(httpRequestMessage, networkCredential);
                //if (downloadProcessCallback != null)
                //{
                //    processMessageHander.HttpReceiveProgress += (sender, e) =>
                //    {
                //        downloadProcessCallback(new HttpProcessData()
                //        {
                //            TotalBytes = e.TotalBytes,
                //            BytesTransferred = e.BytesTransferred,
                //            ProgressPercentage = e.ProgressPercentage
                //        }); ;

                //    };
                //}

                if (cancellationToken != null)
                    response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
                else
                    response = await localHttpClient.SendAsync(httpRequestMessage);


                if (response.IsSuccessStatusCode == false)
                {
                    await ErrorResponseHandler.Handle(response);
                }

                var temp = DeserializerFactory.GetFactory().CreateGetObjectResultDeserializer(getObjectRequest);
                result = await temp.Deserialize(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (hand != null)
                    hand.Dispose();

                //if (processMessageHander != null)
                //    processMessageHander.Dispose();

                if (localHttpClient != null)
                    localHttpClient.Dispose();

                if (httpRequestMessage != null)
                    httpRequestMessage.Dispose();
            }


            return result;   
        }
Example #7
0
        public async Task<PutObjectResult> PutObject(string bucketName, string key, Stream content, ObjectMetadata metadata, 
            Action<HttpProcessData> uploadProcessCallback = null, CancellationToken? cancellationToken = null)
        {
            PutObjectResult result = null;
            HttpClientHandler hand = null;
           // ProgressMessageHandler processMessageHander = null;
            HttpClient localHttpClient = null;
            OssHttpRequestMessage httpRequestMessage = null;
            HttpResponseMessage response = null;
            try
            {
                 hand = new HttpClientHandler();
            //     processMessageHander = new ProgressMessageHandler(hand);
                localHttpClient = new HttpClient();
                localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour); 
                 httpRequestMessage = new OssHttpRequestMessage(bucketName, key);



                httpRequestMessage.Method = HttpMethod.Put;
                httpRequestMessage.Headers.Date = DateTime.UtcNow;
                httpRequestMessage.Content = new StreamContent(content);


                OssClientHelper.initialHttpRequestMessage(httpRequestMessage, metadata);

                

                OssRequestSigner.Sign(httpRequestMessage, networkCredential);

                //if (uploadProcessCallback != null)
                //{
                //    processMessageHander.HttpSendProgress += (sender, e) =>
                //    {
                //        uploadProcessCallback(new HttpProcessData()
                //        {
                //            TotalBytes = e.TotalBytes,
                //            BytesTransferred = e.BytesTransferred,
                //            ProgressPercentage = e.ProgressPercentage
                //        });

                //    };
                //}

                
                if(cancellationToken != null)
                    response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
                else
                     response = await localHttpClient.SendAsync(httpRequestMessage);

                if (response.IsSuccessStatusCode == false)
                {
                    await ErrorResponseHandler.Handle(response);
                }

                var temp = DeserializerFactory.GetFactory().CreatePutObjectReusltDeserializer();
                result = temp.Deserialize(response);
                //localHttpClient.Dispose();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (hand != null)
                    hand.Dispose();

                //if (processMessageHander != null)
                //    processMessageHander.Dispose();

                if (localHttpClient != null)
                    localHttpClient.Dispose();

                if (httpRequestMessage != null)
                    httpRequestMessage.Dispose();


                if (response != null)
                    response.Dispose();
            }

            return result;

        }
Example #8
0
		private static HttpClient GetDefaultClient()
		{
			if (s_DefaultHttpClient == null)
			{
				var handler = new System.Net.Http.HttpClientHandler();
				try
				{
					if (handler.SupportsAutomaticDecompression)
						handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;

					s_DefaultHttpClient = new HttpClient(handler);
				}
				catch
				{
					if (handler != null)
						handler.Dispose();

					throw;
				}
			}

			return s_DefaultHttpClient;
		}
Example #9
0
		public void Disposed ()
		{
			var h = new HttpClientHandler ();
			h.Dispose ();
			var c = new HttpClient (h);
			try {
				c.GetAsync ("http://google.com").Wait ();
				Assert.Fail ("#1");
			} catch (AggregateException e) {
				Assert.IsTrue (e.InnerException is ObjectDisposedException, "#2");
			}
		}
Example #10
0
        /// <summary>
        /// Sends the specified text to be spoken to the TTS service and saves the response audio to a file.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Task</returns>
        public Task Speak(CancellationToken cancellationToken)
        {
            var cookieContainer = new CookieContainer();
            var handler = new HttpClientHandler() { CookieContainer = cookieContainer };
            var client = new HttpClient(handler);

            foreach (var header in this.inputOptions.Headers)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
            }

            var genderValue = "";
            switch (this.inputOptions.VoiceType)
            {
                case Gender.Male:
                    genderValue = "Male";
                    break;
                case Gender.Female:
                default:
                    genderValue = "Female";
                    break;

            }

            var request = new HttpRequestMessage(HttpMethod.Post, this.inputOptions.RequestUri)
            {
                Content = new StringContent(String.Format(SsmlTemplate, this.inputOptions.Locale, genderValue, this.inputOptions.VoiceName, this.inputOptions.Text))
            };

            var httpTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
            Console.WriteLine("Response status code: [{0}]", httpTask.Result.StatusCode);

            var saveTask = httpTask.ContinueWith(
                async (responseMessage, token) =>
                {
                    try
                    {
                        if (responseMessage.IsCompleted && responseMessage.Result != null && responseMessage.Result.IsSuccessStatusCode)
                        {

                            var httpStream = await responseMessage.Result.Content.ReadAsStreamAsync().ConfigureAwait(false);
                            this.AudioAvailable(new GenericEventArgs<Stream>(httpStream));
                        }
                        else
                        {
                            this.Error(new GenericEventArgs<Exception>(new Exception(String.Format("Service returned {0}", responseMessage.Result.StatusCode))));
                        }
                    }
                    catch (Exception e)
                    {
                        this.Error(new GenericEventArgs<Exception>(e.GetBaseException()));
                    }
                    finally
                    {
                        responseMessage.Dispose();
                        request.Dispose();
                        client.Dispose();
                        handler.Dispose();
                    }
                },
                TaskContinuationOptions.AttachedToParent,
                cancellationToken);

            return saveTask;
        }
Example #11
0
File: Hello.cs Project: kapilash/dc
    public static void DoProxyForUrl(string url)
    {
        var proxy = new MyProxyImpl("http://localhost:8394");
        var credential = new System.Net.NetworkCredential("skapila","blah","FAREAST");
        credential.UserName = "******";
        credential.Password = "******";
        credential.Domain = "FAREAST";
        proxy.Credentials = credential;

        var clientHandler = new HttpClientHandler();
        clientHandler.Proxy = proxy;
        clientHandler.UseProxy = true;
        var httpClient = new HttpClient(clientHandler);
        httpClient.MaxResponseContentBufferSize = 256000;
        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        try{
        var responseTask = httpClient.GetAsync(url);
        responseTask.Wait();
            HttpResponseMessage response = responseTask.Result;
        //            response.EnsureSuccessStatusCode();

        if(response.Content != null) {
        var readTask = response.Content.ReadAsStringAsync();
        readTask.Wait();
        Console.WriteLine(readTask.Result);
        }
        else
        {
        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
        }
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
        Console.WriteLine("disposing");
        clientHandler.Dispose();
        httpClient.Dispose();
        }
    }