Exemple #1
0
        /// <summary>
        /// Constructor.
        /// </summary>
        ///
        /// <param name="requestInfo">
        /// Information describing the request.
        /// </param>

        public WebRequestState(AsyncWebRequest requestInfo)
        {
            BufferRead = new byte[BufferSize];
            Request = requestInfo.Request;
            ResponseStreamAsync = null;
            RequestInfo = requestInfo;
        }
Exemple #2
0
        /// <summary>
        /// Constructor.
        /// </summary>
        ///
        /// <param name="requestInfo">
        /// Information describing the request.
        /// </param>

        public WebRequestState(AsyncWebRequest requestInfo)
        {
            BufferRead = new byte[BufferSize];
            RequestData = new StringBuilder(String.Empty);
            Request = requestInfo.Request;
            ResponseStream = null;
            RequestInfo = requestInfo;
        }
        internal HttpJsonInterpretor(IHttpWebRequest request)
        {
            if (request == null)
                throw new ArgumentNullException();

            _Request = request;

        }
 public void BeginClientMetricsRecord(IHttpWebRequest request, CallState callState)
 {
     if (callState != null && callState.AuthorityType == AuthorityType.AAD)
     {
         AddClientMetricsHeadersToRequest(request);
         metricsTimer = Stopwatch.StartNew();
     }            
 }
 private IHttpWebRequest Mature(IHttpWebRequest request)
 {
     request.Headers["Accept-Encoding"] = "gzip";
     if (string.IsNullOrEmpty(request.UserAgent))
         request.UserAgent = _UA;
     if (_TimeOut!=null)
         request.Timeout = _TimeOut.Value;
     return request;
 }
Exemple #6
0
        // Public members

        public static HttpStatusCode GetStatusCode(IHttpWebRequest httpWebRequest)
        {
            if (httpWebRequest is null)
            {
                throw new ArgumentNullException(nameof(httpWebRequest));
            }

            HttpStatusCode?statusCode    = null;
            WebException   lastException = null;

            bool   originalAllowAutoRedirect = httpWebRequest.AllowAutoRedirect;
            string originalMethod            = httpWebRequest.Method;

            httpWebRequest.AllowAutoRedirect = false;

            // Attempt to make a HEAD request first. If it fails, we'll fall back to making a GET request.

            foreach (string method in new[] { "HEAD", "GET" })
            {
                httpWebRequest.Method = method;

                try {
                    using (WebResponse webResponse = httpWebRequest.GetResponse())
                        statusCode = (webResponse as IHttpWebResponse)?.StatusCode;
                }
                catch (WebException ex) {
                    // ex.Response will be a regular HttpWebResponse instead of an IHttpWebResponse when the request fails.

                    using (WebResponse webResponse = ex.Response)
                        statusCode = (webResponse as HttpWebResponse)?.StatusCode;

                    lastException = ex;
                }

                if (statusCode.HasValue && statusCode != HttpStatusCode.MethodNotAllowed)
                {
                    break;
                }
            }

            // Restore original configuration.

            httpWebRequest.AllowAutoRedirect = originalAllowAutoRedirect;
            httpWebRequest.Method            = originalMethod;

            if (statusCode.HasValue)
            {
                return(statusCode.Value);
            }
            else
            {
                throw lastException ?? new Exception($"Unable to obtain HTTP status code from {httpWebRequest.RequestUri}.");
            }
        }
 protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
 {
     if (CanMakeAuthenticatedRequest(payload))
     {
         string form = CryptoUtility.GetFormForPayload(payload);
         request.AddHeader("Key", PublicApiKey.ToUnsecureString());
         request.AddHeader("Sign", CryptoUtility.SHA512Sign(form, PrivateApiKey.ToUnsecureString()));
         request.Method = "POST";
         await CryptoUtility.WriteToRequestAsync(request, form);
     }
 }
 public HttpWebHelperResult(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception exception, Exception innerException, bool isCancelled, bool completeSynchronsouly, Stream responseSaveStream, object state)
 {
     _httpWebRequest        = httpWebRequest;
     _httpWebResponse       = httpWebResponse;
     _exception             = exception;
     _innerException        = innerException;
     _isCancelled           = isCancelled;
     _completeSynchronsouly = completeSynchronsouly;
     _responseSaveStream    = responseSaveStream;
     _state = state;
 }
 public HttpWebHelperResult(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception exception, Exception innerException, bool isCancelled, bool completeSynchronsouly, Stream responseSaveStream, object state)
 {
     _httpWebRequest = httpWebRequest;
     _httpWebResponse = httpWebResponse;
     _exception = exception;
     _innerException = innerException;
     _isCancelled = isCancelled;
     _completeSynchronsouly = completeSynchronsouly;
     _responseSaveStream = responseSaveStream;
     _state = state;
 }
Exemple #10
0
        public async Task VerifyAnotherHostByInstanceDiscoveryAsync(string host, string tenant, CallState callState)
        {
            string instanceDiscoveryEndpoint = this.InstanceDiscoveryEndpoint;

            instanceDiscoveryEndpoint += ("?api-version=1.0&authorization_endpoint=" + AuthorizeEndpointTemplate);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{host}", host);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{tenant}", tenant);

            instanceDiscoveryEndpoint = HttpHelper.CheckForExtraQueryParameter(instanceDiscoveryEndpoint);

            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(instanceDiscoveryEndpoint);
                request.Method = "GET";
                HttpHelper.AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    HttpHelper.VerifyCorrelationIdHeaderInReponse(response, callState);
                    InstanceDiscoveryResponse discoveryResponse = HttpHelper.DeserializeResponse <InstanceDiscoveryResponse>(response);
                    clientMetrics.SetLastError(null);
                    if (discoveryResponse.TenantDiscoveryEndpoint == null)
                    {
                        throw new AdalException(AdalError.AuthorityNotInValidList);
                    }
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse.ErrorCodes);

                if (tokenResponse.Error == "invalid_instance")
                {
                    throw new AdalServiceException(AdalError.AuthorityNotInValidList, ex);
                }
                else
                {
                    throw new AdalServiceException(
                              AdalError.AuthorityValidationFailed,
                              string.Format(CultureInfo.InvariantCulture, "{0}. {1}: {2}", AdalErrorMessage.AuthorityValidationFailed, tokenResponse.Error, tokenResponse.ErrorDescription),
                              ex);
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.InstanceDiscovery, callState);
            }
        }
Exemple #11
0
 protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
 {
     // only authenticated requests write json, everything uses GET and url params
     if (CanMakeAuthenticatedRequest(payload))
     {
         request.AddHeader("Authorization", CryptoUtility.BasicAuthenticationString(PublicApiKey.ToUnsecureString(), PrivateApiKey.ToUnsecureString()));
         if (request.Method == "POST")
         {
             await CryptoUtility.WritePayloadJsonToRequestAsync(request, payload);
         }
     }
 }
Exemple #12
0
        private static string GetRequestPrettyPrint(RestRequest request, IHttpWebRequest httpWebRequest)
        {
            var requestPrettyPrint = httpWebRequest.ToString();

#if DEBUG
            if (request.Verb == HttpVerb.POST || request.Verb == HttpVerb.PUT)
            {
                requestPrettyPrint = string.Concat(requestPrettyPrint, string.Concat(Environment.NewLine, request.GetBody().JsonFormat()));
            }
#endif
            return(requestPrettyPrint);
        }
 /// <summary>
 /// Gets http response, returns (etag, data)
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 private SolrResponse GetResponse(IHttpWebRequest request)
 {
     using (var response = request.GetResponse()) {
         var etag         = response.Headers[HttpResponseHeader.ETag];
         var cacheControl = response.Headers[HttpResponseHeader.CacheControl];
         if (cacheControl != null && cacheControl.Contains("no-cache"))
         {
             etag = null; // avoid caching things marked as no-cache
         }
         return(new SolrResponse(etag, ReadResponseToString(response)));
     }
 }
        protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
        {
            var formData = await request.WritePayloadFormToRequestAsync(payload)
                           .ConfigureAwait(false);

            if (CanMakeAuthenticatedRequest(payload))
            {
                request.AddHeader("Rest-Key", PublicApiKey.ToUnsecureString());
                var signKey = GetSignKey(request, formData);
                request.AddHeader("Rest-Sign", signKey);
            }
        }
Exemple #15
0
        /// <summary>
        /// Initiates an asynchronous GET request from an IHttpWebRequest object.
        /// </summary>
        ///
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="success">
        /// A delegate that will be invoked with the response data structure upon successful resolution
        /// of the request.
        /// </param>
        /// <param name="fail">
        /// A delegate that will be invoked with the response data structure upon failure.
        /// </param>
        ///
        /// <returns>
        /// A ManualResetEvent object for this asynchronous operation.
        /// </returns>

        public ManualResetEvent GetAsync(IHttpWebRequest request, Action <ICsqWebResponse> success, Action <ICsqWebResponse> fail)
        {
            var requestInfo = new AsyncWebRequest(request);

            // do not apply options when using this method.

            requestInfo.Id = Id;
            requestInfo.CallbackSuccess = success;
            requestInfo.CallbackFail    = fail;

            return(requestInfo.GetAsync());
        }
Exemple #16
0
        public virtual void GetResponse(IHttpWebRequest request, string filename, bool streamResponse)
        {
            try
            {
                _response = request.GetResponse();
            }
            catch (WebException webException)
            {
                if (webException.Response == null)
                {
                    throw;
                }
                _response = new HttpWebResponseWrapper((HttpWebResponse)webException.Response);
            }

            GetHeaders();

            if (streamResponse)
            {
                return;
            }

            using (var stream = _response.GetResponseStream())
            {
                if (stream == null)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(filename))
                {
                    using (var filestream = new FileStream(filename, FileMode.CreateNew))
                    {
                        int count;
                        var buffer = new byte[8192];

                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            filestream.Write(buffer, 0, count);
                        }
                    }
                }
                else
                {
                    var encoding = string.IsNullOrEmpty(CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(CharacterSet);
                    using (var reader = new StreamReader(stream, encoding))
                    {
                        RawText = reader.ReadToEnd();
                    }
                }
            }
        }
Exemple #17
0
        public static bool TryGetRemoteFileSize(IHttpWebRequest httpWebRequest, out long fileSize)
        {
            try {
                fileSize = GetRemoteFileSize(httpWebRequest);

                return(true);
            }
            catch (WebException) {
                fileSize = default;

                return(false);
            }
        }
 private async Task <SolrResponse> GetResponseAsync(IHttpWebRequest request)
 {
     using (var response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null))
     {
         var etag         = response.Headers[HttpResponseHeader.ETag];
         var cacheControl = response.Headers[HttpResponseHeader.CacheControl];
         if (cacheControl != null && cacheControl.Contains("no-cache"))
         {
             etag = null; // avoid caching things marked as no-cache
         }
         return(new SolrResponse(etag, await ReadResponseToStringAsync(response)));
     }
 }
Exemple #19
0
        public static bool TryGetStatusCode(IHttpWebRequest httpWebRequest, out HttpStatusCode statusCode)
        {
            try {
                statusCode = GetStatusCode(httpWebRequest);

                return(true);
            }
            catch (WebException) {
                statusCode = default;

                return(false);
            }
        }
Exemple #20
0
 protected override Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
 {
     if (CanMakeAuthenticatedRequest(payload))
     {
         request.AddHeader("X-MBX-APIKEY", PublicApiKey.ToUnsecureString());
     }
     // Needed in order to get listening key
     if (payload == null && request.RequestUri.AbsoluteUri.Contains("userDataStream"))
     {
         request.AddHeader("X-MBX-APIKEY", PublicApiKey.ToUnsecureString());
     }
     return(base.ProcessRequestAsync(request, payload));
 }
Exemple #21
0
        protected sealed internal override WebResponse Send(WebRequest request, CancellationToken cancellationToken)
        {
            IHttpWebRequest httpWebRequest = request.AsHttpWebRequest();

            if (httpWebRequest is null)
            {
                return(base.Send(request, cancellationToken));
            }
            else
            {
                return((WebResponse)Send(httpWebRequest, cancellationToken));
            }
        }
Exemple #22
0
        public static bool TryGetRemoteDateTime(IHttpWebRequest httpWebRequest, out DateTimeOffset date)
        {
            try {
                date = GetRemoteDateTime(httpWebRequest);

                return(true);
            }
            catch (WebException) {
                date = default;

                return(false);
            }
        }
Exemple #23
0
 /// <summary>
 /// Write a form to a request
 /// </summary>
 /// <param name="request">Request</param>
 /// <param name="form">Form to write</param>
 public static async Task WriteToRequestAsync(this IHttpWebRequest request, string form)
 {
     if (string.IsNullOrEmpty(form) && request.Method != "GET")
     {
         request.AddHeader("content-length", "0");
     }
     else
     {
         byte[] bytes = form.ToBytesUTF8();
         request.AddHeader("content-length", bytes.Length.ToStringInvariant());
         await request.WriteAllAsync(bytes, 0, bytes.Length);
     }
 }
Exemple #24
0
 protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
 {
     // Only Private APIs are POST and need Authorization
     if (CanMakeAuthenticatedRequest(payload) && request.Method == "POST")
     {
         var msg = CryptoUtility.GetFormForPayload(payload);
         var sig = CryptoUtility.SHA512Sign(msg, PrivateApiKey.ToUnsecureString());
         request.AddHeader("Key", PublicApiKey.ToUnsecureString());
         request.AddHeader("Sign", sig.ToLowerInvariant());
         byte[] content = msg.ToBytesUTF8();
         await request.WriteAllAsync(content, 0, content.Length);
     }
 }
Exemple #25
0
        protected sealed internal override Task <WebResponse> SendAsync(WebRequest request, CancellationToken cancellationToken)
        {
            IHttpWebRequest httpWebRequest = request.AsHttpWebRequest();

            if (httpWebRequest is null)
            {
                return(base.SendAsync(request, cancellationToken));
            }
            else
            {
                return(SendAsync(httpWebRequest, cancellationToken).ContinueWith(t => (WebResponse)t.Result));
            }
        }
Exemple #26
0
 protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
 {
     if (CanMakeAuthenticatedRequest(payload))
     {
         if (request.Method == "POST")
         {
             request.AddHeader("content-type", "application/json");
             payload.Remove("nonce");
             var msg = CryptoUtility.GetJsonForPayload(payload);
             await CryptoUtility.WriteToRequestAsync(request, msg);
         }
     }
 }
Exemple #27
0
        private HttpWebHelperResult CopyRequestStream(IHttpWebRequest httpWebRequest, Stream requestBody, Stream requestStream)
        {
            try
            {
                CopyStream(requestBody, requestStream, FlushInputRequestBody, FlushRequestStream);
                requestStream.Close();
            }
            catch (Exception ex)
            {
                return(new HttpWebHelperResult(httpWebRequest, null, ex, null, false, false, null, null));
            }

            return(GetResponse(httpWebRequest, requestBody));
        }
Exemple #28
0
        /// <summary>
        /// Get the HTML using a synchronous HTTP request. This will return a string using the encoding
        /// specified by the MIME type. If the document uses an encoding specified in a content-type
        /// header, it will NOT be reflected by the results of this method.
        /// </summary>
        ///
        /// <returns>
        /// The HTML returned by a successful request.
        /// </returns>

        public string Get()
        {
            IHttpWebRequest request = GetWebRequest();

            ApplyOptions(request);

            Html = null;

            using (StreamReader responseReader = GetResponseStreamReader(request))
            {
                Html = responseReader.ReadToEnd();
            }
            return(Html);
        }
        public static void SetPostRequest(IHttpWebRequest request, RequestParameters requestParameters, CallState callState, Dictionary <string, string> headers = null)
        {
            request.Method = "POST";

            if (headers != null)
            {
                foreach (KeyValuePair <string, string> kvp in headers)
                {
                    request.Headers[kvp.Key] = kvp.Value;
                }
            }

            request.BodyParameters = requestParameters;
        }
Exemple #30
0
        private HttpWebHelperResult CopyResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseStream, Stream responseSaveStream)
        {
            try
            {
                CopyStream(responseStream, responseSaveStream, false, false);
                responseStream.Close();

                return(new HttpWebHelperResult(httpWebRequest, httpWebResponse, null, innerException, false, true, responseSaveStream, null));
            }
            catch (Exception ex)
            {
                return(new HttpWebHelperResult(httpWebRequest, httpWebResponse, ex, innerException, false, true, responseSaveStream, null));
            }
        }
Exemple #31
0
        public IObservable <Unit> PostJson <T>(IHttpWebRequest httpWebRequest, T obj, string authToken = null)
        {
            var request = GetRequest(httpWebRequest, authToken);

            request.Method      = "POST";
            request.ContentType = "application/json";

            return
                (from requestStream in
                 Observable
                 .FromAsyncPattern <Stream>(request.BeginGetRequestStream, request.EndGetRequestStream)()
                 from response in WriteContentToStream(requestStream, request, obj)
                 select new Unit());
        }
 public static HttpWebRequestOptions FromHttpWebRequest(IHttpWebRequest httpWebRequest)
 {
     return(new HttpWebRequestOptions()
     {
         Accept = httpWebRequest.Accept,
         AcceptLanguage = httpWebRequest.Headers[HttpRequestHeader.AcceptLanguage],
         AllowAutoRedirect = httpWebRequest.AllowAutoRedirect,
         AutomaticDecompression = httpWebRequest.AutomaticDecompression,
         Cookies = httpWebRequest.CookieContainer,
         Credentials = httpWebRequest.Credentials,
         Headers = httpWebRequest.Headers.Clone(),
         Proxy = httpWebRequest.Proxy,
         UserAgent = httpWebRequest.UserAgent,
     });
 }
        public static void AddCorrelationIdHeadersToRequest(IHttpWebRequest request, CallState callState)
        {
            if (callState == null || callState.CorrelationId == Guid.Empty)
            {
                return;
            }

            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                { OAuthHeader.CorrelationId, callState.CorrelationId.ToString() },
                { OAuthHeader.RequestCorrelationIdInResponse, "true" }
            };

            AddHeadersToRequest(request, headers);
        }
Exemple #34
0
        public static async Task <WsTrustResponse> SendRequestAsync(Uri url, UserCredential credential, CallState callState)
        {
            IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(url.AbsoluteUri);

            request.ContentType = "application/soap+xml; charset=utf-8";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder        = BuildMessage(DefaultAppliesTo, url.AbsoluteUri, credential);
            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                { "SOAPAction", XmlNamespace.Issue.ToString() }
            };

            WsTrustResponse wstResponse;

            try
            {
                HttpHelper.SetPostRequest(request, new RequestParameters(messageBuilder), callState, headers);
                IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState);

                wstResponse = WsTrustResponse.CreateFromResponse(response.GetResponseStream());
            }
            catch (WebException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, url, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
Exemple #35
0
        protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload)
        {
            if (CanMakeAuthenticatedRequest(payload))
            {
                // ensure nonce is the last parameter
                string nonce = payload["nonce"].ToStringInvariant();
                payload.Remove("nonce");

                var msg = CryptoUtility.GetFormForPayload(payload) + "&nonce=" + nonce;
                var sig = CryptoUtility.SHA512Sign(msg, CryptoUtility.ToBytesUTF8(PrivateApiKey)).ToLowerInvariant();
                request.AddHeader("Sign", sig);
                request.AddHeader("Key", PublicApiKey.ToUnsecureString());
                byte[] content = msg.ToBytesUTF8();
                await request.WriteAllAsync(content, 0, content.Length);
            }
        }
        private string GetSignKey(IHttpWebRequest request, string formData)
        {
            //TODO: Use csharp8 ranges
            var index            = Array.IndexOf(request.RequestUri.Segments, "1/");
            var callPath         = string.Join(string.Empty, request.RequestUri.Segments.Skip(index + 1)).TrimStart('/');
            var postData         = $"{callPath}\0{formData}";
            var privateKeyBase64 = Convert.FromBase64String(PrivateApiKey.ToUnsecureString());

            byte[] hashBytes;
            using (var hmacSha512 = new HMACSHA512(privateKeyBase64))
            {
                hashBytes = hmacSha512.ComputeHash(Encoding.UTF8.GetBytes(postData));
            }

            return(Convert.ToBase64String(hashBytes));
        }
        private static void AddClientMetricsHeadersToRequest(IHttpWebRequest request)
        {
            lock (PendingClientMetricsLock)
            {
                if (pendingClientMetrics != null && NetworkPlugin.RequestCreationHelper.RecordClientMetrics)
                {
                    Dictionary<string, string> headers = new Dictionary<string, string>();
                    if (pendingClientMetrics.lastError != null)
                    {
                        headers[ClientMetricsHeaderLastError] = pendingClientMetrics.lastError;
                    }

                    headers[ClientMetricsHeaderLastRequest] = pendingClientMetrics.lastCorrelationId.ToString();
                    headers[ClientMetricsHeaderLastResponseTime] = pendingClientMetrics.lastResponseTime.ToString();
                    headers[ClientMetricsHeaderLastEndpoint] = pendingClientMetrics.lastEndpoint;

                    HttpHelper.AddHeadersToRequest(request, headers);
                    pendingClientMetrics = null;
                }
            }
        }
        private void ResponseCallback(IAsyncResult asyncResult, IHttpWebRequest httpWebRequest, Stream requestBody, AsyncCallback callback, object state)
        {
            IHttpWebResponse httpWebResponse = null;
            Exception exception = null;

            try
            {
                httpWebResponse = httpWebRequest.EndGetResponse(asyncResult);
            }
            catch (WebException ex)
            {
                var webException = new WebExceptionWrapper(ex);
                httpWebResponse = webException.GetResponse();
                exception = webException;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    var args = new ResponseReceivedEventArgs(httpWebResponse, exception, state);
                    OnResponseReceived(args);
                    ReadResponseStream(httpWebRequest, httpWebResponse, exception, args.ResponseSaveStream, callback, state);
                }
                else
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, false, null, state));
                }
            }
        }
        private void RequestCallback(IAsyncResult asyncResult, IHttpWebRequest httpWebRequest, Stream requestBody, AsyncCallback callback, object state)
        {
            Stream requestStream = null;
            Exception exception = null;
            IHttpWebResponse httpWebResponse = null;

            try
            {
                requestStream = httpWebRequest.EndGetRequestStream(asyncResult);
            }
            catch (WebException ex)
            {
                var webException = new WebExceptionWrapper(ex);
                httpWebResponse = webException.GetResponse();
                exception = webException;
            }
            finally
            {
                if (exception == null)
                {
                    // we got the stream, so copy to the stream
                    CopyRequestStream(httpWebRequest, requestBody, requestStream, callback, state);
                }
                else
                {
                    // there was an error
                    if (httpWebResponse == null)
                    {
                        if (callback != null)
                            callback(new HttpWebHelperResult(httpWebRequest, null, exception, null, false, false, null, state));
                    }
                    else
                    {
                        var args = new ResponseReceivedEventArgs(httpWebResponse, exception, state);
                        OnResponseReceived(args);
                        ReadResponseStream(httpWebRequest, httpWebResponse, exception, args.ResponseSaveStream, callback, state);
                    }
                }
            }
        }
        private void ReadResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseSaveStream, AsyncCallback callback, object state)
        {
            Stream responseStream = null;
            Exception exception = null;

            try
            {
                responseStream = httpWebResponse.GetResponseStream();
            }
            catch (WebException ex)
            {
                exception = new WebExceptionWrapper(ex);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (exception == null)
                {
                    CopyResponseStream(httpWebRequest, httpWebResponse, innerException, responseStream, responseSaveStream, callback, state);
                }
                else
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, false, responseSaveStream, state));
                }
            }
        }
        private void CopyResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseStream, Stream responseSaveStream, AsyncCallback callback, object state)
        {
            if (AsyncResponseStream && responseSaveStream != null)
            {
                // pure read/write async
                CopyStreamAsync(responseStream, responseSaveStream, FlushResponseStream, FlushResponseSaveStream,
                                (source, destination, exception) =>
                                {
                                    source.Close();
                                    callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, false, responseSaveStream, state));
                                });
            }
            else
            {
                try
                {
                    if (responseSaveStream == null)
                        ReadStream(responseStream, FlushResponseStream);
                    else
                        CopyStream(responseStream, responseSaveStream, FlushResponseStream, FlushResponseSaveStream);

                    responseStream.Close();
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, null, innerException, false, false, responseSaveStream, state));
                }
                catch (Exception ex)
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, ex, null, false, false, responseSaveStream, state));
                }
            }
        }
        private void CopyRequestStream(IHttpWebRequest httpWebRequest, Stream requestBody, Stream requestStream, AsyncCallback callback, object state)
        {
            if (AsyncRequestStream)
            {
                // pure read/write async
                CopyStreamAsync(requestBody, requestStream, FlushInputRequestBody, FlushRequestStream,
                    (source, destination, exception) =>
                    {
                        source.Close();

                        if (exception == null)
                        {
                            BeginGetResponse(httpWebRequest, requestBody, callback, state);
                        }
                        else
                        {
                            if (callback != null)
                                callback(new HttpWebHelperResult(httpWebRequest, null, exception, null, false, false, null, state));
                        }
                    });
            }
            else
            {
                // Read requestBody then write synchronously.
                try
                {
                    CopyStream(requestBody, requestStream, FlushInputRequestBody, FlushRequestStream);
                    requestStream.Close();
                    BeginGetResponse(httpWebRequest, requestBody, callback, state);
                }
                catch (Exception ex)
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, null, ex, null, false, false, null, state));
                }
            }
        }
        protected virtual void SetHttpWebRequestHeaders(IHttpWebRequest httpWebRequest, IEnumerable<Pair<string, string>> requestHeaders)
        {
            foreach (var requestHeader in requestHeaders)
            {
                var name = requestHeader.Name;
                var value = requestHeader.Value;

                // todo: add more special headers
                if (name.Equals("content-type", StringComparison.OrdinalIgnoreCase))
                {
                    httpWebRequest.ContentType = value;
                }
                else if (name.Equals("content-length", StringComparison.OrdinalIgnoreCase))
                {
            #if WINDOWS_PHONE
                    throw new Exception("Cannot set content-length.");
            #else
                    httpWebRequest.ContentLength = Convert.ToInt64(value);
            #endif
                }
                else if(name.Equals("accept", StringComparison.OrdinalIgnoreCase))
                {
                    httpWebRequest.Accept = value;
                }
                else if (name.Equals("user-agent", StringComparison.OrdinalIgnoreCase))
                {
                    httpWebRequest.UserAgent = value;
                }
                else
                {
            #if SILVERLIGHT
                    httpWebRequest.Headers[name] = value;
            #else
                    httpWebRequest.Headers.Add(name, value);
            #endif
                }
            }
        }
 private void SignWebRequest(IHttpWebRequest webRequest, HttpWebRequestMethod method, string path, string queryString)
 {
     webRequest.Headers.Add("Authorization", string.Format("Basic {0}", GetAuthorizationKey(method, path, queryString)));
 }
        public virtual void ExecuteAsync(IHttpWebRequest httpWebRequest, Stream requestBody, AsyncCallback callback, object state)
        {
            if (httpWebRequest == null)
            {
                throw new ArgumentNullException("httpWebRequest");
            }

            if (requestBody != null && requestBody.Length != 0)
            {
                // we have a request body, so write it asynchronously.
            #if !WINDOWS_PHONE
                httpWebRequest.ContentLength = requestBody.Length;
            #endif
                BeginGetRequestStream(httpWebRequest, requestBody, callback, state);
            }
            else
            {
                // asynchronously get the response from the http server.
                BeginGetResponse(httpWebRequest, requestBody, callback, state);
            }
        }
        private HttpWebHelperResult ReadResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseSaveStream)
        {
            Stream responseStream = null;
            Exception exception = null;

            try
            {
                responseStream = httpWebResponse.GetResponseStream();
            }
            catch (WebException ex)
            {
                exception = new WebExceptionWrapper(ex);
            }

            return exception == null ? CopyResponseStream(httpWebRequest, httpWebResponse, innerException, responseStream, responseSaveStream) : new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, innerException, false, true, responseSaveStream, null);
        }
Exemple #47
0
 public RemoteState(IShipHandle iShipHandle, ManualResetEvent manualEvent, IHttpWebRequest request)
 {
     Request = request;
     IShipHandle = iShipHandle;
     ManualEvent = manualEvent;
 }
        public virtual HttpWebHelperResult Execute(IHttpWebRequest httpWebRequest, Stream requestBody)
        {
            if (httpWebRequest == null)
            {
                throw new ArgumentNullException("httpWebRequest");
            }

            if (requestBody != null && requestBody.Length != 0)
            {
                // we have a request body, so write it synchronously.
            #if !WINDOWS_PHONE
                httpWebRequest.ContentLength = requestBody.Length;
            #endif
                return WriteAndGetReponse(httpWebRequest, requestBody);
            }
            else
            {
                // synchronously get the response from the http server.
                return GetResponse(httpWebRequest, requestBody);
            }
        }
Exemple #49
0
        /// <summary>
        /// Gets response stream from a webrequest using the correct encoding.
        /// </summary>
        ///
        /// <param name="request">
        /// The request.
        /// </param>
        ///
        /// <returns>
        /// The response stream.
        /// </returns>

        protected StreamReader GetResponseStreamReader(IHttpWebRequest request) {
            var response = request.GetResponse();
            
            //var response = request.GetResponse();
            //var encoding = response.Headers["
        
            StreamReader reader;
            var encoding = String.IsNullOrEmpty(response.CharacterSet) ?
                Encoding.UTF8 :
                Encoding.GetEncoding(response.CharacterSet);

            reader = new StreamReader(response.GetResponseStream(), encoding);
            return reader;
        }
        public System.Threading.Tasks.Task<HttpWebHelperAsyncResult> ExecuteTaskAsync(IHttpWebRequest httpWebRequest, Stream requestBody, object state)
        {
            var tcs = new System.Threading.Tasks.TaskCompletionSource<HttpWebHelperAsyncResult>(state);

            try
            {
                ExecuteAsync(httpWebRequest, requestBody,
                             ar =>
                             {
                                 var asyncResult = (HttpWebHelperAsyncResult)ar;
                                 if (asyncResult.IsCancelled) tcs.TrySetCanceled();
                                 if (asyncResult.Exception != null) tcs.TrySetException(asyncResult.Exception);
                                 else tcs.TrySetResult(asyncResult);
                             }, state);

            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            return tcs.Task;
        }
        private HttpWebHelperResult CopyRequestStream(IHttpWebRequest httpWebRequest, Stream requestBody, Stream requestStream)
        {
            try
            {
                CopyStream(requestBody, requestStream, FlushInputRequestBody, FlushRequestStream);
                requestStream.Close();
            }
            catch (Exception ex)
            {
                return new HttpWebHelperResult(httpWebRequest, null, ex, null, false, false, null, null);
            }

            return GetResponse(httpWebRequest, requestBody);
        }
 protected virtual void BeginGetResponse(IHttpWebRequest httpWebRequest, Stream requestBody, AsyncCallback callback, object state)
 {
     httpWebRequest.BeginGetResponse(ar => ResponseCallback(ar, httpWebRequest, requestBody, callback, state), null);
 }
        private HttpWebHelperResult CopyResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseStream, Stream responseSaveStream)
        {
            try
            {
                CopyStream(responseStream, responseSaveStream, false, false);
                responseStream.Close();

                return new HttpWebHelperResult(httpWebRequest, httpWebResponse, null, innerException, false, true, responseSaveStream, null);
            }
            catch (Exception ex)
            {
                return new HttpWebHelperResult(httpWebRequest, httpWebResponse, ex, innerException, false, true, responseSaveStream, null);
            }
        }
 public static void AddAsHeaders(IHttpWebRequest request)
 {
     Dictionary<string, string> headers = new Dictionary<string, string>();
     NetworkPlugin.RequestCreationHelper.AddAdalIdParameters(headers);
     HttpHelper.AddHeadersToRequest(request, headers);
 }
        private HttpWebHelperResult GetResponse(IHttpWebRequest httpWebRequest, Stream requestBody)
        {
            IHttpWebResponse httpWebResponse = null;
            Exception exception = null;
            HttpWebHelperResult httpWebHelperAsyncResult = null;

            try
            {
                httpWebResponse = httpWebRequest.GetResponse();
            }
            catch (WebException ex)
            {
                var webException = new WebExceptionWrapper(ex);
                httpWebResponse = webException.GetResponse();
                exception = webException;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    var args = new ResponseReceivedEventArgs(httpWebResponse, exception, null);
                    OnResponseReceived(args);
                    httpWebHelperAsyncResult = ReadResponseStream(httpWebRequest, httpWebResponse, exception, args.ResponseSaveStream);
                }
                else
                {
                    httpWebHelperAsyncResult = new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, true, null, null);
                }
            }

            return httpWebHelperAsyncResult;
        }
Exemple #56
0
        /// <summary>
        /// Creates an AsyncWebRequest for a WebRequest
        /// </summary>
        ///
        /// <param name="request">
        /// The WebRequest object.
        /// </param>

        public AsyncWebRequest(IHttpWebRequest request)
        {
            Request = request;
            Timeout = request.Timeout;
            UserAgent = request.UserAgent;
        }
        private HttpWebHelperResult WriteAndGetReponse(IHttpWebRequest httpWebRequest, Stream requestBody)
        {
            Stream requestStream = null;
            Exception exception = null;
            IHttpWebResponse httpWebResponse = null;
            HttpWebHelperResult result;

            try
            {
                requestStream = httpWebRequest.GetRequestStream();
            }
            catch (WebException ex)
            {
                var webException = new WebExceptionWrapper(ex);
                httpWebResponse = webException.GetResponse();
                exception = webException;
            }
            finally
            {
                if (exception == null)
                {
                    // we got the stream, so copy to the stream
                    result = CopyRequestStream(httpWebRequest, requestBody, requestStream);
                }
                else
                {
                    // there was an error
                    if (httpWebResponse == null)
                    {
                        result = new HttpWebHelperResult(httpWebRequest, null, exception, null, false, true, null, null);
                    }
                    else
                    {
                        var args = new ResponseReceivedEventArgs(httpWebResponse, exception, null);
                        OnResponseReceived(args);
                        result = ReadResponseStream(httpWebRequest, httpWebResponse, exception, args.ResponseSaveStream);
                    }
                }
            }

            return result;
        }
Exemple #58
0
        /// <summary>
        /// Gets http response, returns (etag, data)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private SolrResponse GetResponse(IHttpWebRequest request) {
            using (var response = request.GetResponse()) {
                var etag = response.Headers[HttpResponseHeader.ETag];
                var cacheControl = response.Headers[HttpResponseHeader.CacheControl];
                if (cacheControl != null && cacheControl.Contains("no-cache"))
                    etag = null; // avoid caching things marked as no-cache

                return new SolrResponse(etag, ReadResponseToString(response));
            }
        }
 public System.Threading.Tasks.Task<HttpWebHelperAsyncResult> ExecuteTaskAsync(IHttpWebRequest httpWebRequest, Stream requestBody)
 {
     return ExecuteTaskAsync(httpWebRequest, requestBody, null);
 }
 private static void SetFormValuesForQuery(IHttpWebRequest webRequest, string safeQueryString)
 {
     if (webRequest == null) throw new ArgumentNullException("webRequest");
     webRequest.ContentType = "application/x-www-form-urlencoded";
     var stream = webRequest.GetRequestStream();
     var bodyBytes = new ASCIIEncoding().GetBytes(safeQueryString);
     stream.Write(bodyBytes, 0, bodyBytes.Length);
     stream.Flush();
     stream.Close();
 }