Ejemplo n.º 1
0
        public async Task <HttpResponseMessage> SendAsync(HttpMethod method)
        {
            HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            client = new HttpClient(handler);
            await TaskV2.Delay(5); // Wait so that the created RestRequest can be modified before its sent

            httpMethod = "" + method;
            client.AddRequestHeaders(requestHeaders);
            var message = new HttpRequestMessage(method, uri);

            if (httpContent != null)
            {
                message.Content = httpContent;
            }
            request = client.SendAsync(message, sendAsyncCompletedAfter);
            var result        = await request;
            var serverUtcDate = result.Headers.Date;

            if (serverUtcDate != null)
            {
                EventBus.instance.Publish(DateTimeV2.SERVER_UTC_DATE, uri, serverUtcDate.Value.DateTime);
            }
            return(result);
        }
Ejemplo n.º 2
0
        public async Task TestThrottledDebounce2()
        {
            int counter = 0;
            EventHandler <int> action = (_, myIntParam) => {
                Log.d("myIntParam=" + myIntParam);
                Interlocked.Increment(ref counter);
            };
            var throttledAction = action.AsThrottledDebounce(delayInMs: 5);

            var tasks = new List <Task>();

            for (int i = 0; i < 100; i++)   // Do 100 calls of the method in parallel:
            {
                var myIntParam = i;
                tasks.Add(TaskV2.Run(() => { throttledAction(this, myIntParam); }));
            }
            await Task.WhenAll(tasks.ToArray());

            for (int i = 0; i < 20; i++)
            {
                await TaskV2.Delay(5); if (counter >= 2)
                {
                    break;
                }
            }
            Assert.Equal(2, counter);
            await TaskV2.Delay(100);

            Assert.Equal(2, counter);
        }
Ejemplo n.º 3
0
        private static async Task TestAsyncActions(IDataStore <MyAppState1> store)
        {
            var t = Log.MethodEntered("TestAsyncActions");

            Assert.Null(store.GetState().currentWeather);
            // Create an async action and dispatch it so that it is executed by the thunk middleware:
            var a = store.Dispatch(NewAsyncGetWeatherAction());

            Assert.True(a is Task, "a=" + a.GetType());
            if (a is Task delayedTask)
            {
                await delayedTask;
            }
            Assert.NotEmpty(store.GetState().currentWeather);

            store.Dispatch(new ActionLogoutUser());
            Assert.Null(store.GetState().user);

            // Another asyn task example with an inline lambda function:
            Func <Task> asyncLoginTask = async() => {
                await TaskV2.Delay(100); // Simulate that the login would talk to a server and take some time

                // Here the user would be logged into the server and returned to the client to store it:
                store.Dispatch(new ActionLoginUser()
                {
                    newLoggedInUser = new MyUser1("Karl")
                });
            };

            // Since the async action uses Func<Task> the returned object can be awaited on:
            await(store.Dispatch(asyncLoginTask) as Task);
            Assert.NotNull(store.GetState().user);

            Log.MethodDone(t);
        }
Ejemplo n.º 4
0
        public async Task TestDefaultAppFlowImplementation()
        {
            var tracker = new MyAppFlowTracker2(new InMemoryKeyValueStore().GetTypeAdapter <AppFlowEvent>());

            tracker.WithBasicTrackingActive();
            Log.MethodEntered(); // This will internally notify the AppFlow instance
            Assert.NotEmpty(await tracker.store.GetAllKeys());

            var s = StopwatchV2.StartNewV2();

            for (int i = 0; i < 20; i++)
            {
                await TaskV2.Delay(500);

                if ((await tracker.store.GetAllKeys()).Count() == 0)
                {
                    break;
                }
            }
            Assert.True(s.ElapsedMilliseconds < 20000, "20000 < s.ElapsedMilliseconds=" + s.ElapsedMilliseconds);

            Assert.Empty(await tracker.store.GetAllKeys());
            // Make sure the DefaultAppFlowImpl itself does not create more events while sending the existing ones:
            for (int i = 0; i < 10; i++)
            {
                await TaskV2.Delay(100);

                var c1 = tracker.eventsThatWereSent.Count;
                await TaskV2.Delay(100);

                var c2 = tracker.eventsThatWereSent.Count;
                Assert.Equal(c1, c2);
            }
        }
Ejemplo n.º 5
0
        public async Task TestThrottledDebounce5()
        {
            int delayInMs = 200;
            Func <object, Task> originalFunction = async(object sender) => {
                Assert.Equal("good", sender);
                await TaskV2.Delay(delayInMs * 4);
            };
            var wrappedFunc = originalFunction.AsThrottledDebounce(10);

            var t    = Stopwatch.StartNew();
            var task = wrappedFunc("good");
            await TaskV2.Delay(delayInMs);

            Assert.Null(wrappedFunc("bad"));
            Assert.Null(wrappedFunc("bad"));
            Assert.Null(wrappedFunc("bad"));
            await task;
            await TaskV2.Delay(delayInMs);

            task = wrappedFunc("good");
            Assert.NotNull(task);
            Assert.Null(wrappedFunc("bad"));
            Assert.Null(wrappedFunc("bad"));
            Assert.Null(wrappedFunc("bad"));
            await task;

            Assert.True(t.ElapsedMilliseconds > 200, "ElapsedMilliseconds=" + t.ElapsedMilliseconds);
        }
Ejemplo n.º 6
0
        private async Task SomeAsyncTask1(CancellationToken cancelRequest)
        {
            var t = Log.MethodEntered();
            await TaskV2.Delay(500);

            Log.MethodDone(t);
        }
Ejemplo n.º 7
0
        public async Task TestOnError()
        {
            {
                var errorHandled = false;
                await SomeAsyncFailingTask1().OnError(async _ => {
                    await TaskV2.Delay(5);
                    errorHandled = true; // error can be rethrown here
                });

                Assert.True(errorHandled);
            }
            {
                var errorHandled = false;
                var result       = await SomeAsyncFailingTask2().OnError(async _ => {
                    await TaskV2.Delay(5);
                    errorHandled = true;
                    return("handled");
                });

                Assert.Equal("handled", result);
                Assert.True(errorHandled);
            }
            { // The error can be rethrown in OnError handler after reacting to it:
                await Assert.ThrowsAsync <AggregateException>(async() => {
                    await SomeAsyncFailingTask1().OnError(async error => {
                        await TaskV2.Delay(5);
                        throw error;
                    });
                });
            }
        }
Ejemplo n.º 8
0
 private static Task ConfirmButtonClicked(GameObject targetView, string confirmButtonId)
 {
     return(targetView.GetLinkMap().Get <Button>(confirmButtonId).SetOnClickAction(async delegate {
         Toast.Show("Saving..");
         await TaskV2.Delay(500); // Wait for potential pending throttled actions to update the model
     }));
 }
Ejemplo n.º 9
0
        public async Task ThrottledDebounceExample1()
        {
            int             counter     = 0;
            bool            allWereGood = true;
            Action <string> action      = (myStringParam) => {
                // Make sure the action is never called with "bad" being passed:
                if (myStringParam != "good")
                {
                    allWereGood = false;
                }
                Interlocked.Increment(ref counter);
            };

            // Make the action throttled / debounced:
            action = action.AsThrottledDebounce(delayInMs: 50);

            // Call it multiple times with less then 50ms between the calls:
            action("good"); // The first call will always be passed through
            action("bad");  // This one will be delayed and not called because of the next:
            action("good"); // This will be delayed for 50ms and then triggered because no additional call follows after it

            // Wait a little bit until the action was triggered at least 2 times:
            for (int i = 0; i < 50; i++)
            {
                await TaskV2.Delay(200); if (counter >= 2)
                {
                    break;
                }
            }
            Assert.Equal(2, counter);
            Assert.True(allWereGood);
        }
Ejemplo n.º 10
0
        public async Task TestEventListeners()
        {
            using (ProgressV2 progress = new ProgressV2("p3", 200)) {
                var progressEventTriggered = false;
                progress.ProgressChanged += (o, newValue) => {
                    Log.e(JsonWriter.AsPrettyString(o));
                    Assert.Equal(100, newValue);
                    progressEventTriggered = true;
                };
                await TaskV2.Run(() => {
                    ((IProgress <double>)progress).Report(100);
                    Assert.False(progressEventTriggered);
                    Assert.Equal(100, progress.GetCount());
                    Assert.Equal(50, progress.percent);
                });

                Assert.Equal(100, progress.GetCount());
                Assert.Equal(50, progress.percent);

                // The progress callback is dispatched using the SynchronizationContext
                // of the constructor, so it will have some delay before being called:
                Assert.False(progressEventTriggered);
                await TaskV2.Delay(50); // Wait for progress update to be invoked

                Assert.True(progressEventTriggered);
            }
        }
Ejemplo n.º 11
0
        private async Task <string> SomeAsyncFailingTask2()
        {
            var t = Log.MethodEntered();
            await TaskV2.Delay(5);

            throw new Exception("task failed as requested");
        }
Ejemplo n.º 12
0
        public async Task TestRunRepeated1()   // Aligned with the coroutine test TestExecuteRepeated1
        {
            var counter = 0;
            var cancel  = new CancellationTokenSource();
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                TaskV2.RunRepeated(async() => {
                    await TaskV2.Delay(1);
                    counter++;
                    return(counter < 3); // stop repeated execution once 3 is reached
                }, delayInMsBetweenIterations: 300, cancelToken: cancel.Token, delayInMsBeforeFirstExecution: 200);
#pragma warning restore CS4014           // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            {                            // while the repeated task is running check over time if the counter increases:
                await TaskV2.Delay(100);

                Assert.Equal(0, counter);
                await TaskV2.Delay(200);

                Assert.Equal(1, counter);
                await TaskV2.Delay(300);

                Assert.Equal(2, counter);
                await TaskV2.Delay(300);

                Assert.Equal(3, counter);
                await TaskV2.Delay(300);

                Assert.Equal(3, counter);
            }
            cancel.Cancel();
        }
Ejemplo n.º 13
0
        private async Task SomeAsyncTask1()
        {
            var t = Log.MethodEntered();
            await TaskV2.Delay(500);

            Log.MethodDone(t);
        }
Ejemplo n.º 14
0
        public async Task ExampleUsage1()
        {
            Log.d("Now testing TaskV2.Run");
            await TaskV2.Run(() => {
                var t = Log.MethodEntered("1");
                TaskV2.Delay(100).ContinueWithSameContext(delegate {
                    Log.MethodDone(t);
                });
            });

            Log.d("Now testing async TaskV2.Run");
            await TaskV2.Run(async() => {
                var t = Log.MethodEntered("2");
                await TaskV2.Delay(100);
                Log.MethodDone(t);
            });

            Log.d("Now testing async TaskV2.Run with return value");
            var result = await TaskV2.Run(async() => {
                var t = Log.MethodEntered("3");
                await TaskV2.Delay(100);
                Log.MethodDone(t);
                return("3");
            });

            Assert.Equal("3", result);
        }
Ejemplo n.º 15
0
                public async Task <ServerActionResult> SendToServer()
                {
                    var t = Log.MethodEntered();
                    await TaskV2.Delay(10); // communication with server would happen here

                    sentToServerCounter++;
                    if (simulateOneTimeout)
                    {
                        simulateOneTimeout = false; return(ServerActionResult.RETRY);
                    }
                    if (simulateError)
                    {
                        return(ServerActionResult.FAIL);
                    }
                    // After communicating with the server an additional store update might be needed:
                    var serverConfirmedEmail = true; // <- this answer would come from the server
                    var store = IoC.inject.Get <DataStore <MyAppState1> >(this);

                    store.Dispatch(new ActionOnUser.EmailConfirmed()
                    {
                        targetEmail      = newEmail,
                        isEmailConfirmed = serverConfirmedEmail
                    });
                    return(ServerActionResult.SUCCESS);
                }
Ejemplo n.º 16
0
        private async Task <string> SomeAsyncTask2()
        {
            var t = Log.MethodEntered();
            await TaskV2.Delay(5);

            Log.MethodDone(t);
            return("Some string result");
        }
Ejemplo n.º 17
0
            protected override async Task <bool> SendEventToExternalSystem(AppFlowEvent appFlowEvent)
            {
                Log.d("SendEventToExternalSystem called with appFlowEvent=" + JsonWriter.AsPrettyString(appFlowEvent));
                await TaskV2.Delay(10); // Simulate that sending the event to an analytics server takes time

                eventsThatWereSent.Add(appFlowEvent);
                return(true);
            }
Ejemplo n.º 18
0
        private async Task <string> SomeAsyncTask2(CancellationToken cancelRequest)
        {
            var t = Log.MethodEntered();
            await TaskV2.Delay(5);

            Log.MethodDone(t);
            return("Some string result");
        }
Ejemplo n.º 19
0
        public static async Task RunTest(this XunitTestRunner.Test self)
        {
            using (var t = Log.MethodEnteredWith("XUnit-Test: " + self)) {
                await TaskV2.Delay(100);

                self.StartTest();
                await self.testTask;
            }
        }
Ejemplo n.º 20
0
        private async Task SimulateDelay()
        {
            await TaskV2.Delay(delay);

            if (throwTimeoutError)
            {
                throw new TimeoutException("Simulated error");
            }
        }
Ejemplo n.º 21
0
            public async Task OnLoad(MyUserModel userToShow)
            {
                await TaskV2.Delay(5); // Simulate a delay

                links = targetView.GetLinkMap();
                NameInputField().text = userToShow.userName;
                AgeInputField().text  = "" + userToShow.userAge;
                var saveTask = links.Get <Button>("Save").SetOnClickAction(delegate { SaveViewIntoModel(userToShow); });
            }
Ejemplo n.º 22
0
        public IEnumerator TestThrowsAsyncPart1()
        {
            yield return(Assert.ThrowsAsync <FormatException>(async() => {
                await TaskV2.Delay(10);
                throw new FormatException();
            }).AsCoroutine());

            yield return(TaskV2.Run(TestThrowsAsyncPart2).AsCoroutine());
        }
Ejemplo n.º 23
0
            public async Task OnLoad(MyUser3 model)
            {
                await TaskV2.Delay(10); // Simulate a 10ms delay in the UI update

                links         = targetView.GetLinkMap();
                NameUi().text = model.name;
                AgeUi().text  = "" + model.age;
                links.Get <Button>("Save").SetOnClickAction(delegate { UpdateUser(model); });
            }
Ejemplo n.º 24
0
        private async Task SimulateConfirmButtonClick()
        {
            if (simulateUserInput)
            {
                await TaskV2.Delay(waitDurationPerDialogInMS);

                Log.d("Now simulating the user clicking on the confirm button");
                RootCanvas.GetOrAddRootCanvas().gameObject.GetLinkMap().Get <Button>("ConfirmButton").onClick.Invoke();
            }
        }
Ejemplo n.º 25
0
        public async Task TestInternetStateListener()
        {
            await InternetStateManager.AddListener(this);

            Assert.False(InternetStateManager.Get(this).hasInet);
            Assert.False(hasInet);
            await TaskV2.Delay(2500);

            Assert.True(hasInet);
        }
Ejemplo n.º 26
0
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

        private static async Task CheckAllAssembliesInProject()
        {
            await TaskV2.Delay(1000);

            var allAssemblies = GetAllAssembliesInProject().Filter(ShouldBeIncludedInCheck);

            foreach (var assembly in allAssemblies)
            {
                CheckTypesInAssembly(assembly);
            }
        }
Ejemplo n.º 27
0
 public async Task <Headers> GetResultHeaders()
 {
     if (request.isModifiable)
     {
         return(await GetResult <Headers>());
     }
     while (!request.isDone && !request.isHttpError && !request.isNetworkError)
     {
         await TaskV2.Delay(5);
     }
     return(request.GetResponseHeadersV2());
 }
Ejemplo n.º 28
0
        private async Task TestThrowsAsyncPart2()
        {
            try {
                await Assert.ThrowsAsync <FormatException>(async() => {
                    await TaskV2.Delay(10);
                    throw new NullReferenceException("abc");
                });

                throw Log.e("Assert.ThrowsAsync did not rethrow the NullReferenceException");
            }
            catch (NullReferenceException e) { NUnit.Framework.Assert.AreEqual("abc", e.Message); }
        }
Ejemplo n.º 29
0
 private async Task WaitForRequestToFinish()
 {
     while (!request.isDone && !request.isHttpError && !request.isNetworkError)
     {
         if (CancellationTokenSource.IsCancellationRequested)
         {
             request.Abort();
         }
         CancellationTokenSource.Token.ThrowIfCancellationRequested();
         await TaskV2.Delay(10);
     }
 }
Ejemplo n.º 30
0
        // Logging when I method is entered and left:
        private async Task SomeExampleMethod1(string s, int i)
        {
            Stopwatch timing = Log.MethodEntered("SomeExampleMethod1", "s =" + s, "i=" + i);

            { // .. here would be some method logic ..
                Log.d("Will now work for 5 ms");
                await TaskV2.Delay(5);

                Log.d("worked for 5 ms");
            } // .. as the last line in the tracked method add:
            Log.MethodDone(timing, maxAllowedTimeInMs: 5000);
        }