Exemplo n.º 1
0
        public void createRESTRequest(RESTRequest rest_request, string URI, string method, string body)
        {
            HttpWebRequest req = WebRequest.Create(new Uri(URI))
                                 as HttpWebRequest;

            req.Method = method;
            req.Headers["Authorization"] = "OAuth " + OAuthConnection.AccessToken;
            req.Headers["User-Agent"]    = "salesforce-toolkit/Windows7/20";
            if (method == "POST" || method == "PATCH")
            {
                req.ContentType = "application/json";
                req.BeginGetRequestStream(
                    (result) =>
                {
                    HttpWebRequest request      = (HttpWebRequest)result.AsyncState;
                    System.IO.Stream postStream = request.EndGetRequestStream(result);
                    string postData             = body;
                    byte[] byteArray            = System.Text.Encoding.UTF8.GetBytes(postData);

                    // Write to the request stream.
                    postStream.Write(byteArray, 0, postData.Length);
                    postStream.Close();
                    // Start the asynchronous operation to get the response
                    request.BeginGetResponse(
                        (postresult) =>
                    {
                        try
                        {
                            RESTResult restresult = new RESTResult();
                            restresult.request    = rest_request;
                            restresult.data       = getHTTPResult(postresult, method);
                            restresult.request.callback(restresult);
                        }
                        catch (WebException wex)
                        {
                            RESTResult restresult = new RESTResult();
                            restresult.request    = rest_request;
                            string error          = handleHTTPError(wex);
                            restresult.data       = JObject.Parse(error.Substring(1, error.Length - 1));
                            restresult.message    = (string)restresult.data["message"];
                            restresult.request.errorCallback(restresult);
                        }
                    }, req);
                }, req);
            }
            else
            {
                req.BeginGetResponse(
                    (result) =>
                {
                    try
                    {
                        RESTResult restresult = new RESTResult();
                        restresult.request    = rest_request;
                        restresult.data       = getHTTPResult(result, method);
                        restresult.request.callback(restresult);
                    }
                    catch (WebException wex)
                    {
                        RESTResult restresult = new RESTResult();
                        restresult.request    = rest_request;
                        string error          = handleHTTPError(wex);
                        restresult.data       = JObject.Parse(error.Substring(1, error.Length - 1));
                        restresult.message    = (string)restresult.data["message"];

                        restresult.request.errorCallback(restresult);
                    }
                }, req);
            }
        }
Exemplo n.º 2
0
        private Task <string> CreateUploadJob(string createJobUri, Stream dataSourceStream, DataSourceFormat format)
        {
            var tcs = new TaskCompletionSource <string>();

            //Include the data to geocode in the HTTP request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(createJobUri);

            // The HTTP method must be 'POST'.
            request.Method          = "POST";
            request.ContentType     = "application/octet-stream";
            request.ContinueTimeout = 1800000;

            request.BeginGetRequestStream((a) =>
            {
                var r = (HttpWebRequest)a.AsyncState;

                using (var postStream = request.EndGetRequestStream(a))
                {
                    if (format == DataSourceFormat.SHP || XmlUtilities.IsStreamCompressed(dataSourceStream))
                    {
                        dataSourceStream.CopyTo(postStream);
                    }
                    else
                    {
                        using (var zipStream = new GZipStream(postStream, CompressionMode.Compress))
                        {
                            dataSourceStream.CopyTo(zipStream);
                        }
                    }
                }

                request.BeginGetResponse((a2) =>
                {
                    try
                    {
                        var r2       = (HttpWebRequest)a2.AsyncState;
                        var response = (HttpWebResponse)r2.EndGetResponse(a2);

                        string dataflowJobLocation = string.Empty;
                        foreach (var hKey in response.Headers.AllKeys)
                        {
                            if (string.Compare(hKey, "Location", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                dataflowJobLocation = response.Headers[hKey];
                                break;
                            }
                        }

                        tcs.SetResult(dataflowJobLocation);
                    }
                    catch (WebException ex)
                    {
                        if (ex.Response != null)
                        {
                            var ser = new DataContractJsonSerializer(typeof(DataflowResponse));
                            var res = ser.ReadObject(ex.Response.GetResponseStream()) as DataflowResponse;

                            if (res.ErrorDetails != null && res.ErrorDetails.Length > 0)
                            {
                                tcs.SetException(new Exception(string.Join("\r\n", res.ErrorDetails)));
                                return;
                            }
                        }

                        tcs.SetException(ex);
                    }
                }, request);
            }, request);

            return(tcs.Task);
        }
Exemplo n.º 3
0
        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            FrameDLRObject stateobj = (FrameDLRObject)asynchronousResult.AsyncState;
            P p = (P)stateobj.GetValue("p");
            D d = (D)stateobj.GetValue("d");
            HttpWebRequest request    = (HttpWebRequest)stateobj.GetValue("request");
            Stream         postStream = null;

            try
            {
                // End the operation
                postStream = request.EndGetRequestStream(asynchronousResult);
                object postdatastr = GetPostDataData();

                if (request.Method.ToLower() == "post")
                {
                    if (postdatastr != null)
                    {
                        request.ContentType = _contenttype;
                        if (_contenttype.ToLower().IndexOf("/json") > 0)
                        {
                            //提交请求
                            var streamWriter = new StreamWriter(postStream);
                            streamWriter.Write(postdatastr);
                            streamWriter.Flush();
                        }
                        else if (_contenttype.ToLower().IndexOf("multipart/form-data") > 0)
                        {
                            byte[] postdata = (byte[])postdatastr;
                            //request.ContentLength = postdata.Length;
                            //提交请求
                            postStream.Write(postdata, 0, postdata.Length);
                            postStream.Flush();
                        }
                        else
                        {
                            byte[] postdatabyte = _encoding.GetBytes(postdatastr.ToString());
                            //request.ContentLength = postdatabyte.Length;
                            //提交请求
                            postStream.Write(postdatabyte, 0, postdatabyte.Length);
                            postStream.Flush();
                        }
                    }
                }
                else if (request.Method.ToLower() == "put")
                {
                    if (postdatastr != null && postdatastr is byte[])
                    {
                        var postdatabyte = (byte[])postdatastr;
                        postStream.Write(postdatabyte, 0, postdatabyte.Length);
                        postStream.Flush();
                    }
                }
                // Start the asynchronous operation to get the response
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), stateobj);
            }
            catch (Exception ex)
            {
                OnError(ex, p, d);
            }
            finally
            {
                if (postStream != null)
                {
                    postStream.Close();
                }

                p.Resources.ReleaseAll();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Upload an array of files to a remote host using the HTTP post multipart method
        /// </summary>
        /// <param name="URL">Target URL</param>
        /// <param name="parameters">Parmaters</param>
        /// <param name="files">An array of files</param>
        /// <param name="SuccessCallback">Funciton that is called on success</param>
        /// <param name="FailCallback">Function that is called on failure</param>
        public static void Upload(string URL, object Parameters, NamedFileStream[] files, Action <string> SuccessCallback, Action <WebException> FailCallback)
        {
            try
            {
                /*
                 * Generate a random boundry string
                 */
                string boundary = RandomString(12);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URL));
                request.Method          = "POST";
                request.ContentType     = "multipart/form-data, boundary=" + boundary;
                request.CookieContainer = cookies;
                request.UserAgent       = UserAgent;

                if (Proxy != null)
                {
                    request.Proxy = Proxy;
                }


                request.BeginGetRequestStream(new AsyncCallback((IAsyncResult asynchronousResult) =>
                {
                    /*
                     * Create a new request
                     */
                    HttpWebRequest tmprequest = (HttpWebRequest)asynchronousResult.AsyncState;

                    /*
                     * Get a stream that we can write to
                     */
                    Stream postStream  = tmprequest.EndGetRequestStream(asynchronousResult);
                    string querystring = "\n";

                    /*
                     * Serialize parameters in multipart manner
                     */
                    foreach (var property in Parameters.GetType().GetProperties())
                    {
                        querystring += "--" + boundary + "\n";
                        querystring += "content-disposition: form-data; name=\"" + System.Uri.EscapeDataString(property.Name) + "\"\n\n";
                        querystring += System.Uri.EscapeDataString(property.GetValue(Parameters, null).ToString());
                        querystring += "\n";
                    }


                    /*
                     * Then write query string to the postStream
                     */
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(querystring);
                    postStream.Write(byteArray, 0, byteArray.Length);

                    /*
                     * A boundary string that we'll reuse to separate files
                     */
                    byte[] closing = System.Text.Encoding.UTF8.GetBytes("\n--" + boundary + "--\n");


                    /*
                     * Write each files to the postStream
                     */
                    foreach (NamedFileStream file in files)
                    {
                        /*
                         * A temporary buffer to hold the file stream
                         * Not sure if this is needed ???
                         */
                        Stream outBuffer = new MemoryStream();

                        /*
                         * Additional info that is prepended to the file
                         */
                        string qsAppend;
                        qsAppend = "--" + boundary + "\ncontent-disposition: form-data; name=\"" + file.Name + "\"; filename=\"" + file.Filename + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";

                        /*
                         * Read the file into the output buffer
                         */
                        StreamReader sr = new StreamReader(file.Stream);
                        outBuffer.Write(System.Text.Encoding.UTF8.GetBytes(qsAppend), 0, qsAppend.Length);

                        int bytesRead = 0;
                        byte[] buffer = new byte[4096];

                        while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            outBuffer.Write(buffer, 0, bytesRead);
                        }


                        /*
                         * Write the delimiter to the output buffer
                         */
                        outBuffer.Write(closing, 0, closing.Length);



                        /*
                         * Write the output buffer to the post stream using an intemediate byteArray
                         */
                        outBuffer.Position = 0;
                        byte[] tempBuffer  = new byte[outBuffer.Length];
                        outBuffer.Read(tempBuffer, 0, tempBuffer.Length);
                        postStream.Write(tempBuffer, 0, tempBuffer.Length);
                        postStream.Flush();
                    }


                    postStream.Flush();
                    postStream.Dispose();

                    tmprequest.BeginGetResponse(ProcessCallback(SuccessCallback, FailCallback), tmprequest);
                }), request);
            }
            catch (WebException webEx)
            {
                FailCallback(webEx);
            }
        }
Exemplo n.º 5
0
        private static void BeginSetRequestContent(HttpWebRequest webRequest, ServiceRequest serviceRequest,
                                                   OssAction asyncCallback, ClientConfiguration clientConfiguration, HttpAsyncResult result)
        {
            var data = serviceRequest.BuildRequestContent();

            if (data == null ||
                (serviceRequest.Method != HttpMethod.Put &&
                 serviceRequest.Method != HttpMethod.Post))
            {
                // Skip setting content body in this case.
                try
                {
                    asyncCallback();
                }
                catch (Exception e)
                {
                    result.WebRequest.Abort();
                    result.Complete(e);
                }

                return;
            }

            // Write data to the request stream.
            long userSetContentLength = -1;

            if (serviceRequest.Headers.ContainsKey(HttpHeaders.ContentLength))
            {
                userSetContentLength = long.Parse(serviceRequest.Headers[HttpHeaders.ContentLength]);
            }

            if (serviceRequest.UseChunkedEncoding || !data.CanSeek) // when data cannot seek, we have to use chunked encoding as there's no way to set the length
            {
                webRequest.SendChunked = true;
                webRequest.AllowWriteStreamBuffering = false; // when using chunked encoding, the data is likely big and thus not use write buffer;
            }
            else
            {
                long streamLength = data.Length - data.Position;
                webRequest.ContentLength = (userSetContentLength >= 0 &&
                                            userSetContentLength <= streamLength) ? userSetContentLength : streamLength;
                if (webRequest.ContentLength > clientConfiguration.DirectWriteStreamThreshold)
                {
                    webRequest.AllowWriteStreamBuffering = false;
                }
            }

            webRequest.BeginGetRequestStream(
                (ar) =>
            {
                try
                {
                    using (var requestStream = webRequest.EndGetRequestStream(ar))
                    {
                        if (!webRequest.SendChunked)
                        {
                            IoUtils.WriteTo(data, requestStream, webRequest.ContentLength);
                        }
                        else
                        {
                            IoUtils.WriteTo(data, requestStream);
                        }
                    }
                    asyncCallback();
                }
                catch (Exception e)
                {
                    result.WebRequest.Abort();
                    result.Complete(e);
                }
            }, null);
        }
Exemplo n.º 6
0
 public Stream EndGetRequestStream(IAsyncResult asyncResult)
 {
     return(_innerRequest.EndGetRequestStream(asyncResult));
 }
Exemplo n.º 7
0
            /// <summary>
            /// Used by the worker thread to start the request
            /// </summary>
            public void Start()
            {
                try
                {
                    // Create the request
                    request             = (HttpWebRequest)System.Net.WebRequest.Create(URL);
                    request.Method      = Method;
                    request.Credentials = CredentialCache.DefaultCredentials;
                    request.Proxy       = null;
                    request.KeepAlive   = false;
                    request.Timeout     = (int)Math.Round((Timeout == 0f ? WebRequests.Timeout : Timeout) * 1000f);
                    request.ServicePoint.MaxIdleTime       = request.Timeout;
                    request.ServicePoint.Expect100Continue = ServicePointManager.Expect100Continue;
                    request.ServicePoint.ConnectionLimit   = ServicePointManager.DefaultConnectionLimit;

                    // Optional request body for post requests
                    var data = new byte[0];
                    if (Body != null)
                    {
                        data = Encoding.UTF8.GetBytes(Body);
                        request.ContentLength = data.Length;
                        request.ContentType   = "application/x-www-form-urlencoded";
                    }

                    if (RequestHeaders != null)
                    {
                        request.SetRawHeaders(RequestHeaders);
                    }

                    // Perform DNS lookup and connect (blocking)
                    if (data.Length > 0)
                    {
                        request.BeginGetRequestStream(result =>
                        {
                            if (request == null)
                            {
                                return;
                            }
                            try
                            {
                                // Write request body
                                using (var stream = request.EndGetRequestStream(result)) stream.Write(data, 0, data.Length);
                            }
                            catch (Exception ex)
                            {
                                ResponseText = ex.Message.Trim('\r', '\n', ' ');
                                request?.Abort();
                                OnComplete();
                                return;
                            }
                            WaitForResponse();
                        }, null);
                    }
                    else
                    {
                        WaitForResponse();
                    }
                }
                catch (Exception ex)
                {
                    ResponseText = ex.Message.Trim('\r', '\n', ' ');
                    var message = $"Web request produced exception (Url: {URL})";
                    if (Owner)
                    {
                        message += $" in '{Owner.Name} v{Owner.Version}' plugin";
                    }
                    Interface.Oxide.LogException(message, ex);
                    request?.Abort();
                    OnComplete();
                }
            }
Exemplo n.º 8
0
        /// <summary>   
        /// 创建POST方式的HTTP请求   
        /// </summary>   
        /// <param name="url">请求的URL</param>   
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>   
        public static void CreatePostHttpResponse(string url, IDictionary<string, string> parameters, callbackResult callback)
        {
            //判断url不为空
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            //创建请求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //请求类型
            request.Method = "POST";
            //http 标头
            request.ContentType = "application/x-www-form-urlencoded";

            request.UserAgent = DefaultUserAgent;
            //参数
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    //if (i > 0)
                    if (url.IndexOf("?") > -1)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("?{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());

                //开始请求
                request.BeginGetRequestStream(new AsyncCallback((ia) =>
                {

                    HttpWebRequest httpWebRequest = (HttpWebRequest)ia.AsyncState;

                    using (Stream stream = httpWebRequest.EndGetRequestStream(ia))
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    request.BeginGetResponse((x) => {

                        HttpWebRequest req = x.AsyncState as HttpWebRequest;
                        string responseStr = string.Empty;

                        try
                        {
                            // 获取请求
                            using (HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(x))
                            {
                                // Get the response stream  
                                StreamReader reader = new StreamReader(response.GetResponseStream());
                                responseStr = reader.ReadToEnd(); 
                            }
                            callback(responseStr);
                        }
                        catch (Exception)
                        {
                            
                            throw;
                        }
                       
                    
                    }, request);

                }), request);
            }
            else
            {
                request.BeginGetResponse((ia) =>
                {

                    HttpWebRequest req = ia.AsyncState as HttpWebRequest;
                    string responseStr = string.Empty;

                    // 获取请求
                    using (HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(ia))
                    {
                        // Get the response stream  
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        responseStr = reader.ReadToEnd();

                    }
                    callback(responseStr);
                }, request);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Makes an update request asynchronously to the remote endpoint.
        /// </summary>
        /// <param name="sparqlUpdate">SPARQL Update.</param>
        /// <param name="callback">Callback to invoke when the update completes.</param>
        /// <param name="state">State to pass to the callback.</param>
        public void Update(String sparqlUpdate, UpdateCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
            request.Accept      = MimeTypesHelper.Any;
            ApplyRequestOptions(request);
            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetRequestStream(result =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(result);
                        using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                        {
                            writer.Write("update=");
                            writer.Write(HttpUtility.UrlEncode(sparqlUpdate));

                            writer.Close();
                        }

                        request.BeginGetResponse(innerResult =>
                        {
                            try
                            {
                                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult))
                                {
                                    Tools.HttpDebugResponse(response);

                                    response.Close();
                                    callback(state);
                                }
                            }
                            catch (SecurityException secEx)
                            {
                                callback(new AsyncError(new SparqlUpdateException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                            }
                            catch (WebException webEx)
                            {
                                if (webEx.Response != null)
                                {
                                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                                }
                                callback(new AsyncError(new SparqlUpdateException("A HTTP error occurred while making an asynchronous update, see inner exception for details", webEx), state));
                            }
                            catch (Exception ex)
                            {
                                callback(new AsyncError(new SparqlUpdateException("Unexpected error while making an asynchronous update, see inner exception for details", ex), state));
                            }
                        }, null);
                    }
                    catch (SecurityException secEx)
                    {
                        callback(new AsyncError(new SparqlUpdateException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(new AsyncError(new SparqlUpdateException("A HTTP error occurred while making an asynchronous update, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(new AsyncError(new SparqlUpdateException("Unexpected error while making an asynchronous update, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (Exception ex)
            {
                callback(new AsyncError(new SparqlUpdateException("Unexpected error while making an asynchronous update, see inner exception for details", ex), state));
            }
        }
Exemplo n.º 10
0
        private dynamic odooServerCall <T>(string url, JsonRpcRequestParameter parameter)
        {
            var    tmpData        = new JsonRpcRequest(parameter);
            string requestContent = "";

            // this.Password = Settings.UserPassword;

            if (Device.RuntimePlatform == "Android")
            {
                requestContent = JsonConvert.SerializeObject(tmpData);
            }
            else
            {
                Dictionary <string, dynamic> paramsDic = new Dictionary <string, dynamic>();
                paramsDic.Add("service", parameter.Service);
                paramsDic.Add("method", parameter.Method);
                paramsDic.Add("args", parameter.Argument);

                Dictionary <string, dynamic> jObj = new Dictionary <string, dynamic>();
                jObj.Add("jsonrpc", "2.0");
                jObj.Add("method", "call");
                jObj.Add("params", paramsDic);

                var formatData = JsonConvert.SerializeObject(jObj);
                requestContent = formatData;
            }
            System.Diagnostics.Debug.WriteLine("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW " + requestContent);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "POST";
            try
            {
                App.responseState = true;
                App.NetAvailable  = true;
                IAsyncResult resultRequest = request.BeginGetRequestStream(null, null);
                Stream       streamInput   = request.EndGetRequestStream(resultRequest);
                byte[]       byteArray     = Encoding.UTF8.GetBytes(requestContent);
                streamInput.WriteAsync(byteArray, 0, byteArray.Length);
                streamInput.FlushAsync();

                // Receive data from server
                IAsyncResult    resultResponse = request.BeginGetResponse(null, null);
                HttpWebResponse response       = (HttpWebResponse)request.EndGetResponse(resultResponse);
                Stream          streamResponse = response.GetResponseStream();
                StreamReader    streamRead     = new StreamReader(streamResponse);
                var             resultData     = streamRead.ReadToEndAsync();
                var             responseData   = resultData.Result;
                streamResponse.FlushAsync();
                if (Device.RuntimePlatform == "iOS")
                {
                    string rspData = string.Join("", responseData);
                    try
                    {
                        JObject jsonObj = JObject.Parse(rspData);
                        Dictionary <string, dynamic> dictObj = jsonObj.ToObject <Dictionary <string, dynamic> >();
                        return(dictObj["result"]);
                    }
                    catch (Exception ea)
                    {
                        return(responseData);
                    }
                }
                else
                {
                    try
                    {
                        JsonRpcResponse <T> jsonRpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(responseData);
                        if (jsonRpcResponse.Error != null)
                        {
                            return("Odoo Error");
                        }
                        else
                        {
                            return(jsonRpcResponse.Result);
                        }
                    }
                    catch (Exception ea)
                    {
                        return(responseData);
                    }
                }
            }
            catch (Exception ea)
            {
                if (ea.Message.Contains("(Network is unreachable)") || ea.Message.Contains("NameResolutionFailure"))
                {
                    App.NetAvailable = false;
                }

                else if (ea.Message.Contains("(503) Service Unavailable"))
                {
                    App.responseState = false;
                }

                System.Diagnostics.Debug.WriteLine(ea.Message);
                //  throw;
            }
            return(default(T));
        }
Exemplo n.º 11
0
        public static void post(Uri uri, Dictionary <String, String> post_params, Dictionary <String, String> extra_headers, RESTSuccessCallback success_callback, RESTErrorCallback error_callback)
        {
            HttpWebRequest request = WebRequest.CreateHttp(uri);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "POST";

            if (extra_headers != null)
            {
                foreach (String header in extra_headers.Keys)
                {
                    try
                    {
                        request.Headers[header] = extra_headers[header];
                    }
                    catch (Exception) { }
                }
            }


            request.BeginGetRequestStream((IAsyncResult result) =>
            {
                HttpWebRequest preq = result.AsyncState as HttpWebRequest;
                if (preq != null)
                {
                    Stream postStream = preq.EndGetRequestStream(result);

                    StringBuilder postParamBuilder = new StringBuilder();
                    if (post_params != null)
                    {
                        foreach (String key in post_params.Keys)
                        {
                            postParamBuilder.Append(String.Format("{0}={1}&", key, post_params[key]));
                        }
                    }

                    Byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString());

                    postStream.Write(byteArray, 0, byteArray.Length);
                    postStream.Close();


                    preq.BeginGetResponse((IAsyncResult final_result) =>
                    {
                        HttpWebRequest req = final_result.AsyncState as HttpWebRequest;
                        if (req != null)
                        {
                            try
                            {
                                WebResponse response = req.EndGetResponse(final_result);
                                success_callback(response.GetResponseStream());
                            }
                            catch (WebException e)
                            {
                                error_callback(e.Message);
                                return;
                            }
                        }
                    }, preq);
                }
            }, request);
        }
Exemplo n.º 12
0
        void WriteRequestBodyAsync(HttpWebRequest webRequest, Action <HttpResponse> callback)
        {
            IAsyncResult asyncResult;

            timeoutState = new TimeOutState {
                Request = webRequest
            };

            if (HasBody || HasFiles || AlwaysMultipartFormData)
            {
                webRequest.ContentLength = CalculateContentLength();

                asyncResult = webRequest.BeginGetRequestStream(
                    RequestStreamCallback, webRequest
                    );
            }
            else
            {
                asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest);
            }

            SetTimeout(asyncResult);

            void RequestStreamCallback(IAsyncResult result)
            {
                if (timeoutState.TimedOut)
                {
                    var response = new HttpResponse {
                        ResponseStatus = ResponseStatus.TimedOut
                    };

                    ExecuteCallback(response, callback);

                    return;
                }

                // write body to request stream
                try
                {
                    using (var requestStream = webRequest.EndGetRequestStream(result))
                    {
                        if (HasFiles || AlwaysMultipartFormData)
                        {
                            WriteMultipartFormData(requestStream);
                        }
                        else if (RequestBodyBytes != null)
                        {
                            requestStream.Write(RequestBodyBytes, 0, RequestBodyBytes.Length);
                        }
                        else if (RequestBody != null)
                        {
                            requestStream.WriteString(RequestBody, Encoding);
                        }
                    }

                    var response = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest);

                    SetTimeout(response);
                }
                catch (Exception ex)
                {
                    ExecuteCallback(CreateErrorResponse(ex), callback);
                }
            }
        }
        private void DoGetResponseAsync <T>(Uri url, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            string postContents = String.Empty;

            if (url.AbsoluteUri.Length > 2000)
            {
                postContents = url.Query.Substring(1);
                url          = new Uri(url, String.Empty);
            }

            FlickrResult <T> result = new FlickrResult <T>();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "POST";
            request.BeginGetRequestStream(requestAsyncResult =>
            {
                using (Stream s = request.EndGetRequestStream(requestAsyncResult))
                {
                    using (StreamWriter sw = new StreamWriter(s))
                    {
                        sw.Write(postContents);
                        sw.Close();
                    }
                    s.Close();
                }

                request.BeginGetResponse(responseAsyncResult =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult);
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseXml = sr.ReadToEnd();

                            lastResponse = responseXml;

                            XmlReaderSettings settings = new XmlReaderSettings();
                            settings.IgnoreWhitespace  = true;
                            XmlReader reader           = XmlReader.Create(new StringReader(responseXml), settings);

                            if (!reader.ReadToDescendant("rsp"))
                            {
                                throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                            }
                            while (reader.MoveToNextAttribute())
                            {
                                if (reader.LocalName == "stat" && reader.Value == "fail")
                                {
                                    throw ExceptionHandler.CreateResponseException(reader);
                                }
                                continue;
                            }

                            reader.MoveToElement();
                            reader.Read();

                            T t = new T();
                            ((IFlickrParsable)t).Load(reader);
                            result.Result   = t;
                            result.HasError = false;

                            sr.Close();
                        }

                        if (null != callback)
                        {
                            callback(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Error = ex;
                        if (null != callback)
                        {
                            callback(result);
                        }
                    }
                }, null);
            }, null);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Read file from Isolated Storage and sends it to server
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void uploadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState   = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       webRequest = reqState.request;
            string callbackId = reqState.options.CallbackId;

            try
            {
                using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
                {
                    string lineStart        = "--";
                    string lineEnd          = Environment.NewLine;
                    byte[] boundaryBytes    = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;

                    if (!string.IsNullOrEmpty(reqState.options.Params))
                    {
                        Dictionary <string, string> paramMap = parseHeaders(reqState.options.Params);
                        foreach (string key in paramMap.Keys)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                            string formItem      = string.Format(formdataTemplate, key, paramMap[key]);
                            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
                            requestStream.Write(formItemBytes, 0, formItemBytes.Length);
                        }
                    }
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(reqState.options.FilePath))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
                            return;
                        }

                        byte[] endRequest       = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
                        long   totalBytesToSend = 0;

                        using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
                        {
                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
                            string header         = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
                            byte[] headerBytes    = System.Text.Encoding.UTF8.GetBytes(header);

                            byte[] buffer    = new byte[4096];
                            int    bytesRead = 0;
                            //sent bytes needs to be reseted before new upload
                            bytesSent        = 0;
                            totalBytesToSend = fileStream.Length;

                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                            requestStream.Write(headerBytes, 0, headerBytes.Length);

                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                if (!reqState.isCancelled)
                                {
                                    requestStream.Write(buffer, 0, bytesRead);
                                    bytesSent += bytesRead;
                                    DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId);
                                    System.Threading.Thread.Sleep(1);
                                }
                                else
                                {
                                    throw new Exception("UploadCancelledException");
                                }
                            }
                        }

                        requestStream.Write(endRequest, 0, endRequest.Length);
                    }
                }
                // webRequest

                webRequest.BeginGetResponse(ReadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                if (!reqState.isCancelled)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
                }
            }
        }
Exemplo n.º 15
0
        public virtual void Invoke <T>(string method, string args, Action <T> success = null, Action <Exception> fail = null)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (method.Length == 0)
            {
                throw new ArgumentException(null, "method");
            }

            try
            {
                var url = string.IsNullOrWhiteSpace(Url) ? DefaultUrl : Url;
                if (string.IsNullOrWhiteSpace(url))
                {
                    if (fail != null)
                    {
                        fail(new Exception("No Url specified"));
                        return;
                    }
                    else
                    {
                        throw new Exception("No Url specified");
                    }
                }
                var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)";
                request.Proxy       = _proxy;
                request.ContentType = "text/plain; charset=utf-8";
                request.Method      = "POST";

                request.BeginGetRequestStream((target) =>
                {
                    HttpWebRequest req = null;
                    try
                    {
                        req = (HttpWebRequest)target.AsyncState;
                        using (Stream stream = req.EndGetRequestStream(target))
                            using (var writer = new StreamWriter(stream, Encoding.UTF8))
                            {
                                string data = "{" + string.Format(" \"id\" : \"{0}\",  \"method\" : \"{1}\",  \"params\" : {2} ", (++_id).ToString(), method, args.ToString()) + "}";
                                writer.WriteLine(data);
                            }
                    }
                    catch (Exception ex)
                    {
                        if (fail != null)
                        {
                            fail(ex); return;
                        }
                        else
                        {
                            throw ex;
                        }
                    }

                    // GetWebResponse(req,target))

                    req.BeginGetResponse(
                        (result) =>
                    {
                        try
                        {
                            var req1  = result.AsyncState as HttpWebRequest;
                            var resp1 = req1.EndGetResponse(result) as HttpWebResponse;
                            using (var stream1 = resp1.GetResponseStream())
                                using (var reader = new StreamReader(stream1, Encoding.UTF8))
                                    if (success != null)
                                    {
                                        try
                                        {
                                            var data = OnResponse <T>(reader);
                                            success(data);
                                        }
                                        catch (Exception ex)
                                        {
                                            if (fail != null)
                                            {
                                                fail(ex);
                                            }
                                            else
                                            {
                                                throw ex;
                                            }
                                        }
                                    }
                        }
                        catch (Exception ex)
                        {
                            if (fail != null)
                            {
                                fail(ex);
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                    }, req);
                }, request);
            }
            catch (Exception ex)
            {
                if (fail != null)
                {
                    fail(ex);
                }
                else
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 16
0
        // Token: 0x06001233 RID: 4659 RVA: 0x0006F2EC File Offset: 0x0006D4EC
        private IEnumerator <int> ProcessProxyRequest(AsyncEnumerator ae)
        {
            ExTraceGlobals.ProxyCallTracer.TraceDebug((long)this.GetHashCode(), "ProxyEventHandler.SendProxyRequest");
            base.DontWriteHeaders = true;
            int newContentLength = 0;

            byte[]         soapHeaderStuff      = this.GetRequestSoapHeader(out newContentLength);
            HttpWebRequest webRequest           = this.GetProxyRequest(newContentLength);
            WindowsImpersonationContext context = NetworkServiceImpersonator.Impersonate();

            try
            {
                ae.AddAsync <IAsyncResult>(webRequest.BeginGetRequestStream(ae.GetAsyncCallback(), null));
            }
            catch
            {
                context.Undo();
                context = null;
                throw;
            }
            finally
            {
                if (context != null)
                {
                    context.Undo();
                    context = null;
                }
            }
            yield return(1);

            Stream outStream = this.DoWebAction <Stream>(() => webRequest.EndGetRequestStream(ae.CompletedAsyncResults[0]));

            if (outStream == null)
            {
                ae.End();
            }
            else
            {
                using (outStream)
                {
                    ae.AddAsync <IAsyncResult>(outStream.BeginWrite(soapHeaderStuff, 0, soapHeaderStuff.Length, ae.GetAsyncCallback(), null));
                    yield return(1);

                    outStream.EndWrite(ae.CompletedAsyncResults[0]);
                    AsyncResult asyncResult = ae.AddAsyncEnumerator((AsyncEnumerator ae1) => ProxyToEwsEventHandler.CopyStream(ae1, this.HttpContext.Request.InputStream, outStream));
                    yield return(1);

                    asyncResult.End();
                }
                ae.AddAsync <IAsyncResult>(webRequest.BeginGetResponse(ae.GetAsyncCallback(), null));
                yield return(1);

                HttpWebResponse webResponse = this.DoWebAction <HttpWebResponse>(() => (HttpWebResponse)webRequest.EndGetResponse(ae.CompletedAsyncResults[0]));
                if (webResponse != null)
                {
                    using (webResponse)
                    {
                        ae.AddAsyncEnumerator((AsyncEnumerator ae1) => this.ProcessWebResponse(ae1, webResponse));
                        yield return(1);
                    }
                }
                ae.End();
            }
            yield break;
        }
Exemplo n.º 17
0
        /// <summary>
        /// This method will perform a the http request synchronously, and return the json decoded result
        /// </summary>
        /// <param name="request"></param>
        /// <returns>Dictionary<string,object></returns>
        public Dictionary <string, object> processRequest(Request request)
        {
            HttpWebRequest conn = (HttpWebRequest)WebRequest.CreateHttp(request.buildUrl(this.apiEndPoint));

            conn.Headers["Authorization"] = "Basic " + this.getAuthString();
            conn.ContentType         = "application/json; charset=utf-8";
            conn.Headers["SDK-Type"] = "Paysafe_CSharp_SDK";

            conn.Method = request.method();
            if (request.method().Equals(RequestType.POST.ToString()) ||
                request.method().Equals(RequestType.PUT.ToString()))
            {
                string requestBody = request.body();
                byte[] requestData = Encoding.UTF8.GetBytes(requestBody);

                var    resultRequest = conn.BeginGetRequestStream(null, null);
                Stream postStream    = conn.EndGetRequestStream(resultRequest);
                postStream.Write(requestData, 0, requestData.Length);
                postStream.Dispose();
            }

            try
            {
                var         responseRequest = conn.BeginGetResponse(null, null);
                WebResponse responseObject  = conn.EndGetResponse(responseRequest);

                StreamReader sr = new StreamReader(responseObject.GetResponseStream());
                return(PaysafeApiClient.parseResponse(sr.ReadToEnd()));
            }
            catch (System.Net.WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                StreamReader    sr       = new StreamReader(response.GetResponseStream());
                string          body     = sr.ReadToEnd();

                string exceptionType = null;
                switch (response.StatusCode)
                {
                case HttpStatusCode.BadRequest:     // 400
                    exceptionType = "InvalidRequestException";
                    break;

                case HttpStatusCode.Unauthorized:     // 401
                    exceptionType = "InvalidCredentialsException";
                    break;

                case HttpStatusCode.PaymentRequired:     //402
                    exceptionType = "RequestDeclinedException";
                    break;

                case HttpStatusCode.Forbidden:     //403
                    exceptionType = "PermissionException";
                    break;

                case HttpStatusCode.NotFound:     //404
                    exceptionType = "EntityNotFoundException";
                    break;

                case HttpStatusCode.Conflict:     //409
                    exceptionType = "RequestConflictException";
                    break;

                case HttpStatusCode.NotAcceptable:           //406
                case HttpStatusCode.UnsupportedMediaType:    //415
                case HttpStatusCode.InternalServerError:     //500
                case HttpStatusCode.NotImplemented:          //501
                case HttpStatusCode.BadGateway:              //502
                case HttpStatusCode.ServiceUnavailable:      //503
                case HttpStatusCode.GatewayTimeout:          //504
                case HttpStatusCode.HttpVersionNotSupported: //505
                    exceptionType = "APIException";
                    break;
                }
                if (exceptionType != null)
                {
                    String message = ex.Message;
                    Dictionary <string, dynamic> rawResponse = PaysafeApiClient.parseResponse(body);
                    if (rawResponse.ContainsKey("error"))
                    {
                        message = rawResponse["error"]["message"];
                    }

                    Object[]         args             = { message, ex.InnerException };
                    PaysafeException PaysafeException = Activator.CreateInstance
                                                            (Type.GetType("Paysafe.Common." + exceptionType), args) as PaysafeException;
                    PaysafeException.rawResponse(rawResponse);
                    if (rawResponse.ContainsKey("error"))
                    {
                        PaysafeException.code(int.Parse(rawResponse["error"]["code"]));
                    }
                    throw PaysafeException;
                }

                throw;
            }
            throw new PaysafeException("An unknown error has occurred.");
        }
Exemplo n.º 18
0
 internal Stream EndGetRequestStream(IAsyncResult asyncResult)
 {
     return(m_request.EndGetRequestStream(asyncResult));
 }
Exemplo n.º 19
0
        /// <summary>
        /// Queries the store asynchronously.
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query.</param>
        /// <param name="rdfHandler">RDF Handler.</param>
        /// <param name="resultsHandler">Results Handler.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, AsyncStorageCallback callback, object state)
        {
            try
            {
                // First off parse the Query to see what kind of query it is
                SparqlQuery q;
                try
                {
                    q = _parser.ParseFromString(sparqlQuery);
                }
                catch (RdfParseException parseEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, parseEx), state);
                    return;
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, new RdfStorageException("An unexpected error occurred while trying to parse the SPARQL Query prior to sending it to the Store, see inner exception for details", ex)), state);
                    return;
                }

                // Now select the Accept Header based on the query type
                String accept = (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask) ? MimeTypesHelper.HttpSparqlAcceptHeader : MimeTypesHelper.HttpAcceptHeader;

                // Create the Request, for simplicity async requests are always POST
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_endpoint.Uri);
                request.Accept      = accept;
                request.Method      = "POST";
                request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
                request             = ApplyRequestOptions(request);

                Tools.HttpDebugRequest(request);

                request.BeginGetRequestStream(r =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(r);
                        using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                        {
                            writer.Write("query=");
                            writer.Write(HttpUtility.UrlEncode(sparqlQuery));
                            writer.Close();
                        }

                        request.BeginGetResponse(r2 =>
                        {
                            // Get the Response and process based on the Content Type
                            try
                            {
                                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                                Tools.HttpDebugResponse(response);
                                StreamReader data = new StreamReader(response.GetResponseStream());
                                String ctype      = response.ContentType;
                                if (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask)
                                {
                                    // ASK/SELECT should return SPARQL Results
                                    ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(ctype, q.QueryType == SparqlQueryType.Ask);
                                    resreader.Load(resultsHandler, data);
                                    response.Close();
                                }
                                else
                                {
                                    // CONSTRUCT/DESCRIBE should return a Graph
                                    IRdfReader rdfreader = MimeTypesHelper.GetParser(ctype);
                                    rdfreader.Load(rdfHandler, data);
                                    response.Close();
                                }
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, sparqlQuery, rdfHandler, resultsHandler), state);
                            }
                            catch (WebException webEx)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state);
                            }
                            catch (Exception ex)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state);
                            }
                        }, state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates a new store based on the given template.
        /// </summary>
        /// <param name="template">Template.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        /// <remarks>
        /// <para>
        /// Template must inherit from <see cref="BaseStardogTemplate"/>.
        /// </para>
        /// </remarks>
        public virtual void CreateStore(IStoreTemplate template, AsyncStorageCallback callback, object state)
        {
            if (template is BaseStardogTemplate)
            {
                // POST /admin/databases
                // Creates a new database; expects a multipart request with a JSON specifying database name, options and filenames followed by (optional) file contents as a multipart POST request.
                try
                {
                    // Get the Template
                    BaseStardogTemplate  stardogTemplate = (BaseStardogTemplate)template;
                    IEnumerable <String> errors          = stardogTemplate.Validate();
                    if (errors.Any())
                    {
                        throw new RdfStorageException("Template is not valid, call Validate() on the template to see the list of errors");
                    }
                    JObject jsonTemplate = stardogTemplate.GetTemplateJson();
                    Console.WriteLine(jsonTemplate.ToString());

                    // Create the request and write the JSON
                    HttpWebRequest request         = CreateAdminRequest("databases", MimeTypesHelper.Any, "POST", new Dictionary <string, string>());
                    String         boundary        = StorageHelper.HttpMultipartBoundary;
                    byte[]         boundaryBytes   = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                    byte[]         terminatorBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary;

                    request.BeginGetRequestStream(r =>
                    {
                        try
                        {
                            using (Stream stream = request.EndGetRequestStream(r))
                            {
                                // Boundary
                                stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                                // Then the root Item
                                String templateItem = String.Format(StorageHelper.HttpMultipartContentTemplate, "root", jsonTemplate.ToString());
                                byte[] itemBytes    = Encoding.UTF8.GetBytes(templateItem);
                                stream.Write(itemBytes, 0, itemBytes.Length);
                                // Then terminating boundary
                                stream.Write(terminatorBytes, 0, terminatorBytes.Length);
                                stream.Close();
                            }

                            Tools.HttpDebugRequest(request);

                            // Make the request
                            request.BeginGetResponse(r2 =>
                            {
                                try
                                {
                                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2))
                                    {
                                        Tools.HttpDebugResponse(response);

                                        // If we get here it completed OK
                                        response.Close();
                                    }
                                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID), state);
                                }
                                catch (WebException webEx)
                                {
                                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                                }
                                catch (Exception ex)
                                {
                                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                                }
                            }, state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state);
                }
            }
            else
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, new RdfStorageException("Invalid template, templates must derive from BaseStardogTemplate")), state);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Executes the Asynchronous Request.
        /// </summary>
        /// <param name="asyncRequest">Asynchronous web request.</param>
        private void ExecAsyncRequestWithRetryPolicy(HttpWebRequest asyncRequest)
        {
            AsyncCallCompletedEventArgs resultArguments = null;

            // Check whether the Method is post.
            if (asyncRequest.Method == "POST")
            {
                // If true then ExecuteAction which calls the service using retry framework.
                this.context.IppConfiguration.RetryPolicy.ExecuteAction(
                    ac =>
                {
                    // Invoke the begin method of the asynchronous call.
                    asyncRequest.BeginGetRequestStream(ac, asyncRequest);
                },
                    ar =>
                {
                    // Invoke the end method of the asynchronous call.
                    HttpWebRequest request = (HttpWebRequest)ar.AsyncState;

                    //enabling header logging in Serilogger
                    WebHeaderCollection allHeaders = request.Headers;

                    CoreHelper.AdvancedLogging.Log(" RequestUrl: " + request.RequestUri);
                    CoreHelper.AdvancedLogging.Log("Logging all headers in the request:");

                    for (int i = 0; i < allHeaders.Count; i++)
                    {
                        CoreHelper.AdvancedLogging.Log(allHeaders.GetKey(i) + "-" + allHeaders[i]);
                    }

                    // Log Request Body to a file
                    this.RequestLogging.LogPlatformRequests(" RequestUrl: " + request.RequestUri + ", Request Payload: " + this.requestBody, true);
                    // Log Request Body to Serilog
                    CoreHelper.AdvancedLogging.Log(" Request Payload: " + this.requestBody);



                    // Using encoding get the byte value of the requestBody.
                    UTF8Encoding encoding = new UTF8Encoding();
                    byte[] content        = encoding.GetBytes(this.requestBody);

                    TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch");
                    this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, (int)traceSwitch.Level > (int)TraceLevel.Info ? "Adding the payload to request. \n Start dump: " + this.requestBody : "Adding the payload to request.");


                    // Check whether compression is enabled and compress the stream accordingly.
                    if (this.RequestCompressor != null)
                    {
                        // get the request stream.
                        using (var requeststream = request.EndGetRequestStream(ar))
                        {
                            this.RequestCompressor.Compress(content, requeststream);
                        }
                    }
                    else
                    {
                        // Get the Request stream.
                        using (System.IO.Stream postStream = request.EndGetRequestStream(ar))
                        {
                            // Write the byte content to the stream.
                            postStream.Write(content, 0, content.Length);
                        }
                    }
                },
                    () =>
                {
                    // Action to perform if the asynchronous operation
                    // succeeded.
                    this.ExecuteServiceCallAsync(asyncRequest);
                },
                    e =>
                {
                    // Action to perform if the asynchronous operation
                    // failed after all the retries.
                    IdsException idsException = e as IdsException;
                    if (idsException != null)
                    {
                        resultArguments = new AsyncCallCompletedEventArgs(null, idsException);
                    }
                    else
                    {
                        resultArguments = new AsyncCallCompletedEventArgs(null, new IdsException("Exception has been generated.", e));
                    }

                    this.OnCallCompleted(this, resultArguments);
                });
            }
            else
            {
                // Call the service without writing the request body to request stream.
                this.ExecuteServiceCallAsync(asyncRequest);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="handler">RDF Handler</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultGraph(IRdfHandler handler, String query, QueryCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
            request.Accept      = ResultsAcceptHeader;
            ApplyRequestOptions(request);
            Tools.HttpDebugRequest(request);

            request.BeginGetRequestStream(result =>
            {
                try
                {
                    Stream stream = request.EndGetRequestStream(result);
                    using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                    {
                        writer.Write("query=");
                        writer.Write(HttpUtility.UrlEncode(query));

                        foreach (String u in DefaultGraphs)
                        {
                            writer.Write("&default-graph-uri=");
                            writer.Write(HttpUtility.UrlEncode(u));
                        }
                        foreach (String u in NamedGraphs)
                        {
                            writer.Write("&named-graph-uri=");
                            writer.Write(HttpUtility.UrlEncode(u));
                        }

                        writer.Close();
                    }

                    request.BeginGetResponse(innerResult =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
                            Tools.HttpDebugResponse(response);
                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            parser.Load(handler, new StreamReader(response.GetResponseStream()));

                            callback(handler, null, state);
                        }
                        catch (SecurityException secEx)
                        {
                            callback(handler, null, new AsyncError(new RdfQueryException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                        }
                        catch (WebException webEx)
                        {
                            if (webEx.Response != null)
                            {
                                Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                            }
                            callback(handler, null, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                        }
                        catch (Exception ex)
                        {
                            callback(handler, null, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                        }
                    }, null);
                }
                catch (SecurityException secEx)
                {
                    callback(handler, null, new AsyncError(new RdfQueryException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                }
                catch (WebException webEx)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                    callback(handler, null, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                }
                catch (Exception ex)
                {
                    callback(handler, null, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                }
            }, null);
        }
Exemplo n.º 23
0
        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            // Get and fill the RequestState
            RequestState   state   = (RequestState)asynchronousResult.AsyncState;
            HttpWebRequest request = state.Request;

            string errorMsg = "PosterAsynch.GetRequestStreamCallback encountered WebException";

            try
            {
                // End the operation
                Stream postStream = request.EndGetRequestStream(asynchronousResult);

                // Write to the request stream.
                if (state.PostBytes == null)
                {
                    state.PostBytes = new byte[0];
                }
                postStream.Write(state.PostBytes, 0, state.PostBytes.Length);
                postStream.Close();
                postStream.Dispose();

                // Start the asynchronous operation to get the response
                IAsyncResult result = request.BeginGetResponse(new AsyncCallback(GetResponseCallback), state);
            }
            catch (WebException ex)
            {
                string StatusDescription = string.Empty;
                ex.Data.Add("Uri", state.Uri);
                ex.Data.Add("Verb", state.Verb);
                ex.Data.Add("WebException.Status", ex.Status);
                state.ErrorMessage           = errorMsg;
                state.Exception              = ex;
                state.WebExceptionStatusCode = ex.Status;

                if (ex.Response != null)
                {
                    state.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
                }
                else if (ex.Message.ToLower().Contains("request was aborted"))
                {
                    state.StatusCode  = HttpStatusCode.RequestTimeout;
                    StatusDescription = "Request cancelled by client because the server did not respond within timeout";
                }
                else
                {
                    state.StatusCode = (HttpStatusCode)(-2);
                }
                ex.Data.Add("StatusCode", state.StatusCode);
                ex.Data.Add("StatusDescription", StatusDescription);
                OnError(state);
                allDone.Set();
            }
            catch (Exception ex)
            {
                ex.Data.Add("Uri", state.Uri);
                ex.Data.Add("Verb", state.Verb);
                state.ErrorMessage = errorMsg;
                state.Exception    = ex;
                state.StatusCode   = (HttpStatusCode)(-2);
                OnError(state);
                allDone.Set();
            }
        }
Exemplo n.º 24
0
        internal static void WriteBody(this HttpWebRequest request, bool CompressRequestBody, byte[] data)
        {
#if NETSTANDARD1_1
            Stream outs = null;
            //outs = request.GetRequestStreamAsync().Result;
            //outs.Write(data, 0, (int)data.Length);
            //outs.Flush();
            //outs.Dispose();

            ManualResetEvent requestReady = new ManualResetEvent(initialState: false);
            Exception        caught       = null;

            AsyncCallback callback = new AsyncCallback(ar =>
            {
                //var request = (WebRequest)ar.AsyncState;
                try
                {
                    outs = request.EndGetRequestStream(ar);
                }
                catch (Exception ex)
                {
                    caught = ex;
                }
                finally
                {
                    requestReady.Set();
                }
            });

            var async = request.BeginGetRequestStream(callback, null);

            if (!async.IsCompleted)
            {
                //async.AsyncWaitHandle.WaitOne();
                // Not having thread affinity seems to work better with ManualResetEvent
                // Using AsyncWaitHandle.WaitOne() gave unpredictable results (in the
                // unit tests), when EndGetResponse would return null without any error
                // thrown
                requestReady.WaitOne();
                //async.AsyncWaitHandle.WaitOne();
            }
            else
            {
                // If the async wasn't finished, then we need to wait anyway
                if (!async.CompletedSynchronously)
                {
                    requestReady.WaitOne();
                }
            }

            if (caught != null)
            {
                throw caught;
            }

            outs.Write(data, 0, (int)data.Length);
            outs.Flush();
            outs.Dispose();
#else
            Stream outs;
            Stream compressor = null;
            if (CompressRequestBody)
            {
                request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
                compressor = request.GetRequestStream();
                outs       = new System.IO.Compression.GZipStream(compressor, System.IO.Compression.CompressionMode.Compress, true);
            }
            else
            {
                outs = request.GetRequestStream();
            }
            outs.Write(data, 0, (int)data.Length);
            outs.Flush();
            outs.Dispose();
            if (compressor != null)
            {
                compressor.Dispose();
            }
#endif
        }
Exemplo n.º 25
0
        /// <summary>
        /// 提交数据并获取返回内容
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Args"></param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public string PostFile(string Url, string Path)
        {
            string respHTML = "";
            //string szError = "";
            Exception Err = null;

            try {
                System.Net.HttpWebRequest httpReq;
                //System.Net.HttpWebResponse httpResp;
                System.Uri httpURL = new System.Uri(Url);

                httpReq        = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL);
                httpReq.Method = "POST";
                //httpReq.KeepAlive = true;
                httpReq.Credentials = CredentialCache.DefaultCredentials;
                httpReq.KeepAlive   = false;
                httpReq.Timeout     = 600000;
                httpReq.Headers.Add("Cookie", _cookies.ToString());

                string boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes      = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                httpReq.ContentType = "multipart/form-data; boundary=" + boundary;

                //byte[] bs = enc.GetBytes(Args);

                //httpReq.KeepAlive = false;
                //httpReq.ContentType = "application/x-www-form-urlencoded";
                //httpReq.ContentLength = bs.Length;
                //httpReq.

                //异步提交
                httpReq.BeginGetRequestStream(new AsyncCallback((IAsyncResult ar) => {
                    try {
                        HttpWebRequest hwr = ar.AsyncState as HttpWebRequest;

                        //post数据
                        using (System.IO.Stream reqStream = hwr.EndGetRequestStream(ar)) {
                            //reqStream.Write(bs, 0, bs.Length);
                            //reqStream.Flush();

                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                            byte[] buffer         = new byte[4096];
                            int bytesRead         = 0;
                            //for (int i = 0; i < files.Length; i++) {
                            reqStream.Write(boundarybytes, 0, boundarybytes.Length);
                            string header      = string.Format(headerTemplate, "file0", System.IO.Path.GetFileName(Path));
                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                            reqStream.Write(headerbytes, 0, headerbytes.Length);
                            using (System.IO.FileStream fileStream = new System.IO.FileStream(Path, FileMode.Open, FileAccess.Read)) {
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    reqStream.Write(buffer, 0, bytesRead);
                                }
                            }
                            //}

                            //1.3 form end
                            reqStream.Write(endbytes, 0, endbytes.Length);
                            //reqStream.Close();
                        }

                        //异步获取
                        hwr.BeginGetResponse(new AsyncCallback((IAsyncResult wrar) => {
                            try {
                                HttpWebRequest wrwr           = wrar.AsyncState as HttpWebRequest;
                                System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wrwr.EndGetResponse(wrar);
                                SetCookies("" + wr.Headers["Set-Cookie"]);

                                using (System.IO.Stream MyStream = wr.GetResponseStream()) {
                                    System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8);

                                    //byte[] TheBytes = new byte[MyStream.Length];
                                    //MyStream.Read(TheBytes, 0, (int)MyStream.Length);

                                    //respHTML = Encoding.UTF8.GetString(TheBytes);
                                    respHTML = reader.ReadToEnd();
                                    //Console.WriteLine(respHTML);

                                    reader.Dispose();
                                    MyStream.Dispose();
                                }
                            } catch (Exception ex) {
                                dpz2.Debug.WriteLine("BeginGetResponse:" + ex.Message);
                                //szError = ex.Message;
                                Err = ex;
                            }
                        }), hwr);
                    } catch (Exception ex) {
                        dpz2.Debug.WriteLine("BeginGetRequestStream:" + ex.Message);
                        Err = ex;
                    }
                }), httpReq);

                int  tick   = Environment.TickCount;
                bool bCheck = true;

                while (bCheck)
                {
                    if (Environment.TickCount - tick > 10)
                    {
                        tick = Environment.TickCount;
                        if (respHTML != "")
                        {
                            bCheck = false;
                            return(respHTML);
                        }
                        if (Err != null)
                        {
                            bCheck = false;
                            throw Err;
                        }
                    }
                    System.Threading.Thread.Sleep(1);
                }

                //httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse();

                //httpResp.Close();
                //httpReq = null;
            } catch (Exception ex) {
                throw new Exception("获取HTML发生异常", ex);
                //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url);
                //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")");
            }

            return(respHTML);
        }
Exemplo n.º 26
0
        private static void MakeRequest(string ContentType, string Method, string URL, object Parameters, Action <string> SuccessCallback, Action <WebException> FailCallback)
        {
            if (Parameters == null)
            {
                throw new ArgumentNullException("Parameters object cannot be null");
            }

            if (string.IsNullOrWhiteSpace(ContentType))
            {
                throw new ArgumentException("Content type is missing");
            }

            if (string.IsNullOrWhiteSpace(URL))
            {
                throw new ArgumentException("URL is empty");
            }

            if (Method != "HEAD" && Method != "GET" && Method != "POST" && Method != "DELETE" && Method != "PUT")
            {
                throw new ArgumentException("Invalid Method");
            }

            try
            {
                /*
                 * Create new Request
                 */
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URL));
                request.CookieContainer = cookies;
                request.Method          = Method;
                request.ContentType     = ContentType;

                request.UserAgent = UserAgent;

                if (Proxy != null)
                {
                    request.Proxy = Proxy;
                }


                /*
                 * Asynchronously get the response
                 */
                if (Method == "POST" || Method == "PUT" || Method == "DELETE")
                {
                    request.BeginGetRequestStream(new AsyncCallback((IAsyncResult callbackResult) =>
                    {
                        HttpWebRequest tmprequest = (HttpWebRequest)callbackResult.AsyncState;
                        Stream postStream;

                        postStream = tmprequest.EndGetRequestStream(callbackResult);


                        string postbody = "";


                        postbody = Utils.SerializeQueryString(Parameters);


                        // Convert the string into a byte array.
                        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postbody);

                        // Write to the request stream.
                        postStream.Write(byteArray, 0, byteArray.Length);
                        postStream.Flush();
                        postStream.Dispose();

                        // Start the asynchronous operation to get the response
                        tmprequest.BeginGetResponse(ProcessCallback(SuccessCallback, FailCallback), tmprequest);
                    }), request);
                }
                else if (Method == "GET" || Method == "HEAD")
                {
                    request.BeginGetResponse(ProcessCallback(SuccessCallback, FailCallback), request);
                }
            }
            catch (WebException webEx)
            {
                FailCallback(webEx);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 提交数据并获取返回内容
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Args"></param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public void DownFile(string Url, string Args, string Path)
        {
            //string respHTML = "";
            string szError = "";
            bool   bAccess = false;

            try {
                System.Net.HttpWebRequest httpReq;
                //System.Net.HttpWebResponse httpResp;
                System.Uri httpURL = new System.Uri(Url);

                httpReq        = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL);
                httpReq.Method = "POST";

                byte[] bs = System.Text.Encoding.UTF8.GetBytes(Args);

                //httpReq.KeepAlive = false;
                httpReq.ContentType = "application/x-www-form-urlencoded";
                httpReq.Headers.Add("Cookie", _cookies.ToString());

                //异步提交
                httpReq.BeginGetRequestStream(new AsyncCallback((IAsyncResult ar) => {
                    try {
                        HttpWebRequest hwr = ar.AsyncState as HttpWebRequest;

                        //post数据
                        using (System.IO.Stream reqStream = hwr.EndGetRequestStream(ar)) {
                            reqStream.Write(bs, 0, bs.Length);
                            reqStream.Flush();
                            //reqStream.Close();
                        }

                        //异步获取
                        hwr.BeginGetResponse(new AsyncCallback((IAsyncResult wrar) => {
                            try {
                                HttpWebRequest wrwr           = wrar.AsyncState as HttpWebRequest;
                                System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wrwr.EndGetResponse(wrar);
                                SetCookies("" + wr.Headers["Set-Cookie"]);

                                using (System.IO.Stream MyStream = wr.GetResponseStream()) {
                                    //System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8);

                                    //byte[] TheBytes = new byte[MyStream.Length];
                                    //MyStream.Read(TheBytes, 0, (int)MyStream.Length);

                                    using (FileStream fs = File.Create(Path)) {
                                        byte[] bytes = new byte[102400];
                                        int n        = 0;
                                        do
                                        {
                                            n = MyStream.Read(bytes, 0, 10240);
                                            fs.Write(bytes, 0, n);
                                        } while (n > 0);
                                    }

                                    //下载成功
                                    bAccess = true;

                                    //respHTML = Encoding.UTF8.GetString(TheBytes);
                                    //respHTML = reader.ReadToEnd();
                                    //Console.WriteLine(respHTML);

                                    //reader.Dispose();
                                    MyStream.Dispose();
                                }
                            } catch (Exception ex) {
                                dpz2.Debug.WriteLine("BeginGetResponse:" + ex.Message);
                                szError = ex.Message;
                            }
                        }), hwr);
                    } catch (Exception ex) {
                        dpz2.Debug.WriteLine("BeginGetRequestStream:" + ex.Message);
                    }
                }), httpReq);

                int  tick   = Environment.TickCount;
                bool bCheck = true;

                while (bCheck)
                {
                    if (Environment.TickCount - tick > 10)
                    {
                        tick = Environment.TickCount;
                        //if (respHTML != "") {
                        //    bCheck = false;
                        //    return respHTML;
                        //}
                        if (szError != "")
                        {
                            bCheck = false;
                            throw new Exception(szError);
                        }
                        if (bAccess)
                        {
                            bCheck = false;
                        }
                    }
                    System.Threading.Thread.Sleep(1);
                }

                //httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse();

                //httpResp.Close();
                //httpReq = null;
            } catch (Exception ex) {
                throw new Exception("获取HTML发生异常:" + ex.Message);
                //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url);
                //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")");
            }

            //return respHTML;
        }
Exemplo n.º 28
0
        private void RequestStreamCallback(IAsyncResult ar)
        {
            HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
            string         boundary = "----pluploadboundary" + DateTime.Now.Ticks, dashdash = "--", crlf = "\r\n";
            Stream         requestStream = null;

            byte[] buffer = new byte[1048576], strBuff;
            int    bytes;
            long   loaded = 0, end = 0;
            int    percent, lastPercent = 0;

            try {
                requestStream = request.EndGetRequestStream(ar);

                if (this.multipart)
                {
                    request.ContentType = "multipart/form-data; boundary=" + boundary;

                    // Add name to multipart array
                    this.multipartParams["name"] = this.targetName;

                    // Add chunking when needed
                    if (this.chunking)
                    {
                        this.multipartParams["chunk"]  = this.chunk;
                        this.multipartParams["chunks"] = this.chunks;
                    }

                    // Append mutlipart parameters
                    foreach (KeyValuePair <string, object> pair in this.multipartParams)
                    {
                        strBuff = this.StrToByteArray(dashdash + boundary + crlf +
                                                      "Content-Disposition: form-data; name=\"" + pair.Key + '"' + crlf + crlf +
                                                      pair.Value + crlf
                                                      );

                        requestStream.Write(strBuff, 0, strBuff.Length);
                    }

                    // Append multipart file header
                    strBuff = this.StrToByteArray(
                        dashdash + boundary + crlf +
                        "Content-Disposition: form-data; name=\"" + this.fileDataName + "\"; filename=\"" + this.name + '"' +
                        crlf + "Content-Type: " + this.mimeType + crlf + crlf
                        );

                    requestStream.Write(strBuff, 0, strBuff.Length);
                }
                else
                {
                    request.ContentType = "application/octet-stream";
                }

                // Move to start
                loaded = this.chunk * this.chunkSize;

                // Find end
                end = (this.chunk + 1) * this.chunkSize;
                if (end > this.Size)
                {
                    end = this.Size;
                }

                while (loaded < end && (bytes = ReadByteRange(buffer, loaded, 0, (int)(end - loaded < buffer.Length ? end - loaded : buffer.Length))) != 0)
                {
                    loaded += bytes;
                    percent = (int)Math.Round((double)loaded / (double)this.Size * 100.0);

                    if (percent > lastPercent)
                    {
                        syncContext.Post(delegate {
                            if (percent > lastPercent)
                            {
                                this.OnProgress(new ProgressEventArgs(loaded, this.Size));
                                lastPercent = percent;
                            }
                        }, this);
                    }

                    requestStream.Write(buffer, 0, bytes);
                    requestStream.Flush();
                }

                // Append multipart file footer
                if (this.multipart)
                {
                    strBuff = this.StrToByteArray(crlf + dashdash + boundary + dashdash + crlf);
                    requestStream.Write(strBuff, 0, strBuff.Length);
                }
            } catch (Exception ex) {
                syncContext.Send(delegate {
                    this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks));
                }, this);
            } finally {
                try {
                    if (requestStream != null)
                    {
                        requestStream.Close();
                        requestStream.Dispose();
                        requestStream = null;
                    }
                } catch (Exception ex) {
                    syncContext.Send(delegate {
                        this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks));
                    }, this);
                }
            }

            try {
                request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.RequestCanceled)
                {
                    syncContext.Send(delegate {
                        this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks));
                    }, this);
                }
            }
            catch (Exception ex) {
                syncContext.Send(delegate {
                    this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks));
                }, this);
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Ends the operation to gets a handle to the request content.
 /// </summary>
 /// <param name="asyncResult">IAsyncResult that represents an async operation.</param>
 /// <returns>The request content.</returns>
 public Stream EndGetRequestContent(IAsyncResult asyncResult)
 {
     return(_request.EndGetRequestStream(asyncResult));
 }
Exemplo n.º 30
0
Arquivo: test.cs Projeto: mono/gert
	static Stream EndGetRequestStreamWithTimeout (HttpWebRequest request, IAsyncResult asyncResult, RegisteredWaitHandle handle)
	{
		try {
			handle.Unregister (asyncResult.AsyncWaitHandle);

			return request.EndGetRequestStream (asyncResult);
		} catch (WebException ex) {
			if (ex.Status == WebExceptionStatus.RequestCanceled) {
				throw new WebException ("GetRequestStream operation has timed out.", WebExceptionStatus.Timeout);
			}

			throw;
		}
	}
 private void PostCallback(IAsyncResult asyncResult)
 {
     postData      = request.EndGetRequestStream(asyncResult);
     postCompleted = true;
 }