Example #1
0
        public void exception_in_done_callback_is_propagated_via_event()
        {
            var promise     = new Promise();
            var ex          = new Exception();
            var eventRaised = 0;

            EventHandler <ExceptionEventArgs> handler = (s, e) =>
            {
                Assert.Equal(ex, e.Exception);

                ++eventRaised;
            };

            Promise.UnhandledException += handler;

            try
            {
                promise
                .Done(() =>
                {
                    throw ex;
                });

                promise.Resolve();

                Assert.Equal(1, eventRaised);
            }
            finally
            {
                Promise.UnhandledException -= handler;
            }
        }
Example #2
0
        public void can_handle_Done_onResolved_with_onReject()
        {
            var promise       = new Promise <int>();
            var callback      = 0;
            var errorCallback = 0;
            var expectedValue = 5;

            promise.Done(
                value =>
            {
                Assert.Equal(expectedValue, value);

                ++callback;
            },
                ex =>
            {
                ++errorCallback;
            }
                );

            promise.Resolve(expectedValue);

            Assert.Equal(1, callback);
            Assert.Equal(0, errorCallback);
        }
Example #3
0
    public void ShouldAddFriend(Cloud cloud)
    {
        // Use two test accounts
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects friend status change event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Community.OnFriendStatusChange += (FriendStatusChangeEvent e) => {
                Assert(e.FriendId == gamer2.GamerId, "Should come from P2");
                Assert(e.NewStatus == FriendRelationshipStatus.Add, "Should have added me");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // Add gamer1 as a friend of gamer2
            gamer2.Community.AddFriend(gamer1.GamerId)
            .ExpectSuccess(addResult => {
                // Then list the friends of gamer1, gamer2 should be in it
                return gamer1.Community.ListFriends();
            })
            .ExpectSuccess(friends => {
                Assert(friends.Count == 1, "Expects one friend");
                Assert(friends[0].GamerId == gamer2.GamerId, "Wrong friend ID");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
        public void CanHandleDoneOnResolvedWithOnReject()
        {
            var       promise       = new Promise <int>();
            var       callback      = 0;
            var       errorCallback = 0;
            const int expectedValue = 5;

            promise.Done(
                value =>
            {
                Assert.AreEqual(expectedValue, value);

                ++callback;
            },
                ex =>
            {
                ++errorCallback;
            }
                );

            promise.Resolve(expectedValue);

            Assert.AreEqual(1, callback);
            Assert.AreEqual(0, errorCallback);
        }
 public AsyncStreamWriter(Stream stream, Action onComplete, Action<Exception> onError)
 {
   _stream = stream;
   _promise = new Promise<bool>();
   if (onComplete != null) _promise.Done(r => onComplete());
   if (onError != null) _promise.Fail(onError);
 }
        private async void InstallRevit2018(object sender, RoutedEventArgs e)
        {
            if (!AppFor2018CanInstall)
            {
                return;
            }

            ShowAppFor2018InstallationInProcess();

            //var success = await Manager.HandleRevit2018ApplicationInstallation();

            var promise = new Promise(
                async(resolve, reject) =>
            {
                var success = await Manager.HandleRevit2018ApplicationInstallation();

                if (success)
                {
                    resolve();
                }
                else
                {
                    reject(null);
                }
            }
                );

            promise.Done(
                ShowAppFor2018InstallationComplete,
                (err) => ShowAppFor2018InstallationFailed()
                );
        }
Example #7
0
    public void ShouldAssociateGodfather(Cloud cloud)
    {
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects godchild event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Godfather.OnGotGodchild += (GotGodchildEvent e) => {
                Assert(e.Gamer.GamerId == gamer2.GamerId, "Should come from player2");
                Assert((object)e.Reward == (object)Bundle.Empty, "No reward should be associated");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // P1 generates a code and associates P2 with it
            gamer1.Godfather.GenerateCode()
            // Use code
            .ExpectSuccess(genCode => gamer2.Godfather.UseCode(genCode))
            .ExpectSuccess(dummy => gamer2.Godfather.GetGodfather())
            .ExpectSuccess(result => {
                Assert(result.GamerId == gamer1.GamerId, "P1 should be godfather");
                Assert(result.AsBundle().Root.Has("godfather"), "Underlying structure should be accessible");
                return gamer1.Godfather.GetGodchildren();
            })
            .ExpectSuccess(result => {
                Assert(result.Count == 1, "Should have only one godchildren");
                Assert(result[0].GamerId == gamer2.GamerId, "P2 should be godchildren");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
Example #8
0
        public void exception_during_Done_onResolved_triggers_error_hander()
        {
            var promise           = new Promise <int>();
            var callback          = 0;
            var errorCallback     = 0;
            var expectedValue     = 5;
            var expectedException = new Exception();

            promise.Done(
                value =>
            {
                Assert.Equal(expectedValue, value);

                ++callback;

                throw expectedException;
            },
                ex =>
            {
                Assert.Equal(expectedException, ex);

                ++errorCallback;
            }
                );

            promise.Resolve(expectedValue);

            Assert.Equal(1, callback);
            Assert.Equal(1, errorCallback);
        }
        public IPromise CreatePool <T>(TKey key) where T : TContract
        {
            Promise promise = new Promise();

            if (!_inactiveItems.ContainsKey(key))
            {
                Stack <TContract> newStack   = new Stack <TContract>(_settings.InitialSize);
                Promise <T>       tmpPromise = null;

                if (!_container.IsValidating)
                {
                    _activeCount.Add(key, 0);
                    _inactiveItems.Add(key, newStack);

                    for (int i = 0; i < _settings.InitialSize; i++)
                    {
                        if (tmpPromise == null)
                        {
                            tmpPromise = (Promise <T>)AllocNew <T>(key)
                                         .Then(item =>
                            {
                                _inactiveItems[key].Push(item);
                                //_pushedToPoolTimestamps[key].Add(DateTime.Now);
                            });
                        }
                        else
                        {
                            tmpPromise = (Promise <T>)tmpPromise.Then((o) =>
                            {
                                AllocNew <T>(key)
                                .Then(item =>
                                {
                                    _inactiveItems[key].Push(item);
                                    //_pushedToPoolTimestamps[key].Add(DateTime.Now);
                                });
                            });
                        }
                    }
                }

                if (tmpPromise != null)
                {
                    tmpPromise.Done(o =>
                    {
                        promise.Resolve();
                    }, promise.Reject);
                }
                else
                {
                    promise.Resolve();
                }
            }
            else
            {
                promise.Resolve();
            }

            return(promise);
        }
Example #10
0
 public static Promise <T> Dump <T>(this Promise <T> promise, string name) where T : class
 {
     promise
     .Done(i => Debug.Log(string.Format("{0}-->{1}", name, i)))
     .Fail(ex => Debug.Log(string.Format("{0} failed-->{1}", name, ex)))
     .Disposed(() => Debug.Log(string.Format("{0} disposed", name)));
     return(promise);
 }
 public void Setup()
 {
     // Setup the promise.
     promise     = new Promise <string>();
     returnValue = MSG_EMPTY;
     promise.Done(result => {
         returnValue = result;
     }, HandlePromiseException);
 }
        public void CanHandleDoneOnResolved()
        {
            var promise  = new Promise();
            var callback = 0;

            promise.Done(() => ++ callback);

            promise.Resolve();

            Assert.AreEqual(1, callback);
        }
        public void can_handle_Done_onResolved()
        {
            var promise = new Promise();
            var callback = 0;

            promise.Done(() => ++callback);

            promise.Resolve();

            Assert.Equal(1, callback);
        }
Example #14
0
        public void can_handle_Done_onResolved()
        {
            var promise  = new Promise();
            var callback = 0;

            promise.Done(() => ++ callback);

            promise.Resolve();

            Assert.Equal(1, callback);
        }
        public void can_handle_Done_onResolved_with_onReject()
        {
            var promise = new Promise();
            var callback = 0;
            var errorCallback = 0;

            promise.Done(
                () => ++callback,
                ex => ++errorCallback
            );

            promise.Resolve();

            Assert.Equal(1, callback);
            Assert.Equal(0, errorCallback);
        }
Example #16
0
        public void can_handle_Done_onResolved_with_onReject()
        {
            var promise       = new Promise();
            var callback      = 0;
            var errorCallback = 0;

            promise.Done(
                () => ++ callback,
                ex => ++ errorCallback
                );

            promise.Resolve();

            Assert.Equal(1, callback);
            Assert.Equal(0, errorCallback);
        }
        public void CanHandleDoneOnResolvedWithOnReject()
        {
            var promise       = new Promise();
            var callback      = 0;
            var errorCallback = 0;

            promise.Done(
                () => ++ callback,
                ex => ++ errorCallback
                );

            promise.Resolve();

            Assert.AreEqual(1, callback);
            Assert.AreEqual(0, errorCallback);
        }
Example #18
0
        public void can_handle_Done_onResolved()
        {
            var promise = new Promise<int>();
            var callback = 0;
            var expectedValue = 5;

            promise.Done(value =>
            {
                Assert.Equal(expectedValue, value);

                ++callback;
            });

            promise.Resolve(expectedValue);

            Assert.Equal(1, callback);
        }
Example #19
0
        public void can_handle_Done_onResolved()
        {
            var       promise       = new Promise <int>();
            var       callback      = 0;
            const int expectedValue = 5;

            promise.Done(value =>
            {
                Assert.Equal(expectedValue, value);

                ++callback;
            });

            promise.Resolve(expectedValue);

            Assert.Equal(1, callback);
        }
Example #20
0
 void ObservePromise(Promise <T> promise)
 {
     promise.Done(deferred.Resolve);
     promise.Fail(t => {
         nonResolvedCount++;
         if (nonResolvedCount == size)
         {
             deferred.Dispose();
         }
     });
     promise.Disposed(() => {
         nonResolvedCount++;
         if (nonResolvedCount == size)
         {
             deferred.Dispose();
         }
     });
 }
        public IPromise <FirebaseNetwork> SignInAnonymouslyIfNot()
        {
            var current = state.Current;

            if (!string.IsNullOrEmpty(current.uid))
            {
                return(Promise <FirebaseNetwork> .Resolved(this));
            }
            signInPromise?.Done();
            signInPromise = new Promise <FirebaseNetwork>();
            if (stubMessage.Current)
            {
                GameObject.Find(listenerObjectName).SendMessage("OnSignedIn", state.editor.uid);
            }
            else
            {
                SignInAnonymously(listenerObjectName);
            }
            return(signInPromise);
        }
Example #22
0
        public void exception_during_Done_onResolved_triggers_error_hander()
        {
            var promise = new Promise<int>();
            var callback = 0;
            var errorCallback = 0;
            var expectedValue = 5;
            var expectedException = new Exception();

            promise.Done(
                value =>
                {
                    Assert.Equal(expectedValue, value);

                    ++callback;

                    throw expectedException;
                },
                ex =>
                {
                    Assert.Equal(expectedException, ex);

                    ++errorCallback;
                }
            );

            promise.Resolve(expectedValue);

            Assert.Equal(1, callback);
            Assert.Equal(1, errorCallback);
        }
        public void CanHandleDoneOnResolved()
        {
            var promise = new Promise();
            var callback = 0;

            promise.Done(() => ++callback);

            promise.Resolve();

            Assert.AreEqual(1, callback);
        }
        public IPromise Resize <T>(TKey key, int desiredPoolSize) where T : TContract
        {
            Promise promise = new Promise();

            if (StackInactive(key) == desiredPoolSize)
            {
                promise.Resolve();
            }

            if (_settings.ExpandMethod == PoolExpandMethods.Disabled)
            {
                promise.Reject(new PoolExceededFixedSizeException(
                                   "Pool factory '{0}' attempted resize but pool set to fixed size of '{1}'!"
                                   .Fmt(GetType(), StackInactive(key))));
            }
            else
            {
                Assert.That(desiredPoolSize >= 0, "Attempted to resize the pool to a negative amount");

                while (_inactiveItems[key].Count > desiredPoolSize)
                {
                    OnDestroyed(key, _inactiveItems[key].Pop());
                }

                Promise <T> tmpSeq = null;

                for (int i = _inactiveItems[key].Count; i < desiredPoolSize; i++)
                {
                    if (tmpSeq == null)
                    {
                        tmpSeq = (Promise <T>)AllocNew <T>(key)
                                 .Then(item =>
                        {
                            _inactiveItems[key].Push(item);
                        });
                    }
                    else
                    {
                        tmpSeq = (Promise <T>)(tmpSeq.Then((o) =>
                        {
                            AllocNew <T>(key)
                            .Then(item =>
                            {
                                _inactiveItems[key].Push(item);
                            });
                        }));
                    }
                }

                if (tmpSeq != null)
                {
                    tmpSeq.Done(tmp =>
                    {
                        Assert.IsEqual(_inactiveItems[key].Count, desiredPoolSize);

                        promise.Resolve();
                    }, promise.Reject);
                }
                else
                {
                    promise.Resolve();
                }
            }

            return(promise);
        }
        public void CanHandleDoneOnResolvedWithOnReject()
        {
            var promise = new Promise();
            var callback = 0;
            var errorCallback = 0;

            promise.Done(
                () => ++callback,
                ex => ++errorCallback
            );

            promise.Resolve();

            Assert.AreEqual(1, callback);
            Assert.AreEqual(0, errorCallback);
        }
Example #26
0
 public void Propagate(Promise <T> source)
 {
     source.Done(Resolve).Fail(Reject).Disposed(Dispose);
 }
Example #27
0
    private void QueryForText(byte[] data, OnMessageHandler callback)
    {
        // register callback support (required for WebClient)
        if (ServicePointManager.ServerCertificateValidationCallback == null)
        {
            AddCertificateChainValidation();
        }

        // make the web call
        using (WebClient client = new WebClient())
        {
            client.Headers.Add("Ocp-Apim-Subscription-Key", VisionKey);
            client.Headers.Add("Content-Type", "application/octet-stream");
            client.UploadDataCompleted += (object sender, UploadDataCompletedEventArgs e) =>
            {
                try
                {
                    if (e.Cancelled)
                    {
                        _status = StatusOptions.failed;
                        RaiseError("web call was cancelled.", callback);
                    }
                    else if (e.Error != null)
                    {
                        _status = StatusOptions.failed;
                        RaiseError(e.Error.Message, callback);
                    }
                    else
                    {
                        string       response_string = System.Text.Encoding.Default.GetString(e.Result);
                        TextResponse response_object = JsonUtility.FromJson <TextResponse>(response_string);
                        if (response_object.regions != null && response_object.regions.Count > 0)
                        {
                            List <string> lines = new List <string>();
                            response_object.regions.ForEach(region =>
                            {
                                region.lines.ForEach(line =>
                                {
                                    List <string> words = new List <string>();
                                    line.words.ForEach(word =>
                                    {
                                        words.Add(word.text);
                                    });
                                    lines.Add(string.Join(" ", words.ToArray()));
                                });
                            });

                            // translate if requested
                            if (!string.IsNullOrEmpty(TranslationKey) && !string.IsNullOrEmpty(TranslateTo) && TranslateTo != response_object.language)
                            {
                                Promise <string> accessToken_promise = QueryForAccessToken();
                                accessToken_promise.Done(() =>
                                {
                                    Promise <string> translation_promise = QueryForTranslation(string.Join(" ", lines.ToArray()), response_object.language, "en");
                                    translation_promise.Done((msg) =>
                                    {
                                        List <string> translated = new List <string>();
                                        translated.Add(msg);
                                        RaiseMessage(new Message()
                                        {
                                            language = "en", lines = translated
                                        }, callback);
                                    });
                                    translation_promise.Fail((msg) =>
                                    {
                                        RaiseError(msg, callback);
                                    });
                                });
                                accessToken_promise.Fail((msg) =>
                                {
                                    RaiseError(msg, callback);
                                });
                            }
                            else
                            {
                                RaiseMessage(new Message()
                                {
                                    language = response_object.language, lines = lines
                                }, callback);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _status = StatusOptions.failed;
                    RaiseError(ex.Message, callback);
                }
                Reset();
            };
            client.UploadDataAsync(new System.Uri("https://" + Region + ".api.cognitive.microsoft.com/vision/v1.0/ocr?language=unk&detectOrientation=false"), data);
        }
    }
        public void CanHandleDoneOnResolvedWithOnReject()
        {
            var promise = new Promise<int>();
            var callback = 0;
            var errorCallback = 0;
            const int expectedValue = 5;

            promise.Done(
                value =>
                {
                    Assert.AreEqual(expectedValue, value);

                    ++callback;
                },
                ex =>
                {
                    ++errorCallback;
                }
            );

            promise.Resolve(expectedValue);

            Assert.AreEqual(1, callback);
            Assert.AreEqual(0, errorCallback);
        }
Example #29
0
 public void ShouldSendEvent(Cloud cloud)
 {
     Login2NewUsers(cloud, (gamer1, gamer2) => {
         // Wait event for P1
         Promise finishedSendEvent = new Promise();
         DomainEventLoop loop = gamer1.StartEventLoop();
         loop.ReceivedEvent += (sender, e) => {
             Assert(sender == loop, "Event should come from the loop");
             Assert(e.Message["event"]["hello"] == "world", "Message invalid");
             loop.Stop();
             // Wait the results of SendEvent as well
             finishedSendEvent.Done(CompleteTest);
         };
         // Send event as P2
         gamer2.Community.SendEvent(
             gamerId: gamer1.GamerId,
             eventData: Bundle.CreateObject("hello", "world"))
         .ExpectSuccess(result => {
             Assert(result, "Expected true result");
             finishedSendEvent.Resolve();
         });
     });
 }
Example #30
0
    private void PromisesShouldWorkProperlyPart2()
    {
        // 2) Test that that an unhandled exception is triggered as expected
        Promise[] expectingException = new Promise[1];
        EventHandler<ExceptionEventArgs> promiseExHandler = (sender, e) => {
            expectingException[0].Resolve();
        };
        FailOnUnhandledException = false;
        Promise.UnhandledException += promiseExHandler;

        Promise<bool> prom = new Promise<bool>();
        // With just then, the handler should not be called
        expectingException[0] = new Promise().Then(() => FailTest("Should not call UnhandledException yet"));
        prom.Reject(new InvalidOperationException());

        // But after a done, it should be invoked
        Wait(100).Then(() => {
            expectingException[0] = new Promise();
            expectingException[0].Then(() => {
                Promise.UnhandledException -= promiseExHandler;
                FailOnUnhandledException = true;
                PromisesShouldWorkProperlyPart3();
            });
            prom.Done();
        });
    }