void onFailure(AndroidJavaObject response)
 {
     if (response == null)
     {
         listener.Invoke(null);
     }
     else
     {
         var errors = new List <Error>();
         foreach (AndroidJavaObject errorObject in response.Call <AndroidJavaObject>("getErrors").Call <AndroidJavaObject[]>("toArray"))
         {
             if (errorObject != null)
             {
                 errors.Add(new Error()
                 {
                     Code    = errorObject.Get <string>("code"),
                     Message = errorObject.Get <string>("message")
                 });
             }
         }
         listener.Invoke(new IdentityHttpResponse()
         {
             HttpCode     = response.Call <int>("getHttpCode"),
             IsSuccessful = response.Call <bool>("isSuccessful"),
             Errors       = errors
         });
     }
 }
Пример #2
0
		private static void HandleSignInResult(GoogleSignInResult result)
		{
            if (result.IsSuccess)
                OnSuccess?.Invoke(result.Status);
            else if (!result.IsSuccess)
                OnFailure?.Invoke(result.Status);
		}
Пример #3
0
        /// <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.");
            }
        }
Пример #4
0
        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");
            }
        }
Пример #5
0
 private void Fail(string message)
 {
     if (OnFailure != null)
     {
         OnFailure.Invoke(message);
     }
 }
Пример #6
0
        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);
        }
Пример #7
0
 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);
 }
Пример #8
0
        /*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);
            }
        }
Пример #9
0
        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();
        }
        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 IMParticleTask <IdentityApiResult> AddFailureListener(OnFailure listener)
 {
     if (Failure != null)
     {
         listener.Invoke(Failure);
     }
     else
     {
         _failureListeners.Add(listener);
     }
     return(this);
 }
 public IMParticleTask <IdentityApiResult> AddFailureListener(OnFailure listener)
 {
     if (!_onFailureListeners.Contains(listener))
     {
         if (_failure != null)
         {
             listener.Invoke(_failure);
         }
         _onFailureListeners.Add(listener);
     }
     return(this);
 }
Пример #13
0
        /// <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);
            }
        }
Пример #14
0
 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();
 }
Пример #15
0
        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));
            }
        }
Пример #16
0
 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));
     }
 }
Пример #17
0
 public void Process(Bitmap image)
 {
     try
     {
         detector.start();
         detector.process(image.ConvertToFrame());
     }
     catch (AffdexException ae)
     {
         detector.stop();
         OnFailure?.Invoke(this, new DetectAdapterEventAgrs(ae));
     }
 }
        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);
        }
Пример #19
0
    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);
        }
    }
Пример #20
0
        public override void ProcessCondition(bool result, Condition condition)
        {
            base.ProcessCondition(result, condition);

            if (result)
            {
                OnSuccess?.Invoke();
            }

            if (falseCount >= conditionsCount)
            {
                OnFailure?.Invoke();
            }
        }
Пример #21
0
        private void OnGetResponse(string response)
        {
            Debug.Log($"UnityUrlLoader OnGetResponse {response}");

            UrlResponseReader reader = new UrlResponseReader();
            string            url    = reader.GetUrl(response);

            if (string.IsNullOrEmpty(url))
            {
                OnFailure?.Invoke("Can`t read response from UrlLoader");
            }
            else
            {
                OnSuccess?.Invoke(url);
            }
        }
Пример #22
0
 public void Intercept(IInvocation invocation)
 {
     try
     {
         invocation.Proceed();
         OnSuccess?.Invoke(invocation);
     }
     catch (Exception ex)
     {
         OnFailure?.Invoke(invocation, ex);
         if (_throwException)
         {
             throw;
         }
     }
 }
 public void OnFailure(IdentityBinding.IdentityHttpResponse result)
 {
     if (_listener != null)
     {
         _listener.Invoke(new IdentityHttpResponse()
         {
             Errors = result.Errors.Select(arg => new Error()
             {
                 Message = arg.Message,
                 Code    = arg.Code
             }).ToList(),
             IsSuccessful = result.IsSuccessful,
             HttpCode     = result.HttpCode,
         });
     }
 }
Пример #24
0
        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);
        }
Пример #25
0
        /// <summary>
        /// Send a message to the signaling server to be dispatched to the remote
        /// endpoint specified by <see cref="SignalerMessage.TargetId"/>.
        /// </summary>
        /// <param name="message">Message to send</param>
        public Task SendMessageAsync(Message message)
        {
            if (string.IsNullOrWhiteSpace(_httpServerAddress))
            {
                throw new ArgumentException("Invalid empty HTTP server address.");
            }

            // Send a POST request to the server with the JSON-serialized message.
            var         jsonMsg    = JsonConvert.SerializeObject(message);
            string      requestUri = $"{_httpServerAddress}data/{RemotePeerId}";
            HttpContent content    = new StringContent(jsonMsg);
            var         task       = _httpClient.PostAsync(requestUri, content).ContinueWith((postTask) =>
            {
                if (postTask.Exception != null)
                {
                    OnFailure?.Invoke(postTask.Exception);
                    OnDisconnect?.Invoke();
                }
            });

            // Atomic read
            if (Interlocked.CompareExchange(ref _connectedEventFired, 1, 1) == 1)
            {
                return(task);
            }

            // On first successful message, fire the OnConnect event
            return(task.ContinueWith((prevTask) =>
            {
                if (prevTask.Exception != null)
                {
                    OnFailure?.Invoke(prevTask.Exception);
                }

                if (prevTask.IsCompletedSuccessfully)
                {
                    // Only invoke if this task was the first one to change the value, because
                    // another task may have completed faster in the meantime and already invoked.
                    if (0 == Interlocked.Exchange(ref _connectedEventFired, 1))
                    {
                        OnConnect?.Invoke();
                    }
                }
            }));
        }
Пример #26
0
        private void ReportFailure()
        {
            lock (_syncRoot)
            {
                if (_isDisposed)
                {
                    return;
                }

                if (!_isStarted)
                {
                    return;
                }
            }

            _failureDetected = true;
            OnFailure?.Invoke(_connectionId);
        }
Пример #27
0
        public void Process(System.Drawing.Bitmap image, Action <double> report)
        {
            try
            {
                report?.Invoke(0);
                using (MemoryStream ms0 = new MemoryStream(), ms1 = new MemoryStream())
                {
                    image.Save(ms0, ImageFormat.Jpeg);
                    image.Save(ms1, ImageFormat.Jpeg);
                    ms0.Position = 0;
                    ms1.Position = 0;

                    Face      mxFace;
                    Rectangle location;
                    if (!GetMaxFace(ms0, out mxFace, out location))
                    {
                        report?.Invoke(1);
                        OnFailure?.Invoke(this, new DetectAdapterEventAgrs(new Exception("M$都找不到脸啊QAQ")));
                        return;
                    }
                    else
                    {
                        report?.Invoke(0.5);
                    }

                    var emotions = AsyncHelper.RunSync(() => mseclient.RecognizeAsync(ms1, new Rectangle[] { location }));
                    report?.Invoke(1);
                    if (emotions.Length == 0)
                    {
                        OnFailure?.Invoke(this, new DetectAdapterEventAgrs(new Exception("M$看不清脸啊QAQ")));
                        return;
                    }
                    else
                    {
                        OnSuccess?.Invoke(this, new DetectAdapterEventAgrs(new MSFace(mxFace, emotions[0])));
                    }
                }
            }
            catch (Exception ex)
            {
                report?.Invoke(1);
                OnFailure?.Invoke(this, new DetectAdapterEventAgrs(ex));
            }
        }
Пример #28
0
        public void OnGetResponse(string response)
        {
            UrlResponseReader reader = new UrlResponseReader();
            string            url    = reader.GetUrl(response);

            if (string.IsNullOrEmpty(url))
            {
                OnFailure?.Invoke("Can`t read response from UrlLoader");
                mediator.Notify(this, "Error");
            }
            else
            {
                urlsConfig.url = url;
                OnSuccess?.Invoke(url);
                mediator.Notify(this, "OnUrlLoaded");
            }

            RemoveListeners();
        }
Пример #29
0
        private IEnumerator SendGet()
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(urlsConfig.server))
            {
                webRequest.timeout = 12;
                webRequest.disposeDownloadHandlerOnDispose = true;
                webRequest.disposeUploadHandlerOnDispose   = true;

                yield return(webRequest.SendWebRequest());

                if (!string.IsNullOrEmpty(webRequest.error))
                {
                    OnFailure?.Invoke(webRequest.error);
                    mediator.Notify(this, "Error");

                    yield break;
                }

                OnGetResponse(webRequest.downloadHandler.text);
            }
        }
Пример #30
0
        public virtual TElement Parse(TNode node)
        {
            TElement e = new TElement();

            try
            {
                e = ParseFunc(node);

                OnSuccess?.Invoke(this, new ParserEventArgs <TNode>(node, (e.InternalName, e.Value.ToString())));
            }
            catch (Exception ex)
            {
                OnFailure?.Invoke(this, new ParserEventArgs <TNode>(node, (e.InternalName, e.Value.ToString()), ex));
            }
            finally
            {
                // Either this Parser succeeded or not, it was already invoked
                parsedAlready = true;
            }

            return(e);
        }