public virtual void Abort(IAsyncResult result) { Recorder.Trace(5L, TraceType.InfoTrace, "ExchangeProxy.Abort Result:", result); AsyncRequestResult asyncRequestResult = result as AsyncRequestResult; if (asyncRequestResult != null) { asyncRequestResult.WebRequest.Abort(); } }
public virtual IEnumerable <TOut> EndExecute <TIn, TOut>(IAsyncResult result) where TIn : SimpleServiceRequestBase where TOut : ServiceResponse { Recorder.Trace(5L, TraceType.InfoTrace, "ExchangeProxy.EndExecute Result:", result); TIn tin = AsyncRequestResult.ExtractServiceRequest <TIn>(this.ExchangeService, result); MultiResponseServiceRequest <TOut> multiResponseServiceRequest = tin as MultiResponseServiceRequest <TOut>; if (multiResponseServiceRequest != null) { return(multiResponseServiceRequest.EndExecute(result)); } return(new TOut[] { tin.EndInternalExecute(result) as TOut }); }
/// <summary> /// Extracts the original service request from the specified IAsyncResult instance /// </summary> /// <typeparam name="T">Desired service request type</typeparam> /// <param name="exchangeService">The ExchangeService object to validate the integrity of asyncResult</param> /// <param name="asyncResult">An IAsyncResult that references the asynchronous request.</param> /// <returns>The original service request</returns> static T ExtractServiceRequest <T>(ExchangeService exchangeService, IAsyncResult asyncResult) where T : SimpleServiceRequestBase { // Validate null first EwsUtilities.ValidateParam(asyncResult, "asyncResult"); AsyncRequestResult asyncRequestResult = asyncResult as AsyncRequestResult; if (asyncRequestResult == null) { // Strings.InvalidAsyncResult is copied from the error message of HttpWebRequest.EndGetResponse() // Just use this simple String for all kinds of invalid IAsyncResult parameters throw new ArgumentError(Strings.InvalidAsyncResult, "asyncResult"); } // Validate the service request if (asyncRequestResult.ServiceRequest == null) { throw new ArgumentError(Strings.InvalidAsyncResult, "asyncResult"); } //Validate the service object if (!Object.ReferenceEquals(asyncRequestResult.ServiceRequest.Service, exchangeService)) { throw new ArgumentError(Strings.InvalidAsyncResult, "asyncResult"); } // Validate the request type T serviceRequest = asyncRequestResult.ServiceRequest as T; if (serviceRequest == null) { throw new ArgumentError(Strings.InvalidAsyncResult, "asyncResult"); } return(serviceRequest); }
void SnmpAsyncResponseCallback(AsyncRequestResult result, SnmpPacket packet) { //If result is null then agent didn't reply or we couldn't parse the reply. if (result == AsyncRequestResult.NoError && packet != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (packet.Pdu.ErrorStatus != 0) { // agent reported an error with the request TipMessage = string.Format("SNMP应答数据包中有错误信息. Error {0} index {1}", packet.Pdu.ErrorStatus, packet.Pdu.ErrorIndex); errorStatus = false; NotifyPropertyChanged("TotalStatus"); } else { errorStatus = true; //ifAdminStatus//ifOperStatus//ifInOctets //ifOutOctets bool tempAdminStatus, tempOperStatus; if (packet.Pdu.VbList[0].Value as Integer32 == 1) { tempAdminStatus = true; } else { tempAdminStatus = false; } if (packet.Pdu.VbList[1].Value as Integer32 == 1) { tempOperStatus = true; } else { tempOperStatus = false; } if (tempAdminStatus != adminStatus || tempOperStatus != operStatus) { adminStatus = tempAdminStatus; operStatus = tempOperStatus; NotifyPropertyChanged("Status"); NotifyPropertyChanged("StatusDescr"); NotifyPropertyChanged("TotalStatus"); if (inSpeed != -1) { TipMessage = string.Format("AdminStatus:{0}\nOperStatus:{1}", adminStatus ? "up" : "down", operStatus ? "up" : "down"); } } if (inSpeed == -1) { //这次是第一次获取数据 oldInOctets = packet.Pdu.VbList[2].Value as Counter32; oldIOutOctets = packet.Pdu.VbList[3].Value as Counter32; oldTime = DateTime.Now; inSpeed = 0; outSpeed = 0; } else { newInOctets = packet.Pdu.VbList[2].Value as Counter32; newOutOctets = packet.Pdu.VbList[3].Value as Counter32; DateTime now = DateTime.Now; double interval = (now - oldTime).TotalSeconds; oldTime = now; inSpeed = Math.Round((newInOctets - oldInOctets) * 0.008 / interval, 2); //结果为 kb/s outSpeed = Math.Round((newOutOctets - oldIOutOctets) * 0.008 / interval, 2); SpeedRealTime = string.Format("In: {0}kb/s; Out: {1}kb/s", inSpeed, outSpeed); oldInOctets = newInOctets; oldIOutOctets = newOutOctets; uiDispatcher.Invoke(new Action(() => { DataPoint dpIn = new DataPoint(); dpIn.XValue = DateTime.Now; dpIn.YValue = inSpeed; DataPoint dpOut = new DataPoint(); dpOut.XValue = DateTime.Now; dpOut.YValue = outSpeed; if (InSpeedDataPointList.Count >= 30) { InSpeedDataPointList.RemoveAt(0); } InSpeedDataPointList.Add(dpIn); if (OutSpeedDataPointList.Count >= 30) { OutSpeedDataPointList.RemoveAt(0); } OutSpeedDataPointList.Add(dpOut); })); if (IsShowSpeedAlarm) { //SpeedAlarmStatus bool tempSpeedAlarmStatus = (inSpeed <= maxInSpeed) && (outSpeed <= maxOutSpeed); if (tempSpeedAlarmStatus != SpeedAlarmStatus) { SpeedAlarmStatus = tempSpeedAlarmStatus; TipMessage = string.Format("In:{0}kb/s{1};Out:{2}kb/s{3}", inSpeed, (inSpeed <= maxInSpeed) ? "正常" : "超限!", outSpeed, (outSpeed <= maxOutSpeed) ? "正常" : "超限!"); } } } } } else { TipMessage = "没有SNMP应答数据包"; } target.Close(); }
private void btnLoadClimbers_Click(object sender, EventArgs e) { try { this.ReloadClimbersList(); } catch (Exception ex) { MessageBox.Show(String.Format("Ошибка обновления: {0}", ex)); } return; if (client != null) { if (cbLoadInDiffThread.Checked) { lock (loaderLocker) { if (climbersLoadingResult != null) { if (MessageBox.Show(this, "Загрузка запущена. Прервать?", String.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { climbersLoadingResult.Abort(); } else { return; } } climbersLoadingResult = OnlineUpdater.BeginRefreshClimbers(true, cn, client, UpdateCompleted, null); } } else { try { OnlineUpdater.RefreshClimbers(true, cn, client, true); StaticClass.ShowExceptionMessageBox("Список участников успешно загружен", owner: this); } catch (WebException wex) { StaticClass.ShowExceptionMessageBox("Ошибка обновления сайта", wex, this); } catch (SqlException s) { StaticClass.ShowExceptionMessageBox("Ошибка работы с данными", s, this); } catch (Exception ex) { StaticClass.ShowExceptionMessageBox("Неизвестная ошибка", ex, this); } } return; } loadAgr la = new loadAgr(!cbLoadInDiffThread.Checked, cbLoadPhoto.Checked, cbLoadJudges.Checked, compForService, client, new MainForm.AfetrStopCallBack(parent.RemThrData), cn); if (la.useCurrent) { LoadClimbers(la); } else { if (parent.LoadingThread != null && parent.LoadingThread.IsAlive) { if (MessageBox.Show("Загрузка списка участников уже запущена. Прервать?", "Загрузка запущена", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { return; } } parent.LoadingThread = new Thread(LoadClimbers); MainForm.ThrData td = new MainForm.ThrData(parent.LoadingThread, MainForm.ThreadStats.IMG_SAV_REM); parent.AddThrData(td); parent.LoadingThread.Start(la); } }
internal void AsyncResponse(AsyncRequestResult result, IPEndPoint peer, byte[] buffer, int buflen) { if (result != AsyncRequestResult.NoError) { _response(result, null); } else { if (buffer == null || buffer.Length <= 0 || buflen <= 0) { _response(AsyncRequestResult.NoDataReceived, null); return; } // verify packet if (_agentParameters.Version == (int)SnmpVersion.Ver1) { SnmpV1Packet packet = new SnmpV1Packet(); try { packet.decode(buffer, buflen); } catch (Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); return; } else if (_agentParameters.Version == SnmpVersion.Ver2) { SnmpV2Packet packet = new SnmpV2Packet(); try { packet.decode(buffer, buflen); } catch (Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); // MutableByte b = new MutableByte(buffer, buflen); // Console.WriteLine("Buffer length {0}", buflen); // SnmpConstants.DumpHex(b); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); } else if (_agentParameters.Version == SnmpVersion.Ver3) { SnmpV3Packet packet = new SnmpV3Packet(); SecureAgentParameters secparams = (SecureAgentParameters)_agentParameters; secparams.InitializePacket(packet); try { if (secparams.HasCachedKeys) { packet.decode(buffer, buflen, secparams.AuthenticationKey, secparams.PrivacyKey); } else { packet.decode(buffer, buflen); } } catch { _response(AsyncRequestResult.DecodeError, packet); return; } if (!secparams.ValidateIncomingPacket(packet)) { _response(AsyncRequestResult.AuthenticationError, packet); } else { secparams.UpdateDiscoveryValues(packet); // update time, etc. values _response(AsyncRequestResult.NoError, packet); } } } }
/// <summary> /// Ends executing an asynchronous request. /// </summary> private void InternalEndExecuteRequest(IAsyncResult asyncResult) { AsyncExecutionState state = (AsyncExecutionState)asyncResult.AsyncState; AsyncRequestResult asyncRequestResult = null; bool retried = false; try { asyncRequestResult = new AsyncRequestResult(new Response( state.CurrentRequest.EndGetResponse(asyncResult))); } catch (WebException ex) { // Returns null if the attempt was retried. retried = HandleFailedRequest(state, ex, out asyncRequestResult); } catch (Exception ex) // Unknown exception. { asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, null, ex)); } finally { // If the async result is null, this indicates that the request was retried. // Another handler will be executed to respond to that attempt, so do not // call the handler yet. if (!retried) state.ResponseHandler(asyncRequestResult); } }
/// <summary> /// Handles a failed request, and tries to fix it if possible. /// </summary> /// <remarks> /// Can not throw an exception. /// </remarks> /// <returns> /// Returns true if the request was handled and is being retried. /// Returns false if the request could not be retried. /// </returns> private bool HandleFailedRequest(AsyncExecutionState state, WebException exception, out AsyncRequestResult asyncRequestResult) { try { RequestError error = null; // Try to get an error response object. if (exception.Response != null) { IResponse errorResponse = new Response(exception.Response); error = Service.DeserializeError(errorResponse); } // Try to handle the response somehow. if (SupportsRetry && state.Try < MaximumRetries) { // Wait some time before sending another request. Thread.Sleep((int)state.WaitTime); state.WaitTime *= RetryWaitTimeIncreaseFactor; state.Try++; foreach (IErrorResponseHandler handler in GetErrorResponseHandlers()) { if (handler.CanHandleErrorResponse(exception, error)) { state.CurrentRequest = CreateWebRequest(); // The provided handler was able to handle this error. Retry sending the request. handler.HandleErrorResponse(exception, error, state.CurrentRequest); logger.Warning("Retrying request [{0}]", this); InternalBeginExecuteRequest(state); // Signal that this begin/end request pair has no result because it has been retried. asyncRequestResult = null; return true; } } } // Retrieve additional information about the http response (if applicable). HttpStatusCode status = 0; HttpWebResponse httpResponse = exception.Response as HttpWebResponse; if (httpResponse != null) { status = httpResponse.StatusCode; } // We were unable to handle the exception. Throw it wrapped in a GoogleApiRequestException. asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, error, exception) { HttpStatusCode = status }); } catch (Exception ex) { asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, null, ex)); } return false; }
/// <summary> /// Handles a failed request, and tries to fix it if possible. /// </summary> /// <remarks> /// Can not throw an exception. /// </remarks> /// <returns> /// Returns true if the request was handled and is being retried. /// Returns false if the request could not be retried. /// </returns> private bool HandleFailedRequest(AsyncExecutionState state, WebException exception, out AsyncRequestResult asyncRequestResult) { try { RequestError error = null; // Try to get an error response object. if (exception.Response != null) { IResponse errorResponse = new Response(exception.Response); error = Service.DeserializeError(errorResponse); } // Try to handle the response somehow. if (SupportsRetry && state.Try < MaximumRetries) { // Wait some time before sending another request. Thread.Sleep((int)state.WaitTime); state.WaitTime *= RetryWaitTimeIncreaseFactor; state.Try++; foreach (IErrorResponseHandler handler in GetErrorResponseHandlers()) { if (handler.CanHandleErrorResponse(exception, error)) { // The provided handler was able to handle this error. Retry sending the request. handler.HandleErrorResponse(exception, error, state.CurrentRequest); logger.Warning("Retrying request [{0}]", this); // Begin a new request and when it is completed being assembled, execute it // asynchronously. state.CurrentRequest = CreateWebRequest((request) => { InternalBeginExecuteRequest(state); }); // Signal that this begin/end request pair has no result because it has been retried. asyncRequestResult = null; return(true); } } } // Retrieve additional information about the http response (if applicable). HttpStatusCode status = 0; HttpWebResponse httpResponse = exception.Response as HttpWebResponse; if (httpResponse != null) { status = httpResponse.StatusCode; } // We were unable to handle the exception. Throw it wrapped in a GoogleApiRequestException. asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, error, exception) { HttpStatusCode = status }); } catch (Exception) { asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, null, exception)); } return(false); }
internal void AsyncResponse(AsyncRequestResult result, IPEndPoint peer, byte[] buffer, int buflen) { if (result != AsyncRequestResult.NoError) { _response(result, null); } else { if (buffer == null || buffer.Length <= 0 || buflen <= 0) { _response(AsyncRequestResult.NoDataReceived, null); return; } // verify packet if (_agentParameters.Version == (int)SnmpVersion.Ver1) { SnmpV1Packet packet = new SnmpV1Packet(); try { packet.decode(buffer, buflen); } catch(Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); return; } else if (_agentParameters.Version == SnmpVersion.Ver2) { SnmpV2Packet packet = new SnmpV2Packet(); try { packet.decode(buffer, buflen); } catch (Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); // MutableByte b = new MutableByte(buffer, buflen); // Console.WriteLine("Buffer length {0}", buflen); // SnmpConstants.DumpHex(b); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); } else if (_agentParameters.Version == SnmpVersion.Ver3) { SnmpV3Packet packet = new SnmpV3Packet(); SecureAgentParameters secparams = (SecureAgentParameters)_agentParameters; secparams.InitializePacket(packet); try { if (secparams.HasCachedKeys) packet.decode(buffer, buflen, secparams.AuthenticationKey, secparams.PrivacyKey); else packet.decode(buffer, buflen); } catch { _response(AsyncRequestResult.DecodeError, packet); return; } if (!secparams.ValidateIncomingPacket(packet)) { _response(AsyncRequestResult.AuthenticationError, packet); } else { secparams.UpdateDiscoveryValues(packet); // update time, etc. values _response(AsyncRequestResult.NoError, packet); } } } }
/// <summary> /// Async callback method for HttpWebRequest async requests. /// </summary> /// <param name="webAsyncResult">An IAsyncResult that references the asynchronous request.</param> private static void WebRequestAsyncCallback(IAsyncResult webAsyncResult) { WebAsyncCallStateAnchor wrappedState = webAsyncResult.AsyncState as WebAsyncCallStateAnchor; if (wrappedState != null && wrappedState.AsyncCallback != null) { AsyncRequestResult asyncRequestResult = new AsyncRequestResult( wrappedState.ServiceRequest, wrappedState.WebRequest, webAsyncResult, /* web async result */ wrappedState.AsyncState /* user state */); // Call user's call back wrappedState.AsyncCallback(asyncRequestResult); } }
public NetworkRequest(Transaction transaction) { _asyncRequestResult = new AsyncRequestResult(this); _transactions.Insert(0, transaction); }