BeginGetResponse() public method

public BeginGetResponse ( System callback, object state ) : System.IAsyncResult
callback System
state object
return System.IAsyncResult
        public void BeginProcessRequest(Site site)
        {
            string sql = "";
            int iResult = 0;
            this.Site = site;

            oDataIO = new DataIO();
            SqlConnection Conn = new SqlConnection();
            Conn = oDataIO.GetDBConnection("ProfilesDB");
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = Conn;

            site.IsDone = false;
            _request = WebRequest.Create(site.URL);

            // Enter log record
            sql = "insert into [Direct.].LogOutgoing(FSID,SiteID,Details,SentDate,QueryString) "
                 + " values ('" + site.FSID.ToString() + "'," + site.SiteID.ToString() + ",0,GetDate()," + cs(site.SearchPhrase) + ")";
            sqlCmd.CommandText = sql;
            sqlCmd.CommandType = System.Data.CommandType.Text;
            iResult = sqlCmd.ExecuteNonQuery();

            if (sqlCmd.Connection.State == System.Data.ConnectionState.Open)
                sqlCmd.Connection.Close();

            _request.BeginGetResponse(new AsyncCallback(EndProcessRequest), site);
        }
Ejemplo n.º 2
0
        private void BingSupportedLanguageCodesFetched(IAsyncResult ar)
        {
            // Fetched language codes
            // Get the request details
            HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
            // Get the response details
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

            // Read the contents of the response into a string
            System.IO.Stream       streamResponse = response.GetResponseStream();
            System.IO.StreamReader streamRead     = new System.IO.StreamReader(streamResponse);
            string langCodes = streamRead.ReadToEnd();

            ApplicationData.Current.LocalSettings.Values["supportedLanguageCodes"] = langCodes;

            // We have language codes. Fetch the language names as well
            try
            {
                string uriForNames = "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguageNames?locale=en&languageCodes=" + langCodes;
                System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uriForNames);
                // The authorization header needs to be "Bearer" + " " + the access token
                string headerValue = "Bearer " + AdmAccessToken._admAccessToken.access_token;
                translationWebRequest.Headers["Authorization"] = headerValue;
                // And now we call the service. When the translation is complete, we'll get the callback
                IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(BingSupportedLanguageNamesFetched), translationWebRequest);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Something bad happened while fetching language names" + ex.Message);
            }
        }
Ejemplo n.º 3
0
        public void Check(string currentVersion, Action<bool, Update[]> callback)
        {
            responseCallback = callback;
            webRequest = WebRequest.Create(string.Format(UpdateUrl, currentVersion));

            webRequest.BeginGetResponse(new AsyncCallback(finishRequest), null);
        }
Ejemplo n.º 4
0
 IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
     AsyncCallback cb, object state)
 {
     Trace.Write("BeginAsyncOperation");
     _request = WebRequest.Create("http://msdn.microsoft.com");
     return _request.BeginGetResponse(cb, state);
 }
        public ImageBrowser()
        {
            InitializeComponent();

            //Get list of stock photos
            Uri uri = new Uri("http://docs.xamarin.com/demo/stock.json");
            request = WebRequest.Create(uri);
            request.BeginGetResponse(WebRequestCallback, null);
        }
Ejemplo n.º 6
0
 private async Task StartWebRequest()
 {
     requester = (HttpWebRequest)WebRequest.Create(url);
     requester.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
     GettingData(BEGINDOWNLOAD);
     while (!go)
         await Task.Delay(500);
     GettingData(ENDDOWNLOAD);
 }
Ejemplo n.º 7
0
 private void BeginRequest(WebRequest request, AsyncCallback callback, object state)
 {
     var result = request.BeginGetResponse(callback, state);
     ClientEngine.MainLoop.QueueTimeout(RequestTimeout, delegate
     {
         if (!result.IsCompleted)
             request.Abort();
         return false;
     });
 }
 public void Get(WebRequest request, Action<HttpStatusCode, Stream> onComplete, Action<Uri, Exception> onError)
 {
     SetStandardHeaders(request);
     request.BeginGetResponse(HandleResponseCallback,
                              new RequestContext
                                  {
                                      Request = request,
                                      OnComplete = (code, s, entity) => onComplete(code, entity),
                                      OnError = onError,
                                  });
 }
Ejemplo n.º 9
0
 private void UploadStringRequestAsyncCallback(IAsyncResult result)
 {
     try {
         object[] bag    = (result.AsyncState as object[]);
         byte[]   data   = (bag [0] as byte[]);
         Stream   stream = request.EndGetRequestStream(result);
         stream.Write(data, 0, data.Length);
         request.BeginGetResponse(new AsyncCallback(UploadStringResponseAsyncCallback), bag [1]);
     }
     catch {
         request.Abort();
         throw;
     }
 }
 internal void WriteStreamClosedCallback(object WebClientData, long length)
 {
     try
     {
         request.BeginGetResponse(OpenWriteAsyncResponseCallback, WebClientData);
     }
     catch (Exception e)
     {
         callback_data.sync_context.Post(delegate(object sender)
         {
             OnWriteStreamClosed(new WriteStreamClosedEventArgs(e));
         }, null);
     }
     finally
     {
         // kind of dummy, 0% progress, that is always emitted
         upload_length = length;
         callback_data.sync_context.Post(delegate(object sender)
         {
             OnUploadProgressChanged(
                 new UploadProgressChangedEventArgs(0, -1, length, -1, 0, callback_data.user_token));
         }, null);
     }
 }
Ejemplo n.º 11
0
 private static void DoWithResponse(WebRequest request, Action<HttpWebResponse> responseAction)
 {
     Action wrapperAction = () =>
     {
         request.BeginGetResponse(iar =>
         {
             var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);
             responseAction(response);
         }, request);
     };
     wrapperAction.BeginInvoke(iar =>
     {
         var action = (Action)iar.AsyncState;
         action.EndInvoke(iar);
     }, wrapperAction);
 }
        public void SearchForPlaceAync(GooglePlaceSearchRequest searchRequest)
        {
            var language = searchRequest.Language.HasValue ? Enum.GetName(typeof(GoogleMapsLanguage), searchRequest.Language.Value).Replace("_", "-") : null;
                var types = searchRequest.Types == null ? string.Empty : string.Join("|", searchRequest.Types);
                var requestUrl = string.Format(GooglePlacesAPI_Url, _appId, searchRequest.Sensor.ToString().ToLower(), searchRequest.Keyword);
                _webRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                _webRequest.Method = "Post";

                try
                {
                    _webRequest.BeginGetResponse(ResponseCallback, new List<object> { _webRequest, searchRequest });
                }
                catch (Exception e)
                {
                    SearchForPlacesAsyncFailed(e.Message, e);
                }
        }
Ejemplo n.º 13
0
 private void FetchBingSupportedLanguageCodes()
 {
     try
     {
         string uriForCodes = "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate";
         System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uriForCodes);
         // The authorization header needs to be "Bearer" + " " + the access token
         string headerValue = "Bearer " + AdmAccessToken._admAccessToken.access_token;
         translationWebRequest.Headers["Authorization"] = headerValue;
         // And now we call the service. When the translation is complete, we'll get the callback
         IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(BingSupportedLanguageCodesFetched), translationWebRequest);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Something bad happened while fetching language codes" + ex.Message);
     }
 }
Ejemplo n.º 14
0
        private static void RequestAsync(WebRequest request, byte[] bodyBytes, Action<TrackResult> callback)
        {
            request.BeginGetRequestStream((r1) =>
            {
                try
                {
                    var stream = request.EndGetRequestStream(r1);
                    stream.BeginWrite(bodyBytes, 0, bodyBytes.Length, (r2) =>
                    {
                        try
                        {
                            stream.EndWrite(r2);
                            stream.Dispose();

                            request.BeginGetResponse((r3) =>
                            {
                                try
                                {
                                    using (var response = request.EndGetResponse(r3))
                                    {
                                        using (var reader = new StreamReader(response.GetResponseStream()))
                                        {
                                            if (callback != null)
                                                callback(new TrackResult(reader.ReadToEnd()));
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HandleError(callback, ex);
                                }
                            }, null);
                        }
                        catch (Exception ex)
                        {
                            HandleError(callback, ex);
                        }
                    }, null);
                }
                catch(Exception ex)
                {
                    HandleError(callback, ex);
                }
            }, null);
        }
        private static WebResponse GetResponseInternal(WebRequest request)
        {            
            // build the envent
			using (var revent = new ManualResetEvent(false))
			{
				// start the async call
				IAsyncResult result = request.BeginGetResponse(new AsyncCallback(CallStreamCallback), revent);

				// wait for event
				revent.WaitOne();

				// get the response
				WebResponse response = request.EndGetResponse(result);

				// go ahead
				return response;
			}
        }
Ejemplo n.º 16
0
        public void Execute()
        {
            MobeelizerConfigurationSection section = (MobeelizerConfigurationSection)ConfigurationManager.GetSection("mobeelizer-configuration");
            String propUrl = null;

            String mode = null;
            try
            {
                propUrl = section.AppSettings[META_URL].Value;
            }
            catch (KeyNotFoundException) { }

            try
            {
                mode = section.AppSettings[META_MODE].Value;
            }
            catch (KeyNotFoundException) { }

            StringBuilder baseUrlBuilder = new StringBuilder();
            if (propUrl == null)
            {
                baseUrlBuilder.Append(Resources.Config.c_apiURL_host);
            }
            else
            {
                baseUrlBuilder.Append(propUrl);
            }

            baseUrlBuilder.Append(Resources.Config.c_apiURL_path);

            if ("test".Equals(mode.ToLower()))
            {
                baseUrlBuilder.Append("?test=true");
            }
            else
            {
                baseUrlBuilder.Append("?test=false");
            }
            baseUrlBuilder.Append("&disablecache=" + Guid.NewGuid());

            Uri url = new Uri(baseUrlBuilder.ToString());
            request = WebRequest.Create(url);
            request.BeginGetResponse(OnBeginGetResponse, null);
        }
Ejemplo n.º 17
0
 private void SendTranslateViaBingRequest()
 {
     try
     {
         string strLngFrom = ApplicationData.Current.LocalSettings.Values["tramslateFromLanguage"].ToString();
         string strLngTo   = ApplicationData.Current.LocalSettings.Values["tramslateToLanguage"].ToString();
         string uri        = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + WebUtility.UrlEncode(strTextToTranslate) + "&from=" + strLngFrom + "&to=" + strLngTo;
         System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uri);
         // The authorization header needs to be "Bearer" + " " + the access token
         string headerValue = "Bearer " + AdmAccessToken._admAccessToken.access_token;
         translationWebRequest.Headers["Authorization"] = headerValue;
         // And now we call the service. When the translation is complete, we'll get the callback
         IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(BingTranslationReady), translationWebRequest);
         strTextToTranslate = "";
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Something bad happened " + ex.Message);
     }
 }
Ejemplo n.º 18
0
        public Task <byte[]> UploadValuesTaskAsync(string address, NameValueCollection names)
        {
            return(Task <byte[]> .Factory.StartNew(() =>
            {
                WebRequest request = this.GetWebRequest(new Uri(address));
                request.ContentType = "text/plain; charset=utf-8";
                request.Method = "POST";

                byte[] data = null;

                request.BeginGetRequestStream(new AsyncCallback((IAsyncResult res) =>
                {
                    using (Stream postStream = request.EndGetRequestStream(res))
                    {
                        StringBuilder postParamBuilder = new StringBuilder();
                        foreach (var key in names.Keys)
                        {
                            postParamBuilder.Append(String.Format("{0}={1}&", key, names[key]));
                        }

                        byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString());
                        postStream.Write(byteArray, 0, byteArray.Length);
                        postStream.Close();

                        request.BeginGetResponse(new AsyncCallback((IAsyncResult nres) =>
                        {
                            using (Stream respStream = request.EndGetResponse(nres).GetResponseStream())
                            {
                                data = new byte[respStream.Length];
                                respStream.Write(data, 0, data.Length);
                            }
                        }), null);
                    }
                }), null);

                while (data == null)
                {
                }
                return data;
            }));
        }
Ejemplo n.º 19
0
        public void OpenReadAsync(Uri address, object userToken)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            lock (locker) {
                SetBusy();

                try {
                    request = SetupRequest(address, "GET", new CallbackData(userToken));
                    request.BeginGetResponse(new AsyncCallback(OpenReadAsyncCallback), null);
                }
                catch (Exception e) {
                    WebException wex = new WebException("Could not start operation.", e);
                    OnOpenReadCompleted(
                        new OpenReadCompletedEventArgs(null, wex, false, userToken));
                }
            }
        }
Ejemplo n.º 20
0
        private WebQueryAsyncResult ExecuteGetOrDeleteAsync(ICache cache, 
                                                            string key, 
                                                            string url, 
                                                            WebRequest request,
                                                            object userState)
        {
            var fetch = cache.Get<Stream>(key);
            if (fetch != null)
            {
                var args = new WebQueryResponseEventArgs(fetch);
                OnQueryResponse(args);

                var result = new WebQueryAsyncResult
                {
                    CompletedSynchronously = true
                };
                return result;
            }
            else
            {
                var state = new Triplet<WebRequest, Pair<ICache, string>, object>
                                {
                                    First = request,
                                    Second = new Pair<ICache, string>
                                                 {
                                        First = cache,
                                        Second = key
                                    },
                                    Third = userState
                                };

                var args = new WebQueryRequestEventArgs(url);
                OnQueryRequest(args);

                var inner = request.BeginGetResponse(GetAsyncResponseCallback, state);
                RegisterAbortTimer(request, inner); 
                var result = new WebQueryAsyncResult { InnerResult = inner };
                return result;
            }
        }
 private void Start()
 {
     try
     {
         request = System.Net.WebRequest.Create(requestURI);
         request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy();
         if (null != postData)
         {
             request.ContentLength = postData.Length;
             request.ContentType = "application/x-www-form-urlencoded";
             request.Method = "POST";
             request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), request);
         }
         else
         {
             request.Method = "GET";
             request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
         }
     }
     catch (OutOfMemoryException e)
     {
         if (retryCount < retryMax)
         {
             System.Diagnostics.Debug.WriteLine(e.Message);
             ++retryCount;
             Random random = new Random();
             Thread.Sleep(retryDelay * random.Next(retryCount * retryCount));
             Start();
         }
         else
         {
             OnException(e);
         }
     }
     catch (Exception e)
     {
         OnException(e);
     }
 }
Ejemplo n.º 22
0
        private void GetResponseCallback(IAsyncResult ar)
        {
            HttpWebRequest  request  = (HttpWebRequest)ar.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
                                                                                          System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
                AdmAccessToken token =
                    (AdmAccessToken)serializer.ReadObject(response.GetResponseStream());

                string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Net.HttpUtility.UrlEncode(strTextToTranslate) + "&from=" + strLngFrom + "&to=" + strLngTo;
                System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uri);

                string headerValue = "Bearer " + token.access_token;
                translationWebRequest.Headers["Authorization"] = headerValue;

                IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(translationReady), translationWebRequest);
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 23
0
 private void ButtonSearch_Click(object sender, RoutedEventArgs e)
 {
     if (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
     {
         if (BookToSearch.Text.Equals("") || BookToSearch.Text == "" || BookToSearch.Text == null)
         {
             MessageBox.Show("请输入需要搜索的书名或者关键字!");
         }
         else
         {
             string BookTitle = BookToSearch.Text;
             string url       = @"http://api.douban.com/v2/book/search?q=" + @BookTitle; //get book info from douban.com
             downDelegate = setConent;
             System.Net.WebRequest request = HttpWebRequest.Create(url);
             IAsyncResult          result  = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request); //async web request
         }
     }
     else
     {
         Debug.WriteLine("[DEBUG]Network Interface Available Status:" + NetworkInterface.GetIsNetworkAvailable());
         Debug.WriteLine("[DEBUG]Network Interface Type Status:" + NetworkInterface.NetworkInterfaceType);
         MessageBox.Show("搜索书籍信息需要网络连接,请开启手机的移动网络。");
     }
 }
Ejemplo n.º 24
0
        private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data)
        {
            Debug.Assert(ar != null);
            Debug.Assert(request != null);
            Debug.Assert(data != null);
            Debug.Assert(data.Length > 0);

            try
            {
                using (var output = request.EndGetRequestStream(ar))
                    output.Write(data, 0, data.Length);
                request.BeginGetResponse(OnGetResponseCompleted, request);
            }
            catch (Exception e)
            {
                OnWebPostError(request, e);
            }
        }
Ejemplo n.º 25
0
        private void HandleResponse(WebRequest request)
        {
            WebResponse response = null;
            Stream responseStream = null;
            StreamReader responseStreamReader = null;

            request.BeginGetResponse((responseResult) =>
                {
                    try
                    {
                        response = request.EndGetResponse(responseResult);

                        responseStream = response.GetResponseStream();
                        responseStreamReader = new StreamReader(responseStream);
                        ResponseText = responseStreamReader.ReadToEnd();
                    }
                    finally
                    {
                        try { if (response != null) response.Dispose(); }
                        catch { }
                        try { if (responseStream != null) responseStream.Dispose(); }
                        catch { }
                        try { if (responseStreamReader != null) ((IDisposable)responseStreamReader).Dispose(); }
                        catch { }

                        DisableProgressIndicator();
                    }
                }, null);
        }
Ejemplo n.º 26
0
		public void OpenReadAsync (Uri address, object userToken)
		{
			if (address == null)
				throw new ArgumentNullException ("address");

			lock (locker) {
				SetBusy ();

				try {
					request = SetupRequest (address, "GET", new CallbackData (userToken));
					request.BeginGetResponse (new AsyncCallback (OpenReadAsyncCallback), null);
				}
				catch (Exception e) {
					WebException wex = new WebException ("Could not start operation.", e);
					OnOpenReadCompleted (
						new OpenReadCompletedEventArgs (null, wex, false, userToken));
				}
			}
		}
Ejemplo n.º 27
0
        public void SendRequest()
        {
            try
            {
                Request = WebRequest.Create(Url);
                Request.Method = HttpMethod;
                Request.ContentType = HttpMIMEType;

                if (!HttpVerifyCert)
                {
                    // We could hijack Connection Group Name to identify
                    // a desired security exception.  But at the moment we'll use a dummy header instead.
//                    Request.ConnectionGroupName = "NoVerify";
                    Request.Headers.Add("NoVerifyCert", "true");
                }
//                else
//                {
//                    Request.ConnectionGroupName="Verify";
//                }
                if (!HttpPragmaNoCache)
                {
                    Request.Headers.Add("Pragma", "no-cache");
                }
                if (HttpCustomHeaders != null)
                {
                    for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
                        Request.Headers.Add(HttpCustomHeaders[i],
                                            HttpCustomHeaders[i+1]);
                }
                if (!string.IsNullOrEmpty(proxyurl))
                {
                    if (!string.IsNullOrEmpty(proxyexcepts))
                    {
                        string[] elist = proxyexcepts.Split(';');
                        Request.Proxy = new WebProxy(proxyurl, true, elist);
                    }
                    else
                    {
                        Request.Proxy = new WebProxy(proxyurl, true);
                    }
                }

                if (ResponseHeaders != null)
                {
                    foreach (KeyValuePair<string, string> entry in ResponseHeaders)
                        if (entry.Key.ToLower().Equals("user-agent") && Request is HttpWebRequest)
                            ((HttpWebRequest)Request).UserAgent = entry.Value;
                        else
                            Request.Headers[entry.Key] = entry.Value;
                }

                // Encode outbound data
                if (!string.IsNullOrEmpty(OutboundBody))
                {
                    byte[] data = Util.UTF8.GetBytes(OutboundBody);

                    Request.ContentLength = data.Length;
                    using (Stream bstream = Request.GetRequestStream())
                        bstream.Write(data, 0, data.Length);
                }

                try
                {
                    IAsyncResult result = (IAsyncResult)Request.BeginGetResponse(ResponseCallback, null);

                    ThreadPool.RegisterWaitForSingleObject(
                        result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true);
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.ProtocolError)
                    {
                        throw;
                    }

                    HttpWebResponse response = (HttpWebResponse)e.Response;

                    Status = (int)response.StatusCode;
                    ResponseBody = response.StatusDescription;
                    _finished = true;
                }
            }
            catch (Exception e)
            {
//                m_log.Debug(
//                    string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1}  ", Url, ItemID), e);

                Status = (int)OSHttpStatusCode.ClientErrorJoker;
                ResponseBody = e.Message;
                _finished = true;
            }
        }
Ejemplo n.º 28
0
        private static Task<HttpWebResponse> GetResponseWithRetryAsync(WebRequest request, int retries)
        {
            if (retries < 0)
                throw new ArgumentOutOfRangeException("Invalid number of retries to make");

            Func<Task<WebResponse>, Task<HttpWebResponse>> proceedToNextStep = null;

            Func<Task<HttpWebResponse>> doStep = () =>
            {
                var ds = Task.Factory.FromAsync(
                    (asyncCallback, state) => request.BeginGetResponse(asyncCallback, state),
                    (asyncResult) => request.EndGetResponse(asyncResult),
                    null
                );
                return ds.ContinueWith(proceedToNextStep).Unwrap();
            };

            proceedToNextStep = (prevTask) =>
            {
                if (prevTask.IsCanceled)
                    throw new TaskCanceledException();
                if (prevTask.IsFaulted && --retries > 0)
                    return doStep();

                var tcs = new TaskCompletionSource<HttpWebResponse>();
                tcs.SetResult((HttpWebResponse)prevTask.Result);
                return tcs.Task;
            };
            return doStep();
        }
Ejemplo n.º 29
0
 internal virtual WebResponse GetResponse(WebRequest request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     HttpWebRequest request2 = request as HttpWebRequest;
     TimeoutState state = null;
     if ((request2 != null) && (request2.Timeout > 0))
     {
         state = new TimeoutState(request2);
     }
     this._webRequest = request;
     WebRequestState state2 = new WebRequestState(request);
     IAsyncResult result = request.BeginGetResponse(new AsyncCallback(WebRequestPSCmdlet.ResponseCallback), state2);
     if (state != null)
     {
         ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(WebRequestPSCmdlet.TimeoutCallback), state, state.httpRequest.Timeout, true);
     }
     state2.waithandle.WaitOne(-1, false);
     this._webRequest = null;
     if (state2.webException == null)
     {
         return state2.response;
     }
     if (((state != null) && state.abort) && state2.webException.Status.Equals(WebExceptionStatus.RequestCanceled))
     {
         throw new WebException(WebCmdletStrings.RequestTimeout, WebExceptionStatus.Timeout);
     }
     throw state2.webException;
 }
Ejemplo n.º 30
0
 private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data)
 {
     try {
         using (var output = request.EndGetRequestStream(ar)) {
             output.Write(data, 0, data.Length);
         }
         request.BeginGetResponse(OnGetResponseCompleted, request);
     }
     catch (Exception e) {
         OnWebPostError(request, e);
     }
 }
 /// <summary>
 /// Begins download process.
 /// </summary>
 public void Download()
 {
     _downloadStatus.ProgressBar.Information = Languages.AppResources.downloadNewSurveys_Downloading;
     _downloadStatus.ProgressBar.IsEnabled = true;
     _downloadStatus.CanCancel = true;
     _downloadStatus.IsCanceled = false;
     try
     {
         _request = WebRequest.Create(_downloadUrl);
         var result = (IAsyncResult)_request.BeginGetResponse(DownloadCallback, _request);
     }
     catch (WebException)
     {
         _downloadStatus.Message.Show(Languages.AppResources.downloadNewSurveys_CantDownloading);
     }
 }
Ejemplo n.º 32
0
        private HttpWebResponse SmartGetWebResponse(WebRequest req)
        {
            try
            {
                if (req == null)
                    return null;

                IAsyncResult arGet = req.BeginGetResponse(null, null);
                if (!arGet.AsyncWaitHandle.WaitOne(DEFAULT_READ_TIMEOUT))
                {
                    return null;
                }
                return req.EndGetResponse(arGet) as HttpWebResponse;
            }
            catch (Exception ex)
            {
                bool bShouldLog = true;
                
                WebException exw = ex as WebException;
                if (exw != null)
                {
                    if (exw.Status == WebExceptionStatus.RequestCanceled)
                    {
                        bShouldLog = false;
                    }
                    else if (exw.Status == WebExceptionStatus.ProtocolError)
                    {
                        try
                        {
                            System.Net.HttpWebResponse httpRes = exw.Response as System.Net.HttpWebResponse;
                            if (httpRes != null && httpRes.StatusCode == HttpStatusCode.NotFound)
                            {
                                SetFeedActive(false, false);
                                FirePropertyChangedAction(false);
                                LongSmartSleep(FEED_NOT_ACTIVE_SLEEP_SECS, "SmartGetWebResponse - Inactive Stream (404)"); // sleeping for 15 minutes on this stream!
                            }
                        }
                        catch { }
                    }
                }
                if (bShouldLog)
                {
                    Common.DebugHelper.WriteExceptionToLog("WaveStreamProcessor.SmartGetWebResponse", ex, false, _streamURL);
                }
                return null;
            }
        }
                internal AsyncMetadataLocationRetriever(WebRequest request, long maxMessageSize, XmlDictionaryReaderQuotas readerQuotas, TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.maxMessageSize = maxMessageSize;
                    this.readerQuotas = readerQuotas;
                    IAsyncResult result = request.BeginGetResponse(Fx.ThunkCallback(new AsyncCallback(this.GetResponseCallback)), request);

                    //Register a callback to abort the request if we hit the timeout.
                    ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,
                        Fx.ThunkCallback(new WaitOrTimerCallback(RetrieveTimeout)), request,
                        TimeoutHelper.ToMilliseconds(timeoutHelper.RemainingTime()), /* executeOnlyOnce */ true);

                    if (result.CompletedSynchronously)
                    {
                        HandleResult(result);
                        this.Complete(true);
                    }
                }
Ejemplo n.º 34
0
 public IPAddressAsyn(string url, int millisecondsTimeout)
 {
     WebRequest = WebRequest.Create(url);
     WebRequest.Timeout = millisecondsTimeout;
     WebRequest.BeginGetResponse(GetResponseCallback, null);
 }
 public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     return(_internalWebRequest.BeginGetResponse(callback, state));
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Loads this <see cref="RssFeed"/> instance asynchronously using the specified <see cref="Uri"/>, <see cref="SyndicationResourceLoadSettings"/>, <see cref="ICredentials"/>, and <see cref="IWebProxy"/>.
        /// </summary>
        /// <param name="source">A <see cref="Uri"/> that represents the URL of the syndication resource XML data.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the <see cref="RssFeed"/> instance. This value can be <b>null</b>.</param>
        /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param>
        /// <param name="userToken">A user-defined object that is passed to the method invoked when the asynchronous operation completes.</param>
        /// <remarks>
        ///     <para>
        ///         To receive notification when the operation has completed or the operation has been canceled, add an event handler to the <see cref="Loaded"/> event. 
        ///         You can cancel a <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/> operation by calling the <see cref="LoadAsyncCancel()"/> method.
        ///     </para>
        ///     <para>
        ///         After calling <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/>, 
        ///         you must wait for the load operation to complete before attempting to load the syndication resource using the <see cref="LoadAsync(Uri, Object)"/> method.
        ///     </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="FormatException">The <paramref name="source"/> data does not conform to the expected syndication content format. In this case, the feed remains empty.</exception>
        /// <exception cref="InvalidOperationException">This <see cref="RssFeed"/> has a <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/> call in progress.</exception>
        public void LoadAsync(Uri source, SyndicationResourceLoadSettings settings, WebRequestOptions options, Object userToken)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");

            //------------------------------------------------------------
            //	Use default settings if none specified by the caller
            //------------------------------------------------------------
            if (settings == null)
            {
                settings    = new SyndicationResourceLoadSettings();
            }

            //------------------------------------------------------------
            //	Validate syndication resource state
            //------------------------------------------------------------
            if (this.LoadOperationInProgress)
            {
                throw new InvalidOperationException();
            }

            //------------------------------------------------------------
            //	Indicate that a load operation is in progress
            //------------------------------------------------------------
            this.LoadOperationInProgress    = true;

            //------------------------------------------------------------
            //	Reset the asynchronous load operation cancelled indicator
            //------------------------------------------------------------
            this.AsyncLoadHasBeenCancelled  = false;

            //------------------------------------------------------------
            //	Build HTTP web request used to retrieve the syndication resource
            //------------------------------------------------------------
            asyncHttpWebRequest         = SyndicationEncodingUtility.CreateWebRequest(source, options);
            asyncHttpWebRequest.Timeout = Convert.ToInt32(settings.Timeout.TotalMilliseconds, System.Globalization.NumberFormatInfo.InvariantInfo);

            //------------------------------------------------------------
            //	Get the async response to the web request
            //------------------------------------------------------------
            object[] state      = new object[6] { asyncHttpWebRequest, this, source, settings, options, userToken };
            IAsyncResult result = asyncHttpWebRequest.BeginGetResponse(new AsyncCallback(AsyncLoadCallback), state);

            //------------------------------------------------------------
            //  Register the timeout callback
            //------------------------------------------------------------
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(AsyncTimeoutCallback), state, settings.Timeout, true);
        }
Ejemplo n.º 37
0
 public void requestFrame()
 {
     request = System.Net.HttpWebRequest.Create(cameraUrl);
     request.Credentials = new NetworkCredential("admin", "12345");
     request.Proxy = null;
     request.BeginGetResponse(OnfinishRequestFrame, request);
     
 }
Ejemplo n.º 38
0
        private void _IrosHPost(IntPtr handle, ref IrosHPostData data)
        {
            string url   = Marshal.PtrToStringAnsi(data.url);
            string ctype = Marshal.PtrToStringAnsi(data.contentType);

            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
            req.ContentType = ctype;
            //req.Method = data.len > 0 ? "POST" : "GET";
            req.Method = "POST";

            TraceLogger(String.Format("{3}ing {2} bytes to {0} handle {1}", url, handle, data.len, req.Method));

            byte[] buffer = new byte[data.len];
            Marshal.Copy(data.data, buffer, 0, buffer.Length);

            WebTask t = new WebTask()
            {
                Req = req, Handle = handle, writeBack = data.writeBack
            };

            _http[handle] = t;

            AsyncCallback doResponse = ar2 => {
                try {
                    var resp = req.EndGetResponse(ar2);
                    var rs   = req.GetResponse().GetResponseStream();
                    t.Async = rs.BeginRead(t.ReceiveBuffer, 0, t.ReceiveBuffer.Length, AsyncReceive, t);
                } catch (WebException e) {
                    ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString()));
                    t.ReceiveDone = true;
                    if (e.Response != null)
                    {
                        t.Status = (int)((HttpWebResponse)e.Response).StatusCode;
                    }
                    else
                    {
                        t.Status = 500;
                    }
                }
                catch (Exception e)
                {
                    ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString()));
                    t.ReceiveDone = true;
                    t.Status      = 500;
                }
            };

            t.ReceiveBuffer = new byte[0x10000];

            if (buffer.Length > 0)
            {
                t.Async = req.BeginGetRequestStream(ar => {
                    var s = req.EndGetRequestStream(ar);
                    using (s) {
                        s.Write(buffer, 0, buffer.Length);
                    }
                    t.Completed = t.Size = buffer.Length;
                    TraceLogger(String.Format("Beginning GetResponse for {0}", handle));
                    t.Async = req.BeginGetResponse(doResponse, t);
                }, t);
            }
            else
            {
                TraceLogger(String.Format("Beginning GetResponse [no request data] for {0}", handle));
                t.Async = req.BeginGetResponse(doResponse, t);
            }
        }
Ejemplo n.º 39
0
        public byte[] Download(WebRequest req, UpdateProgessCallback progressCB)
        {
            // Ensure flag set correctly.
            allDone.Reset();

            // Create the state object.
            DownloadInfo info = new DownloadInfo();

            // Put the request into the state object so it can be passed around.
            info.Request = req;

            // Assign the callbacks
            info.ProgressCallback += progressCB;

            // Issue the async request.
            IAsyncResult r = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseCallback), info);

            // Wait until the ManualResetEvent is set so that the application
            // does not exit until after the callback is called.
            allDone.WaitOne();

            // Pass back the downloaded information.

            if (info.useFastBuffers)
                return info.dataBufferFast;
            else
            {
                byte[] data = new byte[info.dataBufferSlow.Count];
                for (int b = 0; b < info.dataBufferSlow.Count; b++)
                    data[b] = (byte)info.dataBufferSlow[b];
                return data;
            }
        }
Ejemplo n.º 40
0
 private void IGrabShardList()
 {
     fShardReq = WebRequest.Create("http://mud.hoikas.com/shards.xml");
     fShardReq.BeginGetResponse(new AsyncCallback(IGotShardList), null);
 }
Ejemplo n.º 41
0
        public bool StartRequest(string requestUri, int timeout, ICredentials credentials)
        {
            if (onResponse == null) return false;

            request = WebRequest.Create(requestUri);
            if (credentials != null)
                request.Credentials = credentials;

            try
            {
                var rst = request.BeginGetResponse(RequestCompleted, null);
                ThreadPool.RegisterWaitForSingleObject(rst.AsyncWaitHandle,
                    TimeoutCallback, request, timeout, true);
                requestInProcess = true;
            }
            catch (Exception ex)
            {
                Logger.Error("AsynchWebRequest.StartRequest", ex);
                return false;
            }
            return true;
        }