コード例 #1
0
        private void OnEventResponseReceived(IAsyncResult ar)
        {
            AsyncRequestState state = (AsyncRequestState)ar.AsyncState;

            try
            {
                HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(ar);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // When one callback URL succeeded, break event notification for this SID
                    lock (_serverData.SyncObj)
                    {
                        _pendingRequests.Remove(state);
                        return;
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    e.Response.Close();
                }
            }
            // Try next callback URL
            ContinueEventNotification(state);
        }
コード例 #2
0
        private void AsyncDownload()
        {
            AsyncRequestState state = null;

            try {
                state = new AsyncRequestState();
                var req = GetRequest();
                state.request = req;

                // creates asynchronous request
                var result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseAsyncCallback), state);

                // creates timeout thread
                ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, Timeout, true);
                asyncCounter.WaitOne();
            } catch (Exception ex) {
                threadException = ex;
            } finally {
                if (state != null)
                {
                    if (state.response != null)
                    {
                        state.response.Close();
                    }
                }
            }
        }
コード例 #3
0
        private static void OnGetAccountInfoForVerifing(AsyncRequestState asyncRequestState, bool allowOnFailure, Action <ApplicationAccount> callback)
        {
            ApplicationAccount account;
            var appId = asyncRequestState.AppId.ToString();

            try
            {
                switch (asyncRequestState.ResultCode)
                {
                case AccountServiceResult.Ok:
                    account = new ApplicationAccount(appId, asyncRequestState.ResultCode, asyncRequestState.RequestResult);
                    break;

                case AccountServiceResult.NotFound:
                    account = new ApplicationAccount(appId, asyncRequestState.ResultCode, false, ErrorMessages.InvalidAppId);
                    break;

                default:
                    account = new ApplicationAccount(appId, asyncRequestState.ResultCode, allowOnFailure, asyncRequestState.ErrorMessage);
                    break;
                }
            }
            catch (Exception e)
            {
                log.Warn(e);
                account = new ApplicationAccount(appId, AccountServiceResult.Error, allowOnFailure, e.Message);
            }
            callback(account);
        }
コード例 #4
0
        /// <summary>
        /// Tries to send the event message specified by the given <paramref name="state"/> object to the next
        /// available event callback URL, if present.
        /// </summary>
        private void ContinueEventNotification(AsyncRequestState state)
        {
            IEnumerator <string> e = state.PendingCallbackURLs.GetEnumerator();

            if (!e.MoveNext())
            {
                lock (_serverData.SyncObj)
                    _pendingRequests.Remove(state);
                return;
            }
            string callbackURL = e.Current;

            state.PendingCallbackURLs.Remove(callbackURL);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(callbackURL);

            NetworkUtils.SetLocalEndpoint(request, _config.EndPointIPAddress);
            request.Method      = "NOTIFY";
            request.KeepAlive   = false;
            request.ContentType = "text/xml; charset=\"utf-8\"";
            request.Headers.Add("NT", "upnp:event");
            request.Headers.Add("NTS", "upnp:propchange");
            request.Headers.Add("SID", _sid);
            request.Headers.Add("SEQ", _eventingState.EventKey.ToString());
            state.Request = request;

            // First get the request stream...
            IAsyncResult result = state.Request.BeginGetRequestStream(OnEventGetRequestStream, state);

            NetworkHelper.AddTimeout(request, result, PENDING_EVENT_NOTIFICATION_TIMEOUT * 1000);
        }
コード例 #5
0
        public async Task <AsyncRequestState <T> > DownloadAsync <T>(
            CrawlStep crawlStep,
            CrawlStep referrer,
            DownloadMethod method,
            Action <AsyncRequestState <T> > completed,
            Action <DownloadProgressEventArgs> progress, T state)
        {
            AspectF.Define.
            NotNull(crawlStep, "crawlStep");

            if (UserAgent.IsNullOrEmpty())
            {
                UserAgent = "Mozilla/5.0";
            }

            AsyncRequestState <T> requestState = new AsyncRequestState <T>
            {
                CrawlStep        = crawlStep,
                Referrer         = referrer,
                State            = state,
                DownloadProgress = progress,
                Retry            = RetryCount.HasValue ? RetryCount.Value + 1 : 1,
                Method           = method,
            };

            return(await DownloadAsync(requestState));
        }
コード例 #6
0
 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
 {
     var reqState = new AsyncRequestState(context, cb, extraData);
     _processRequest = OnProcessRequest;
     new Thread(new AsyncRequest(reqState).ProcessRequest).Start(_processRequest);
     return reqState;
 }
コード例 #7
0
 public void UnregisterClient(AsyncRequestState state)
 {
     lock (_lock)
     {
         _clientStateList.Remove(state);
     }
 }
コード例 #8
0
        private static void FinishWebRequest(IAsyncResult result)
        {
            AsyncRequestState requestState = (result.AsyncState as AsyncRequestState);

            var             updateContent = string.Empty;
            HttpWebResponse response      = requestState.Request.EndGetResponse(result) as HttpWebResponse;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        updateContent = reader.ReadToEnd();
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(updateContent))
            {
                var update = JsonConvert.DeserializeObject <DtoBeeConfig>(updateContent);
                if (update.BeeConfigLastUpdate > requestState.Config.BeeConfigLastUpdate)
                {
                    using (var writer = new StreamWriter(_CacheFilePath, false, System.Text.Encoding.UTF8))
                    {
                        writer.WriteLine(updateContent);
                    }
                    _BeeConfigKeyValues = JsonConvert.DeserializeObject <ConcurrentDictionary <string, string> >(JsonConvert.SerializeObject(update.BeeConfigData));
                }
            }
        }
コード例 #9
0
        private static void GetTmpMonitoringFromResponse(AsyncRequestState requestState, string uri, string jsonResult)
        {
            //TODO?
//            try
//            {
//                var tmpApplicationAccount = JsonConvert.DeserializeObject<TmpApplicationAccount>(jsonResult);
//                if (tmpApplicationAccount == null)
//                {
//                    log.ErrorFormat("Account service: Error while deserializing application account: appId={0}, url={1}, result='{2}'",
//                        requestState.AppId, uri, jsonResult);
//                }
//                else
//                {
//                    if (log.IsDebugEnabled)
//                    {
//                        LogApplicationAccount("GetApplicationInfo: ", requestState.AppId, tmpApplicationAccount, requestState.Stopwatch.ElapsedMilliseconds);
//                    }

            requestState.ResultCode    = MonitoringServiceResult.Ok;
            requestState.RequestResult = jsonResult;
//                }
//            }
//            catch (Exception e)
//            {
//                log.Error(string.Format("Account service: Exception while deserializing application account: appId={0}, url={1}, result={2}, Exception Msg:{3}",
//                    requestState.AppId, uri, jsonResult, e.Message), e);
//            }
        }
コード例 #10
0
//        public void TryGetMonitoringResult(string application, Action<MonitoringServiceResult, ExternalApiInfoList> callback)
//        {
//            try
//            {
//                if (callback == null)
//                {
//                    throw new ArgumentNullException("callback");
//                }
//
//                if (string.IsNullOrEmpty(application))
//                {
//                    throw new ArgumentException("'application' can not be null or empty string");
//                }
//
//                Guid id;
//                if (Guid.TryParse(application, out id) == false)
//                {
//                    log.WarnFormat("TryGetExternalApiInfo: Invalid Application ID format: {0}. No external API info loaded for app ID {1}.", application, id);
//                    callback(MonitoringServiceResult.Error, null);
//                    return;
//                }
//
//                this.TryGetMonitoringResultAsync(id, asyncRequestState => OnGetMonitoringResult(asyncRequestState, callback));
//                return;
//            }
//            catch (Exception ex)
//            {
//                log.Error(ex);
//            }
//
//            log.WarnFormat("AccountService.GetApplication: No external API info loaded for app ID {0}.", application);
//            callback(MonitoringServiceResult.Error, null);
//        }

        #endregion

        #region Private Methods

        #region Async Mode Code

        private static void OnGetMonitorResultForVerifing(AsyncRequestState asyncRequestState, Action <MonitoringResult, object> callback, object state)
        {
            MonitoringResult result;
            var appId = asyncRequestState.AppId.ToString();

            try
            {
                switch (asyncRequestState.ResultCode)
                {
                case MonitoringServiceResult.Ok:
//                        account = new ApplicationAccount(appId, asyncRequestState.ResultCode, asyncRequestState.RequestResult);
                    result = new MonitoringResult(appId, asyncRequestState.ResultCode, asyncRequestState.RequestResult, null);
                    break;

                case MonitoringServiceResult.NotFound:
                    //                        account = new ApplicationAccount(appId, asyncRequestState.ResultCode, false, ErrorMessages.InvalidAppId);
                    result = new MonitoringResult(appId, asyncRequestState.ResultCode, null, "Invalid AppId");
                    break;

                default:
                    //                        account = new ApplicationAccount(appId, asyncRequestState.ResultCode, allowOnFailure, asyncRequestState.ErrorMessage);
                    result = new MonitoringResult(appId, asyncRequestState.ResultCode, null, asyncRequestState.ErrorMessage);
                    break;
                }
            }
            catch (Exception e)
            {
                log.Warn(e);
                //                account = new ApplicationAccount(appId, AccountServiceResult.Error, allowOnFailure, e.Message);
                result = new MonitoringResult(appId, MonitoringServiceResult.Error, null, e.Message);
            }
            callback(result, state);
        }
コード例 #11
0
 public void UnregisterClient(AsyncRequestState state)
 {
     lock (_lock)
     {
         _clientStateList.Remove(state);
     }
 }
コード例 #12
0
        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            AsyncRequestState state = (AsyncRequestState)asynchronousResult.AsyncState;

            state.cancelTimeout();
            HttpWebRequest request = state.Request;

            try
            {
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                if (state.OutgoingData != null)
                {
                    if (state.type == MessageType.CONNECT)
                    {
                        byte[] tcpheader = new byte[7] {
                            0xfb, 0, 0, 0, 0, 0, 0x1
                        };

                        writeLenght(tcpheader, state.OutgoingData.Length + tcpheader.Length, 1);
                        postStream.Write(tcpheader, 0, tcpheader.Length);
                    }
                    postStream.Write(state.OutgoingData, 0, state.OutgoingData.Length);
                }
                postStream.Close();
                IAsyncResult result = request.BeginGetResponse(new AsyncCallback(this.GetResponseCallback), state);
                state.asyncResult = result;
            }
            catch (WebException webEx)
            {
                _webExceptionHandler(state, request, webEx);
            }
        }
コード例 #13
0
        private static void GetTmpAccountFromResponse(AsyncRequestState requestState, string uri, string jsonResult)
        {
            try
            {
                var tmpApplicationAccount = JsonConvert.DeserializeObject <TmpApplicationAccount>(jsonResult);
                if (tmpApplicationAccount == null)
                {
                    log.ErrorFormat("Account service: Error while deserializing application account: appId={0}, url={1}, result='{2}'",
                                    requestState.AppId, uri, jsonResult);
                }
                else
                {
                    if (log.IsDebugEnabled)
                    {
                        LogApplicationAccount("GetApplicationInfo: ", requestState.AppId, tmpApplicationAccount, requestState.Stopwatch.ElapsedMilliseconds);
                    }

                    requestState.ResultCode    = AccountServiceResult.Ok;
                    requestState.RequestResult = tmpApplicationAccount;
                }
            }
            catch (Exception e)
            {
                log.Error(string.Format("Account service: Exception while deserializing application account: appId={0}, url={1}, result={2}, Exception Msg:{3}",
                                        requestState.AppId, uri, jsonResult, e.Message), e);
            }
        }
コード例 #14
0
        private void OnGetAccountInfoFromAccountStorage(AsyncRequestState asyncRequestState,
                                                        Action <AsyncRequestState> callback)
        {
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Got response from account service. Result:{0}, appId: {1}", asyncRequestState.ResultCode, asyncRequestState.AppId);
            }

            try
            {
                Counter.IncrementAccountServiceRequests(asyncRequestState.Stopwatch.ElapsedTicks);

                this.healthController.OnGetResponseFromAccountService(asyncRequestState);

                switch (asyncRequestState.ResultCode)
                {
                case AccountServiceResult.Ok:
                    break;

                case AccountServiceResult.Timeout:
                    Counter.IncrementAccountServiceTimeouts();
                    break;

                default:
                    Counter.IncrementAccountServiceServiceErrors();
                    break;
                }
            }
            catch (Exception e)
            {
                log.Warn(e);
            }
            callback(asyncRequestState);
        }
コード例 #15
0
        private void OnGetAccountInfoFromFallbackBlobStorage(AsyncRequestState asyncRequestState, Action <AsyncRequestState> callback)
        {
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Got response from fallback storage. Result:{0}, appId: {1}", asyncRequestState.ResultCode, asyncRequestState.AppId);
            }

            Counter.IncrementFallbackBlobServiceRequests(asyncRequestState.Stopwatch.ElapsedTicks);

            this.healthController.OnGetResponseFromBlobstore(asyncRequestState);

            var triggerBlobStorageCacheRefresh = false;

            switch (asyncRequestState.ResultCode)
            {
            case AccountServiceResult.Ok:
                callback(asyncRequestState);
                return;

            case AccountServiceResult.NotFound:
                triggerBlobStorageCacheRefresh = true;
                Counter.IncrementFallbackBlobServiceCacheMisses();
                break;

            case AccountServiceResult.Timeout:
                Counter.IncrementFallbackBlobServiceTimeouts();
                break;

            case AccountServiceResult.Error:
                Counter.IncrementFallbackBlobServiceErrors();
                break;
            }

            this.CallToAccountServiceQueue(asyncRequestState, callback, triggerBlobStorageCacheRefresh);
        }
コード例 #16
0
        private static void CallComplete <T>(AsyncRequestState <T> requestState, HttpWebResponse response)
        {
            var endTime = DateTime.UtcNow;

            if (response != null)
            {
                requestState.CallComplete(
                    new PropertyBag
                {
                    Step                    = requestState.CrawlStep,
                    CharacterSet            = response.CharacterSet,
                    ContentEncoding         = response.ContentEncoding,
                    ContentType             = response.ContentType,
                    Headers                 = response.Headers,
                    IsMutuallyAuthenticated = response.IsMutuallyAuthenticated,
                    IsFromCache             = response.IsFromCache,
                    LastModified            = response.LastModified,
                    Method                  = response.Method,
                    ProtocolVersion         = response.ProtocolVersion,
                    ResponseUri             = response.ResponseUri,
                    Server                  = response.Server,
                    StatusCode              = response.StatusCode,
                    StatusDescription       = response.StatusDescription,
                    GetResponse             = requestState.ResponseBuffer.IsNull()
                                ? (Func <Stream>)(() => new MemoryStream())
                                : requestState.ResponseBuffer.GetReaderStream,
                    EndTime      = endTime,
                    StartTime    = requestState.StartTime,
                    DownloadTime = requestState.StartTime - endTime,
                }, null);
            }
            else
            {
                requestState.CallComplete(
                    new PropertyBag
                {
                    Step                    = requestState.CrawlStep,
                    CharacterSet            = string.Empty,
                    ContentEncoding         = null,
                    ContentType             = null,
                    Headers                 = null,
                    IsMutuallyAuthenticated = false,
                    IsFromCache             = false,
                    LastModified            = DateTime.Now,
                    Method                  = string.Empty,
                    ProtocolVersion         = null,
                    ResponseUri             = null,
                    Server                  = string.Empty,
                    StatusCode              = HttpStatusCode.Forbidden,
                    StatusDescription       = string.Empty,
                    GetResponse             = requestState.ResponseBuffer.IsNull()
                                ? (Func <Stream>)(() => new MemoryStream())
                                : requestState.ResponseBuffer.GetReaderStream,
                    EndTime      = endTime,
                    StartTime    = requestState.StartTime,
                    DownloadTime = requestState.StartTime - endTime,
                }, null);
            }
        }
コード例 #17
0
 public void RegicterClient(AsyncRequestState state)
 {
     lock (_lock)
     {
         state.ClientGuid = Guid.NewGuid().ToString("N");
         _clientStateList.Add(state);
     }
 }
コード例 #18
0
 public void RegicterClient(AsyncRequestState state)
 {
     lock (_lock)
     {
         state.ClientGuid = Guid.NewGuid().ToString("N");
         _clientStateList.Add(state);
     }
 }
コード例 #19
0
        /// <summary>
        /// Start downloading of the request as continuation for the retry.
        /// </summary>
        /// <typeparam name="T">Type of the state object.</typeparam>
        /// <param name="requestState">Request state.</param>
        /// <returns>Task which return request state on completition.</returns>
        private async Task <AsyncRequestState <T> > DownloadWithRetryAsync <T>(AsyncRequestState <T> requestState)
        {
            if (RetryWaitDuration.HasValue)
            {
                await Task.Delay(RetryWaitDuration.Value);
            }

            return(await DownloadAsync(requestState));
        }
コード例 #20
0
    public void EndProcessRequest(IAsyncResult ar)
    {
        AsyncRequestState ars = ar as AsyncRequestState;

        if (ars != null)
        {
            // here you could perform some cleanup, write something else to the
            // Response, or whatever else you need to do
        }
    }
コード例 #21
0
        private static void OnGetAccountInfoForExternalApiUpdate(AsyncRequestState asyncRequestState,
                                                                 Action <AccountServiceResult, ExternalApiInfoList> callback)
        {
            ExternalApiInfoList apiList = null;

            if (asyncRequestState.ResultCode == AccountServiceResult.Ok)
            {
                apiList = asyncRequestState.RequestResult.ExternalApiInfoList ?? new ExternalApiInfoList();
            }
            callback(asyncRequestState.ResultCode, apiList);
        }
コード例 #22
0
 public void UpdateClient(AsyncRequestState state, String guid)
 {
     lock (_lock)
     {
         AsyncRequestState clientState = _clientStateList.Find(s => s.ClientGuid == guid);
         if (clientState != null)
         {
             clientState.CurrentContext = state.CurrentContext;
             clientState.ExtraData      = state.ExtraData;
             clientState.AsyncCallback  = state.AsyncCallback;
         }
     }
 }
コード例 #23
0
 public void UpdateClient(AsyncRequestState state, String guid)
 {
     lock (_lock)
     {
         AsyncRequestState clientState = _clientStateList.Find(s => s.ClientGuid == guid);
         if (clientState != null)
         {
             clientState.CurrentContext = state.CurrentContext;
             clientState.ExtraData = state.ExtraData;
             clientState.AsyncCallback = state.AsyncCallback;
         }
     }
 }
コード例 #24
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            AsyncRequestState state   = (AsyncRequestState)asynchronousResult.AsyncState;
            HttpWebRequest    request = state.Request;

            state.cancelTimeout();
            byte[] responseData = null;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
                {
                    if (state.IsDisconnect)
                    {
                        state.Base.EnqueueActionForDispatch(delegate
                        {
                            state.Base.Disconnected();
                        });
                        response.Close();
                        return;
                    }
                    using (Stream streamResponse = response.GetResponseStream())
                    {
                        using (BinaryReader binReader = new BinaryReader(streamResponse))
                        {
                            responseData = binReader.ReadBytes((int)response.ContentLength);
                            streamResponse.Close();
                            binReader.Close();
                        }
                    }
                    response.Close();
                }
                if (responseData.Length > 0)
                {
                    state.Base.ReceiveIncomingCommands(responseData, responseData.Length);
                }
                Interlocked.Exchange(ref state.Base._grossErrorCount, 0);
            }
            catch (WebException webEx)
            {
                _webExceptionHandler(state, request, webEx);
                return;
            }
            lock (state.Base._requestCache)
            {
                state.Base._checkAckCondition();
                state.Base._requestCache.Remove(state.id);
                state.Request      = null;
                state.OutgoingData = null;
            }
        }
コード例 #25
0
        private static void TimeoutCallback(object stateObject, bool timedOut)
        {
            AsyncRequestState state = stateObject as AsyncRequestState;

            if ((timedOut && (state != null)) && (state.Request != null))
            {
                if (state.Base.debugOut >= DebugLevel.WARNING)
                {
                    state.Base.Listener.DebugReturn(DebugLevel.WARNING, string.Format("Request {0} for pid={1} cid={2} aborted by timeout", state.id, state.Base.HttpPeerID, state.Base._challengId));
                }
                state.Aborted = true;
                state.Request.Abort();
            }
        }
コード例 #26
0
        private void TryGetApplicationAccountAsync(HttpRequestQueue httpQueue, Guid appId, string url, string username,
                                                   string password, Action <AsyncRequestState> onGetAccountInfoCallback, int retriesCount = DefaultRetriesCount)
        {
            var logGuard          = httpQueue == this.blobHttpQueue ? this.blobHttpQueueLogGuard : this.accountServiceHttpQueueLogGuard;
            var asyncRequestState = new AsyncRequestState(appId, httpQueue,
                                                          onGetAccountInfoCallback,
                                                          httpQueue == this.blobHttpQueue,
                                                          logGuard);

            var uri     = string.Format(url, appId);
            var request = this.GetWebRequest(uri, username, password, logGuard);

            httpQueue.Enqueue(request, HttpRequestQueueCallbackAsync, asyncRequestState, retriesCount);
        }
コード例 #27
0
    public IAsyncResult BeginProcessRequest(HttpContext ctx,
                                            AsyncCallback cb,
                                            object obj)
    {
        AsyncRequestState reqState =
            new AsyncRequestState(ctx, cb, obj);
        AsyncRequest ar = new AsyncRequest(reqState);
        ThreadStart  ts = new ThreadStart(ar.ProcessRequest);
        Thread       t  = new Thread(ts);

        t.Start();

        return(reqState);
    }
コード例 #28
0
        public void RegisterCodeForRecovery(string email, ProgressIndicator pi)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                AsyncRequest      async             = new AsyncRequest(pi, this.Page);
                AsyncRequestState asyncRequestState = new AsyncRequestState(async.XMLConsumption);
                async.Invoke(5000, asyncRequestState, string.Format("http://www.thinkbackpacking.com/DatingDiary/Register.php?email={0}&pin={1}", email, ((SetPassCode)Page).txtRetype.Text));

                //return new SetPassCodeResult() { Success = asyncRequestState.success, Message = asyncRequestState.success ? "Your pass code has been set" : "There was an error in connecting the remote server. Your pass code has not been set" };
            }
            else
            {
                MessageBox.Show("You do not have any connectivity to complete the operation at this time", "Information", MessageBoxButton.OK);
            }
            //return new SetPassCodeResult() { Success = false, Message = "You do not have any connectivity to complete the operation at this time" };
        }
コード例 #29
0
        private static void _webExceptionHandler(AsyncRequestState state, HttpWebRequest request, WebException webEx)
        {
            HttpWebResponse response = (HttpWebResponse)webEx.Response;

            if ((((state.Base.peerConnectionState != PeerBase.ConnectionStateValue.Disconnecting) || (state.Base.peerConnectionState != PeerBase.ConnectionStateValue.Disconnected)) && !state.restarting) && (state.Base.debugOut >= DebugLevel.ERROR))
            {
                if (response != null)
                {
                    int subCode = _getStatusCodeFromResponse(response, state.Base);
                    state.Base.Listener.DebugReturn(DebugLevel.ERROR, string.Format("Request {0} for pid={1} cid={2} failed with exception {3}, msg: {4}, status code: {5}, reason: {6}", state.id, state.Base.HttpPeerID, state.Base._challengId, webEx.Status, webEx.Message, subCode, response.StatusDescription));
                }
                else
                {
                    state.Base.Listener.DebugReturn(DebugLevel.ERROR, string.Format("Request {0} for pid={1} cid={2} failed with exception {3}, msg: {4}", state.id, state.Base.HttpPeerID, state.Base._challengId, webEx.Status, webEx.Message));
                }
            }
            if (state.Base.peerConnectionState == PeerBase.ConnectionStateValue.Connecting)
            {
                state.Base.EnqueueErrorDisconnect(StatusCode.ExceptionOnConnect);
            }
            else if (state.IsDisconnect || (state.Base.peerConnectionState != PeerBase.ConnectionStateValue.Connected))
            {
                state.Base.Listener.DebugReturn(DebugLevel.ERROR, string.Format("pid={0} cid={1} is already disconnected", state.Base.HttpPeerID, state.Base._challengId));
            }
            else if (state.Aborted)
            {
                state.Base.EnqueueErrorDisconnect(StatusCode.TimeoutDisconnect);
            }
            else if (response != null)
            {
                if (_gotIgnoreStatus(response.StatusCode))
                {
                    if (state.Base.debugOut >= DebugLevel.ALL)
                    {
                        state.Base.Listener.DebugReturn(DebugLevel.ALL, "got statues which we ignore");
                    }
                }
                else
                {
                    state.Base.EnqueueErrorDisconnect(StatusCode.DisconnectByServer);
                }
            }
            else
            {
                _handleError(state, request, webEx);
            }
        }
コード例 #30
0
        private void TryGetMonitoringResultAsync(HttpRequestQueue httpQueue, Guid appId, string servernames, string url, /*string username,
                                                                                                                         *  string password,*/Action <AsyncRequestState> onGetMonitoringInfoCallback)
        {
            var logGuard          = /*httpQueue == this.blobHttpQueue ? this.blobHttpQueueLogGuard :*/ this.monitoringServiceHttpQueueLogGuard;
            var asyncRequestState = new AsyncRequestState(appId, httpQueue,
                                                          onGetMonitoringInfoCallback,
                                                          /*httpQueue == this.blobHttpQueue,*/
                                                          logGuard);

            //TODO
            var uri     = string.Format(url, servernames);
            var request = this.GetWebRequest(uri, /*username, password,*/ logGuard);

            const int RETRY_COUNT = 3;

            httpQueue.Enqueue(request, HttpRequestQueueCallbackAsync, asyncRequestState, RETRY_COUNT);
        }
コード例 #31
0
        private void OnGetAccountInfoFromBlobStorage(AsyncRequestState asyncRequestState,
                                                     Action <AsyncRequestState> callback)
        {
            Counter.IncrementBlobServiceRequests(asyncRequestState.Stopwatch.ElapsedTicks);

            this.healthController.OnGetResponseFromBlobstore(asyncRequestState);

            var triggerBlobStorageCacheRefresh = false;

            switch (asyncRequestState.ResultCode)
            {
            case AccountServiceResult.Ok:
                callback(asyncRequestState);
                return;

            case AccountServiceResult.NotFound:
                triggerBlobStorageCacheRefresh = true;
                Counter.IncrementBlobServiceCacheMisses();
                break;

            case AccountServiceResult.Timeout:
                Counter.IncrementBlobServiceTimeouts();
                break;

            case AccountServiceResult.Error:
                Counter.IncrementBlobServiceErrors();
                break;
            }

            if (asyncRequestState.ResultCode != AccountServiceResult.NotFound)
            {
                if (!string.IsNullOrEmpty(this.fallBackBlobServiceUrl))
                {
                    this.CallToFallbackQueue(asyncRequestState, callback);
                }
                else
                {
                    log.WarnFormat(FallbackStoreLogGuard, "No fallback storage configured for account manager. BlobStore url:{0}", this.blobServiceUrl);
                }

                return;
            }

            this.CallToAccountServiceQueue(asyncRequestState, callback, triggerBlobStorageCacheRefresh);
        }
コード例 #32
0
        private void OnEventGetRequestStream(IAsyncResult ar)
        {
            AsyncRequestState state = (AsyncRequestState)ar.AsyncState;

            try
            {
                Stream requestStream = state.Request.EndGetRequestStream(ar);
                // ... then write to it...
                requestStream.Write(state.MessageData, 0, state.MessageData.Length);
                requestStream.Close();
                // ... and get the response
                IAsyncResult result = state.Request.BeginGetResponse(OnEventResponseReceived, state);
                NetworkHelper.AddTimeout(state.Request, result, PENDING_EVENT_NOTIFICATION_TIMEOUT * 1000);
            }
            catch (IOException) { }
            catch (WebException) { }
            ContinueEventNotification(state);
        }
コード例 #33
0
ファイル: HTTP.cs プロジェクト: seamusic/TicketHelper
 public static void AddState(AsyncRequestState state)
 {
     if (ListenForm != null)
     {
         if (ListenForm.InvokeRequired)
         {
             ListenForm.Invoke(new Func<AsyncRequestState>(AddState), state);
         }
         else
         {
             BindingRequestStates.Add(state);
         }
     }
     else
     {
         BindingRequestStates.Add(state);
     }
 }
コード例 #34
0
 private static void _handleError(AsyncRequestState state, HttpWebRequest request, WebException webEx)
 {
     if (_isExceptionGross(webEx.Status))
     {
         Interlocked.Increment(ref state.Base._grossErrorCount);
     }
     if (state.Base._grossErrorCount >= 3)
     {
         if (state.Base.debugOut >= DebugLevel.ALL)
         {
             state.Base.Listener.DebugReturn(DebugLevel.ALL, "limit of gross errors reached. Connection closed");
         }
         state.Base.EnqueueErrorDisconnect(StatusCode.InternalReceiveException);
     }
     else
     {
         _rerequestState(state, state.Base.UrlParameters, request);
     }
 }
コード例 #35
0
        internal void Request(byte[] data, string urlParameter, MessageType type)
        {
            int id = Interlocked.Increment(ref this._stateIdBase);

            this._addAckId(ref urlParameter);
            AsyncRequestState state = new AsyncRequestState()
            {
                Base         = this,
                OutgoingData = data,
                type         = type,
                id           = id
            };

            lock (this._requestCache)
            {
                this._requestCache.Add(id, state);
            }
            this.Request(state, urlParameter);
        }
コード例 #36
0
        private void AsyncDownload()
        {
            AsyncRequestState state = null;
            try {
                state = new AsyncRequestState();
                var req = GetRequest();
                state.request = req;

                // creates asynchronous request
                var result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseAsyncCallback), state);

                // creates timeout thread
                ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, Timeout, true);
                asyncCounter.WaitOne();

            } finally {
                if (state != null) {
                    if (state.response != null) {
                        state.response.Close();
                    }
                }
            }
        }
コード例 #37
0
ファイル: Session.cs プロジェクト: OPCFoundation/UA-.NET
        /// <summary>
        /// Removes a completed async request.
        /// </summary>
        private void AsyncRequestCompleted(IAsyncResult result, uint requestId, uint typeId)
        {
            lock (m_outstandingRequests)
            {
                // remove the request.
                AsyncRequestState state = RemoveRequest(result, requestId, typeId);
                
                if (state != null)
                {
                    // mark any old requests as default (i.e. the should have returned before this request).
                    DateTime maxAge = state.Timestamp.AddSeconds(-1);

                    for (LinkedListNode<AsyncRequestState> ii = m_outstandingRequests.First; ii != null; ii = ii.Next)
                    {
                        if (ii.Value.RequestTypeId == typeId && ii.Value.Timestamp < maxAge)
                        {
                            ii.Value.Defunct = true;
                        }
                    }
                }

                // add a dummy placeholder since the begin request has not completed yet.
                if (state == null)
                {
                    state = new AsyncRequestState();

                    state.Defunct = true;
                    state.RequestId  = requestId;
                    state.RequestTypeId = typeId;
                    state.Result = result;
                    state.Timestamp = DateTime.UtcNow;

                    m_outstandingRequests.AddLast(state);
                }
            }
        }
コード例 #38
0
ファイル: Session.cs プロジェクト: OPCFoundation/UA-.NET
        /// <summary>
        /// Adds a new async request.
        /// </summary>
        private void AsyncRequestStarted(IAsyncResult result, uint requestId, uint typeId)
        {
            lock (m_outstandingRequests)
            {
                // check if the request completed asynchronously.
                AsyncRequestState state = RemoveRequest(result, requestId, typeId);
                
                // add a new request.
                if (state == null)
                {
                    state = new AsyncRequestState();

                    state.Defunct = false;
                    state.RequestId  = requestId;
                    state.RequestTypeId = typeId;
                    state.Result = result;
                    state.Timestamp = DateTime.UtcNow;

                    m_outstandingRequests.AddLast(state);
                }
            }
        }
コード例 #39
0
ファイル: HTTP.cs プロジェクト: seamusic/TicketHelper
 public static void RetryRequest(AsyncRequestState state)
 {
     bool isPost = "POST".Equals(state.UserRequest.Method, StringComparison.OrdinalIgnoreCase);
     var request = CreateRequest(isPost, state.UserRequest.Url, RunTimeData.Cookies, state.UserRequest.Referer, state.UserRequest.Timeout, state.UserRequest.ReadWriteTimeout);
     state.InnerRequest = request;
     state.StorageStream.Position = 0;
     state.StorageStream.SetLength(0);
     state.ReadStream = null;
     state.WriteStream = null;
     state.ContentType = null;
     state.ContentEncoding = null;
     _BeginRequest(state);
 }
コード例 #40
0
        //////////////////////////////////////////////////////////////////////////////
        ///main routine implements asynchronous Stream.Copy
        public Stream Do()
        {
            if (source == null)
            throw new ArgumentNullException("source");

              ////////////////////////////////////////////////////////////////////////////
              // declare the callback to handle write completions.
              AsyncCallback writeCompleteCallback = new AsyncCallback(WriteCompleteCallback);

              ////////////////////////////////////////////////////////////////////////////
              /// start a request timer
              //double elapsedTime, CPUtime, CPUutilization;
              //IOexamples.Timer time = new IOexamples.Timer();
              //time.timerReset();

              ////////////////////////////////////////////////////////////////////////////
              /// destination?
              if (target == null)
              {
            try
            {
              target = new BufferedStream(source, BufferSize);
            }
            catch
            {
              target = new MemoryStream();
            }
              }

              ////////////////////////////////////////////////////////////////////////////
              ///  files are open, initialize async request structures.
              try
              {
            totalBytes = source.Length;               // Size of source file
              }
              catch { }
              for (int i = 0; i < BUFFERS; i++)           // initialize the request structure to point to each request.
            request[i] = new AsyncRequestState(i, this.BufferSize);

              ////////////////////////////////////////////////////////////////////////////
              // launch initial async reads
              for (int i = 0; i < BUFFERS; i++)
              {                                         // no callback on reads.
            request[i].ReadAsyncResult =
              source.BeginRead(request[i].Buffer, 0, BufferSize, null, i);
            request[i].ReadLaunched.Set();          // say that read is launched
            lock (_mutex)
              pending++;
              }

              ////////////////////////////////////////////////////////////////////////////
              // wait for the reads to complete in order, process buffer and then write it.
              for (int i = 0; (bytesRead < totalBytes || totalBytes == 0); i = (i + 1) % BUFFERS)
              {
            request[i].ReadLaunched.WaitOne();      // wait for flag that says buffer is reading
            int bytes =                             // wait for read complete
              source.EndRead(request[i].ReadAsyncResult);
            bytesRead += bytes;                     // process the buffer <your code goes here>
            target.BeginWrite(request[i].Buffer     // write it
              , 0, bytes, writeCompleteCallback, i);
              }                                         // end of reader loop

              ////////////////////////////////////////////////////////////////////////////
              // IOs started now wait for them to all complete
              while (pending > 0) Thread.Sleep(10);   // wait for all the writes to complete
              if (source != null)
              {                                       // close the files
            source.Close();
            source.Dispose();
              }

              ////////////////////////////////////////////////////////////////////////////
              /// report the time and speed.
              //elapsedTime = time.timerRead(out CPUtime, out CPUutilization);
              //float fileSizeMB = totalBytes >> 20;

              //Console.WriteLine("AsyncCopy of a {0:F0} MB file in: {1:F2} seconds @ {2:F2} MBps, \n\tCPU: {3:F2},\tUser: {4:F2},\tKernel {5:F2}."
              //                 , fileSizeMB, elapsedTime, fileSizeMB / elapsedTime, CPUtime, time.UserTime, time.KernelTime);
              ////////////////////////////////////////////////////////////////////////////
              /// cleanup
              return target;
        }
コード例 #41
0
ファイル: Session.cs プロジェクト: OPCFoundation/UA-.NET
        /// <summary>
        /// Sends an additional publish request.
        /// </summary>
        public IAsyncResult BeginPublish(int timeout)
        { 
            // do not publish if reconnecting.
            if (m_reconnecting)
            {
                Utils.Trace("Published skipped due to reconnect");
                return null;
            }

            SubscriptionAcknowledgementCollection acknowledgementsToSend = null;

            // collect the current set if acknowledgements.
            lock (SyncRoot)
            {
                acknowledgementsToSend = m_acknowledgementsToSend;
                m_acknowledgementsToSend = new SubscriptionAcknowledgementCollection();
                foreach (var toSend in acknowledgementsToSend)
                {
                    if (m_latestAcknowledgementsSent.ContainsKey(toSend.SubscriptionId))
                    {
                        m_latestAcknowledgementsSent[toSend.SubscriptionId] = toSend.SequenceNumber;
                    }
                    else
                    {
                        m_latestAcknowledgementsSent.Add(toSend.SubscriptionId, toSend.SequenceNumber);
                    }
                }
            }

            // send publish request.
            RequestHeader requestHeader = new RequestHeader();

            // ensure the publish request is discarded before the timeout occurs to ensure the channel is dropped.
            requestHeader.TimeoutHint       = (uint)OperationTimeout/2;
            requestHeader.ReturnDiagnostics = (uint)(int)ReturnDiagnostics;
            requestHeader.RequestHandle     = Utils.IncrementIdentifier(ref m_publishCounter);
            
            AsyncRequestState state = new AsyncRequestState();

            state.RequestTypeId = DataTypes.PublishRequest;
            state.RequestId = requestHeader.RequestHandle;
            state.Timestamp = DateTime.UtcNow;

            try
            {                
                IAsyncResult result = BeginPublish(
                    requestHeader, 
                    acknowledgementsToSend, 
                    OnPublishComplete, 
                    new object[] { SessionId, acknowledgementsToSend, requestHeader });
                    
                AsyncRequestStarted(result, requestHeader.RequestHandle, DataTypes.PublishRequest);

                // Utils.Trace("PUBLISH #{0} SENT", requestHeader.RequestHandle);

                return result;
            }
            catch (Exception e)
            {   
                Utils.Trace(e, "Unexpected error sending publish request.");
                return null;
            }
        }
コード例 #42
0
    /// <summary>
    /// Sends an event notification to our subscriber for the specified <paramref name="variables"/>.
    /// </summary>
    protected void SendEventNotification(IEnumerable<DvStateVariable> variables)
    {
      AsyncRequestState state;
      lock (_serverData.SyncObj)
      {
        foreach (DvStateVariable variable in variables)
          _eventingState.UpdateModerationData(variable);
        String body;
        lock (_serverData.SyncObj)
          body = GENAMessageBuilder.BuildEventNotificationMessage(variables, !_subscriberSupportsUPnP11);
        byte[] bodyData = UPnPConsts.UTF8_NO_BOM.GetBytes(body);

        state = new AsyncRequestState(_config, _sid, _callbackURLs, _eventingState.EventKey, bodyData);
        _pendingRequests.Add(state);
        _eventingState.IncEventKey();
      }
      // Outside the lock
      ContinueEventNotification(state);
    }
コード例 #43
0
    /// <summary>
    /// Tries to send the event message specified by the given <paramref name="state"/> object to the next
    /// available event callback URL, if present.
    /// </summary>
    private void ContinueEventNotification(AsyncRequestState state)
    {
      IEnumerator<string> e = state.PendingCallbackURLs.GetEnumerator();
      if (!e.MoveNext())
      {
        lock (_serverData.SyncObj)
          _pendingRequests.Remove(state);
        return;
      }
      string callbackURL = e.Current;
      state.PendingCallbackURLs.Remove(callbackURL);

      HttpWebRequest request = (HttpWebRequest) WebRequest.Create(callbackURL);
      NetworkUtils.SetLocalEndpoint(request, _config.EndPointIPAddress);
      request.Method = "NOTIFY";
      request.KeepAlive = false;
      request.ContentType = "text/xml; charset=\"utf-8\"";
      request.Headers.Add("NT", "upnp:event");
      request.Headers.Add("NTS", "upnp:propchange");
      request.Headers.Add("SID", _sid);
      request.Headers.Add("SEQ", _eventingState.EventKey.ToString());
      state.Request = request;

      // First get the request stream...
      IAsyncResult result = state.Request.BeginGetRequestStream(OnEventGetRequestStream, state);
      NetworkHelper.AddTimeout(request, result, PENDING_EVENT_NOTIFICATION_TIMEOUT * 1000);
    }
コード例 #44
0
 public AsyncRequest(AsyncRequestState ars)
 {
     _asyncRequestState = ars;
 }
コード例 #45
0
ファイル: HTTP.cs プロジェクト: seamusic/TicketHelper
 private static void _BeginRequest(AsyncRequestState state)
 {
     bool isPost = "POST".Equals(state.UserRequest.Method, StringComparison.OrdinalIgnoreCase);
     if (isPost && !string.IsNullOrEmpty(state.UserRequest.Body))
     {
         state.RaiseItemChanged("BeginGetRequestStream");
         state.InnerRequest.ContentType = "application/x-www-form-urlencoded";
         state.InnerRequest.BeginGetRequestStream(_AsyncGetRequestStream, state);
     }
     else
     {
         if (isPost)
         {
             state.InnerRequest.ContentLength = 0;
         }
         state.RaiseItemChanged("BeginGetResponse");
         state.InnerRequest.BeginGetResponse(_AsyncGetResponse, state);
     }
 }
コード例 #46
0
ファイル: HTTP.cs プロジェクト: seamusic/TicketHelper
 public static void RemoveState(AsyncRequestState state)
 {
     if (ListenForm != null)
     {
         if (ListenForm.InvokeRequired)
         {
             ListenForm.Invoke(new Func<AsyncRequestState>(RemoveState), state);
         }
         else
         {
             BindingRequestStates.Remove(state);
         }
     }
     else
     {
         BindingRequestStates.Remove(state);
     }
     state.UserRequest.Reset();
 }
コード例 #47
0
ファイル: HTTP.cs プロジェクト: seamusic/TicketHelper
 public static void Request(HttpRequest req)
 {
     bool isPost = "POST".Equals(req.Method, StringComparison.OrdinalIgnoreCase);
     var request = CreateRequest(isPost, req.Url, RunTimeData.Cookies, req.Referer, req.Timeout, req.ReadWriteTimeout);
     var state = new AsyncRequestState(req, request);
     AddState(state);
     _BeginRequest(state);
 }