public void Send() { while (continueSending) { IList <PersistentMessage> messages = null; //normal conditions will be at 5, when there are several unreliable endpoints //it will grow up to 31 connections all attempting to connect, timeouts can take up to 30 seconds if ((currentlySendingCount - currentlyConnecting > 5) || currentlyConnecting > 30) { lock (@lock) Monitor.Wait(@lock, TimeSpan.FromSeconds(1)); continue; } Endpoint point = null; queueStorage.Send(actions => { messages = actions.GetMessagesToSendAndMarkThemAsInFlight(100, 1024 * 1024, out point); actions.Commit(); }); if (messages.Count == 0) { lock (@lock) Monitor.Wait(@lock, TimeSpan.FromSeconds(1)); continue; } Interlocked.Increment(ref currentlySendingCount); Interlocked.Increment(ref currentlyConnecting); new Sender { Connected = () => Interlocked.Decrement(ref currentlyConnecting), Destination = point, Messages = messages.ToArray(), Success = OnSuccess(messages), Failure = OnFailure(point, messages), FailureToConnect = e => { Interlocked.Decrement(ref currentlyConnecting); OnFailure(point, messages)(e); }, Revert = OnRevert(point), Commit = OnCommit(point, messages) }.Send(); } }
public void Login(LoginRequest loginRequest, OnLogin loginCallback, OnFailure failureCallback) { LoginResponseHandler loginResponseHandler = new LoginResponseHandler(); try { string sessionId; Response response = this._httpInvoker.Invoke(this._baseUri, (IRequest)loginRequest, this._xmlParser, (Handler)loginResponseHandler, out sessionId); if (response.IsOk) { if (loginResponseHandler.IsOk) { loginCallback((ISession) new Session(loginResponseHandler.AccountDetails, this._baseUri, this._httpInvoker, this._xmlParser, sessionId, true)); } else { failureCallback(new FailureResponse(false, loginResponseHandler.FailureType, loginResponseHandler.Message, (Exception)null)); } } else { failureCallback(new FailureResponse(true, "HttpStatus: " + (object)response.Status + ", for: " + this._baseUri + loginRequest.Uri)); } } catch (Exception ex) { failureCallback(new FailureResponse(ex, "URI: " + this._baseUri + loginRequest.Uri)); } }
private void OnStop(object sender, StoppedEventArgs args) { if (args.Exception != null) { // Notify program of stop caused by exception _renderFix?.Stop(); OnFailure?.Invoke(args.Exception); return; } if (_action == PauseAction.Clip) { // Write circular buffer to output stream using (_dest) { if (_fullBuffer) { _dest.Write(_buffer, _index, _buffer.Length - _index); } if (_index > 0) { _dest.Write(_buffer, 0, _index); } _dest.Flush(); } _dest = null; } _action = PauseAction.None; _task.SetResult(true); }
/// <summary> /// Login to the Lmax Trader platform. The appropriate handler will be called back /// on success or failure. The loginCallback should be the main entry point into /// your trading application. From that point you should add listeners to the /// session, subscribe to resources that you're interested in, e.g. OrderBooks /// and call Start on the <see cref="ISession"/>. /// </summary> /// <param name="loginRequest"> /// A <see cref="LoginRequest"/> that contains your login credentials. /// </param> /// <param name="loginCallback"> /// A <see cref="OnLogin"/> callback, fired when you are successfully logged in. /// </param> /// <param name="failureCallback"> /// A <see cref="OnFailure"/> callback, fired when there is a login failure. /// </param> public void Login(LoginRequest loginRequest, OnLogin loginCallback, OnFailure failureCallback) { LoginResponseHandler handler = new LoginResponseHandler(); try { string sessionId; Response response = _httpInvoker.Invoke(_baseUri, loginRequest, _xmlParser, handler, out sessionId); if (response.IsOk) { if (handler.IsOk) { loginCallback(new Session(handler.AccountDetails, _baseUri, _httpInvoker, _xmlParser, sessionId, true)); } else { failureCallback(new FailureResponse(false, handler.FailureType, handler.Message, null)); } } else { failureCallback(new FailureResponse(true, "HttpStatus: " + response.Status + ", for: " + _baseUri + loginRequest.Uri)); } } catch (Exception e) { failureCallback(new FailureResponse(e, "URI: " + _baseUri + loginRequest.Uri)); } }
/*Definition for Callback Methods*/ public async void Call <T>() { CheckExeptions(); HttpResponseDTO <object> responseDto = new HttpResponseDTO <object>(); string urlRequest = FullUrl ?? RequestUri; HttpResponseMessage response = null; try { response = GetHttpResponse(urlRequest); } catch (Exception e) { throw new Exception(e.Message, e); } string jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); responseDto.StatusCode = response.StatusCode; if (response.StatusCode == (HttpStatusCode)401) { responseDto.Message = "You are not authorized to request this resource"; OnFailure?.Invoke(responseDto); } else { T dynamicObj = JsonConvert.DeserializeObject <T>(jsonString); responseDto.Body = dynamicObj; OnResponse?.Invoke(responseDto); } }
private IEnumerator SendGet(string url, Dictionary <string, string> headers) { Debug.Log($"url for get-request: {url}"); using UnityWebRequest webRequest = UnityWebRequest.Get(url); Debug.Log($"Adding headers --------------------"); foreach (var header in headers) { Debug.Log($"Adding header {header.Key} {header.Value}"); webRequest.SetRequestHeader(header.Key, header.Value); } Debug.Log($"End of adding headers --------------------"); webRequest.disposeDownloadHandlerOnDispose = true; webRequest.disposeUploadHandlerOnDispose = true; yield return(webRequest.SendWebRequest()); if (!string.IsNullOrEmpty(webRequest.error)) { OnFailure?.Invoke(webRequest.error); yield break; } OnGetResponse(webRequest.downloadHandler.text); }
private void Fail(string message) { if (OnFailure != null) { OnFailure.Invoke(message); } }
/// <summary> /// Executes the transaction, and returns the result. /// </summary> /// <returns>A TaskResult that has the ResultType Success if all tasks executed successfully, /// or the TaskResult returned by a failed task, depending on ErrorHandlingMode.</returns> public override TaskResult Execute() { var lock_obj = Lock ?? new object(); lock (lock_obj) { foreach (var task in Tasks) { var result = task.Execute(); if (ErrorHandlingMode != TransactionErrorHandlingMode.Ignore && result.Type != ResultType.Success && !result.Type.HasFlag(ResultType.Ignorable)) { if (OnFailure != null) { OnFailure.Execute(); } // fatal failure return(result); } else if (result.Type == ResultType.StopExecution) { break; } } } return(new TaskResult(this, ResultType.Success)); }
private static void HandleSignInResult(GoogleSignInResult result) { if (result.IsSuccess) OnSuccess?.Invoke(result.Status); else if (!result.IsSuccess) OnFailure?.Invoke(result.Status); }
/// <summary> /// Caller proxy /// </summary> /// <typeparam name="T"></typeparam> /// <param name="returnType">Retrun type of target method</param> /// <param name="args"></param> /// <returns></returns> public async Task <T> Call <T>(T returnType, object[] args) { var httpClient = new HttpClient(); var requestBuilder = new RequestBuilder(HttpMethod, HeadersToParse, BaseUri, RelativeUrl, HasBody, IsFormEncoded, IsMultipart); ProcessParameters(requestBuilder, args); try { var result = await httpClient.SendRequestAsync(requestBuilder.GetRequest()); if (result.IsSuccessStatusCode) { OnSuccess?.Invoke(result); if (returnType != null) { var content = await result?.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(content)); } return(default(T)); } else { OnFailure?.Invoke(result); return(default(T)); } } catch { throw new AggregateException("Http Request returned with a exception, please check your network."); } }
public void Start() { if (urlsConfig == null) { OnFailure?.Invoke("urlsConfig is null"); mediator.Notify(this, "Error"); return; } if (urlsConfig.HasUrl) { OnSuccess?.Invoke(urlsConfig.url); mediator.Notify(this, "OnUrlLoaded"); } else if (urlsConfig.HasServer) { coroutine = GlobalFacade.MonoBehaviour.StartCoroutine(SendGet()); } else { OnFailure?.Invoke("urlsConfig either hasn`t nor url nor server"); mediator.Notify(this, "Error"); } }
public void SearchInstruments(SearchRequest searchRequest, OnSearchResponse searchCallback, OnFailure onFailure) { try { SearchResponseHandler handler = new SearchResponseHandler(); Response response = _httpInvoker.GetInSession(_baseUri, searchRequest, _xmlParser, handler, _sessionId); if (response.IsOk) { if (handler.IsOk) { searchCallback(handler.Instruments, handler.HasMoreResults); } else { onFailure(new FailureResponse(false, handler.Message, "", null)); } } else { onFailure(new FailureResponse(true, "HttpStatus: " + response.Status + ", for: " + _baseUri + searchRequest.Uri)); } } catch (Exception e) { onFailure(new FailureResponse(e, "URI: " + _baseUri + searchRequest.Uri)); } }
private TResult Invoke<TResult>(SyncCommand<TResult> command, OnFailure failureAction, InformativeCancellationToken ct) { var stopwatch = Stopwatch.StartNew(); var logName = $"Hudl.Mjolnir.Command.{command.Name}"; var status = CommandCompletionStatus.RanToCompletion; try { _log.Debug($"[{logName}] Invoke Command={command.Name} Breaker={command.BreakerKey} Bulkhead={command.BulkheadKey} Timeout={ct.DescriptionForLog}"); // If we've already timed out or been canceled, skip execution altogether. ct.Token.ThrowIfCancellationRequested(); return _bulkheadInvoker.ExecuteWithBulkhead(command, ct.Token); } catch (Exception e) { status = GetCompletionStatus(e, ct); AttachCommandExceptionData(command, e, status, ct); throw; } finally { stopwatch.Stop(); _metricEvents.CommandInvoked(command.Name, stopwatch.Elapsed.TotalMilliseconds, command.ExecutionTimeMillis, status.ToString(), failureAction.ToString().ToLowerInvariant()); } }
public TestCase(TestCase originalTestCase, TestSuite parent) : base(originalTestCase, parent) { _knownDefects = originalTestCase._knownDefects; _defects = TestUtils.SafeCopyString(originalTestCase._defects); _onTestStepFailure = originalTestCase._onTestStepFailure; _tags = TestUtils.SafeCopyString(originalTestCase._tags); }
private void Gateway_OnFailure(object sender, GatewayFailureData e) { isRunning = false; CleanUp(); OnFailure?.Invoke(this, new ShardFailureEventArgs(this, e.Message, e.Reason, e.Exception)); stoppedResetEvent.Set(); }
/// <summary> /// Determines what action will be taken if stack creation fails. /// </summary> /// <param name="onFailure">The action to take on create failure.</param> /// <returns>The builder</returns> /// <exception cref="ArgumentException">Cannot set OnFailure when DisableRollback is true</exception> public CloudFormationBuilder WithOnFailure(OnFailure onFailure) { if (this._disableRollback && onFailure != null) { throw new ArgumentException("Cannot set OnFailure when DisableRollback is true"); } this._onFailure = onFailure; return(this); }
private void Close(Exception ex) { // already in close state ? QueryInfo queryInfo; int wasClosed = Interlocked.Exchange(ref this._isClosed, 1); if (wasClosed == 1) { return; } running.Cancel(); // if we connect failed, _pendingQueries, _queryInfos will be null. _pendingQueries?.CompleteAdding(); // abort all pending queries if (_queryInfos != null) { var canceledException = new OperationCanceledException(); for (int i = 0; i < _queryInfos.Length; ++i) { queryInfo = _queryInfos[i]; if (null != queryInfo) { queryInfo.NotifyError(canceledException); _instrumentation.ClientTrace(queryInfo.Token, EventType.Cancellation); _queryInfos[i] = null; } } } // cleanup not sending queries. if (_pendingQueries != null) { var canceledException = new OperationCanceledException(); while (_pendingQueries.TryTake(out queryInfo)) { queryInfo.NotifyError(canceledException); _instrumentation.ClientTrace(queryInfo.Token, EventType.Cancellation); } } // we have now the guarantee this instance is destroyed once _tcpClient.SafeDispose(); if (null != ex) { _logger.Fatal("Failed with error : {0}", ex); OnFailure?.Invoke(this, new FailureEventArgs(ex)); } // release event to release observer OnFailure = null; }
public Boolean Connect(String host, String token, String displayName, String resourceId, IConnect _iIConnect) { _mIConnect = _iIConnect; _mOnSuccess = OnSuccessDelegate; _mOnFailure = OnFailureDelegate; _mOnDisconnected = OnDisconnectedDelegate; Boolean ret = VidyoGatewayConnectNative(objPtr, host, token, displayName, resourceId, _mOnSuccess, _mOnFailure, _mOnDisconnected); return(ret); }
public IMParticleTask <IdentityApiResult> AddFailureListener(OnFailure listener) { if (!_onFailureListeners.Contains(listener)) { if (_failure != null) { listener.Invoke(_failure); } _onFailureListeners.Add(listener); } return(this); }
public IMParticleTask <IdentityApiResult> AddFailureListener(OnFailure listener) { if (Failure != null) { listener.Invoke(Failure); } else { _failureListeners.Add(listener); } return(this); }
/// <summary> /// Checks value in Predicate and invokes OnFailure if needed. /// </summary> /// <exception cref="InvalidOperationException" /> public void Check() { if (Predicate == null || OnFailure == null) { throw new InvalidOperationException("Check that properties are valid values."); } if (!Predicate.Invoke()) { OnFailure.Invoke(Parameters); } }
public void onImageResults(Dictionary <int, Face> faces, Frame frame) { if (faces.Count == 0) { OnFailure?.Invoke(this, new DetectAdapterEventAgrs(new Exception("啊,找不到脸!"))); } else { OnSuccess?.Invoke(this, new DetectAdapterEventAgrs(new AffdexFace(faces.First().Value))); } frame.Dispose(); }
public void OpenUri(Uri uri, OnUriResponse uriCallback, OnFailure onFailure) { try { IConnection connection = _httpInvoker.Connect(uri, _sessionId); uriCallback(uri, connection.GetBinaryReader()); } catch (UnexpectedHttpStatusCodeException e) { onFailure(new FailureResponse(true, "HttpStatus: " + e.StatusCode + ", for: " + uri.AbsoluteUri)); } }
public void Process(System.Drawing.Bitmap image) { try { Logger.WriteLog($"MSCS process"); using (MemoryStream ms0 = new MemoryStream(), ms1 = new MemoryStream()) { image.Save(ms0, ImageFormat.Jpeg); image.Save(ms1, ImageFormat.Jpeg); ms0.Position = 0; ms1.Position = 0; FaceAttributeType[] fat = { FaceAttributeType.Age, FaceAttributeType.Gender }; Face[] faces = AsyncHelper.RunSync(() => msfclient.DetectAsync(ms0, false, false, fat)); if (faces.Length == 0) { OnFailure?.Invoke(this, new DetectAdapterEventAgrs(new Exception("M$都找不到脸啊QAQ"))); return; } Face mxFace = faces[0]; for (int i = 1; i < faces.Length; i++) { if (faces[i].FaceRectangle.Width * faces[i].FaceRectangle.Height > mxFace.FaceRectangle.Width * mxFace.FaceRectangle.Height) { mxFace = faces[i]; } } Rectangle[] rect = new Rectangle[] { new Rectangle() { Left = mxFace.FaceRectangle.Left, Top = mxFace.FaceRectangle.Top, Width = mxFace.FaceRectangle.Width, Height = mxFace.FaceRectangle.Height } }; Emotion[] emotions = AsyncHelper.RunSync(() => mseclient.RecognizeAsync(ms1, rect)); if (emotions.Length == 0) { OnFailure?.Invoke(this, new DetectAdapterEventAgrs(new Exception("M$看不清脸啊QAQ"))); return; } OnSuccess?.Invoke(this, new DetectAdapterEventAgrs(new MSFace(mxFace, emotions[0]))); } } catch (Exception ex) { OnFailure?.Invoke(this, new DetectAdapterEventAgrs(ex)); } }
public void Execute <T>(Action <IFrameWriter> writer, Func <IFrameReader, IEnumerable <T> > reader, InstrumentationToken token, IObserver <T> observer) { if (_isClosed == 1) { var ex = new OperationCanceledException(); OnFailure?.Invoke(this, new FailureEventArgs(ex)); throw ex; } QueryInfo queryInfo = new QueryInfo <T>(writer, reader, token, observer); _pendingQueries.Add(queryInfo); }
public void Process(Bitmap image) { try { Frame frame = image.ConvertToFrame(); frame.setTimestamp(0); detector.process(frame); } catch (AffdexException ae) { OnFailure?.Invoke(this, new DetectAdapterEventAgrs(ae)); } }
public void Process(Bitmap image) { try { detector.start(); detector.process(image.ConvertToFrame()); } catch (AffdexException ae) { detector.stop(); OnFailure?.Invoke(this, new DetectAdapterEventAgrs(ae)); } }
public override void ProcessCondition(bool result, Condition condition) { base.ProcessCondition(result, condition); if (result) { OnSuccess?.Invoke(); } if (falseCount >= conditionsCount) { OnFailure?.Invoke(); } }
private void OnCollisionEnter(Collision collision) { Falling = false; if (collision.gameObject.GetComponentInChildren <DropCube>() != null && GameManager.Instance.gameVariables.CompletedBlockCount > 0 && collision.transform.position.y < 5.0f) { OnFailure?.Invoke(this, null); } else if (collision.gameObject.GetComponentInChildren <DropCube>() == null) //This is game over { OnFailure?.Invoke(this, null); } }
private void Socket_OnFatalDisconnection(object sender, GatewayCloseCode e) { if (isDisposed) { return; } log.LogVerbose("Fatal disconnection occured, setting state to Disconnected."); state = GatewayState.Disconnected; (string message, ShardFailureReason reason) = GatewayCloseCodeToReason(e); gatewayFailureData = new GatewayFailureData(message, reason, null); handshakeCompleteEvent.Set(); OnFailure?.Invoke(this, gatewayFailureData); }
public void CancelOrder(CancelOrderRequest cancelOrderRequest, OnInstructionResponse instructionCallback, OnFailure failureCallback) { OrderResponseHandler handler = new OrderResponseHandler(); SendRequest(cancelOrderRequest, handler, delegate() { instructionCallback(handler.InstructionId); }, failureCallback); }
private void SendRequest(IRequest request, Handler handler, OnSucessfulRequest onSucessfulRequest, OnFailure failureCallback) { try { Response response = _httpInvoker.PostInSession(_baseUri, request, _xmlParser, handler, _sessionId); if (response.IsOk) { if (handler.IsOk) { onSucessfulRequest(); } else { failureCallback(new FailureResponse(false, handler.Message, handler.Content, null)); } } else { failureCallback(new FailureResponse(true, "HttpStatus: " + response.Status + ", for: " + _baseUri + request.Uri)); } } catch (Exception e) { failureCallback(new FailureResponse(e, "URI: " + _baseUri + request.Uri)); } }
public void RequestAccountState(AccountStateRequest accountStateRequest, OnSuccess successCallback, OnFailure failureCallback) { DefaultHandler handler = new DefaultHandler(); SendRequest(accountStateRequest, handler, delegate() { successCallback(); }, failureCallback); }
public void AmendStops(AmendStopLossProfitRequest amendStopLossProfitRequest, OnInstructionResponse instructionCallback, OnFailure failureCallback) { OrderResponseHandler handler = new OrderResponseHandler(); SendRequest(amendStopLossProfitRequest, handler, delegate() { instructionCallback(handler.InstructionId); }, failureCallback); }
public void RequestHeartbeat(HeartbeatRequest heartbeatRequest, OnSuccess successCallback, OnFailure failureCallback) { DefaultHandler handler = new DefaultHandler(); SendRequest(heartbeatRequest, handler, delegate() { successCallback(); }, failureCallback); }
public void RequestHistoricMarketData(IHistoricMarketDataRequest historicMarketDataRequest, OnSuccess successCallback, OnFailure failureCallback) { DefaultHandler handler = new DefaultHandler(); SendRequest(historicMarketDataRequest, handler, delegate() { successCallback(); }, failureCallback); }
/// <summary> /// What action this step should take if the modification fails. This can happen when /// you request to perform an invalid action, such as shrink a core instance group. /// </summary> /// <param name="onFailure">OnFailure enum specifying which action to take.</param> /// <returns>A reference to this updated object so that method calls can be chained /// together.</returns> public ResizeJobFlowStep WithOnFailure(OnFailure onFailure) { this.onFailure = onFailure; return this; }
public void PlaceLimitOrder(LimitOrderSpecification limitOrderSpecification, OnInstructionResponse instructionCallback, OnFailure failureCallback) { OrderResponseHandler handler = new OrderResponseHandler(); SendRequest(limitOrderSpecification, handler, delegate() { instructionCallback(handler.InstructionId); }, failureCallback); }
/// <summary> /// logout from the exchange. /// You should stop listening to events first. /// /// <param name="successCallback">Will be called when the logout request suceeds.</param> /// <param name="onFailure">Will be called when the logout request fails.</param> /// </summary> public void Logout(OnSuccess successCallback, OnFailure onFailure) { SendRequest(new LogoutRequest(), new DefaultHandler(), delegate() { successCallback(); }, onFailure); }
public void Subscribe(ISubscriptionRequest subscriptionRequest, OnSuccess successCallback, OnFailure failureCallback) { DefaultHandler handler = new DefaultHandler(); SendRequest(subscriptionRequest, handler, delegate() { successCallback(); }, failureCallback); }