public async Task WhenInSuspendedState_ShouldTryAndReconnectAfterSuspendRetryTimeoutIsReached()
        {
            Now = DateTimeOffset.UtcNow;

            _fakeTransportFactory.initialiseFakeTransport =
                transport => transport.OnConnectChangeStateToConnected = false;
            //this will keep it in connecting state

            var client = GetClientWithFakeTransport(opts =>
            {
                opts.AutoConnect = false;
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(100);
            });

            client.Connect();
            do
            {
                LastCreatedTransport.Listener?.OnTransportEvent(TransportState.Closing, new Exception());

                await WaitForConnectingOrSuspended(client);

                Now = Now.AddSeconds(30);
            } while (client.Connection.State != ConnectionState.Suspended);

            var awaiter = new ConnectionAwaiter(client.Connection, ConnectionState.Connecting);
            var elapsed = await awaiter.Wait();

            elapsed.Should().BeCloseTo(client.Options.SuspendedRetryTimeout, 100);
        }
            public async Task ItShouldRenewTheLeaseWithRateLimiter()
            {
                this.SetupAquireMocks();
                await this.target.AcquireLeaseAsync();

                this.blob.Setup(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken))
                .Returns(Task.FromResult(0)).Verifiable();

                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(0));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds - 1));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(0));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(1));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds((BlobLease.RenewRateLimitSeconds * 2) - 1));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(1));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds * 2));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(2));

                this.blob.Verify();
            }
        public async Task WhenInSuspendedStateAfterRetrying_ShouldGoBackToSuspendedState()
        {
            Now = DateTimeOffset.UtcNow;

            _fakeTransportFactory.initialiseFakeTransport =
                transport => transport.OnConnectChangeStateToConnected = false;
            //this will keep it in connecting state

            var client = GetClientWithFakeTransport(opts =>
            {
                opts.AutoConnect = false;
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(10);
                opts.RealtimeRequestTimeout   = TimeSpan.FromMilliseconds(100);
            });

            client.Connect();
            do
            {
                LastCreatedTransport.Listener?.OnTransportEvent(TransportState.Closing, new Exception());
                await WaitForConnectingOrSuspended(client);

                Now = Now.AddSeconds(30);
            } while (client.Connection.State != ConnectionState.Suspended);

            await new ConnectionAwaiter(client.Connection, ConnectionState.Connecting).Wait();
            await new ConnectionAwaiter(client.Connection, ConnectionState.Suspended).Wait();
        }
Example #4
0
        public void CountDownToStringIsHHMM()
        {
            var startedTimer = _countDownTimer.Start();

            Now = Now.AddSeconds(30);
            Assert.Equal($"14:30", startedTimer.ToString());
        }
 public void ShouldSuspend_WhenFirstAttemptEqualOrGreaterThanConnectionStateTtl_ShouldReturnTrue()
 {
     Now = DateTimeOffset.Now;
     _info.Attempts.Add(new ConnectionAttempt(Now));
     //Move now to default ConnetionStatettl - 1 second
     Now = Now.Add(Defaults.ConnectionStateTtl);
     _info.ShouldSuspend().Should().BeTrue("When time is equal");        // =
     Now = Now.AddSeconds(1);
     _info.ShouldSuspend().Should().BeTrue("When time is greater than"); // >
 }
Example #6
0
    void Update()
    {
        if (Application.isEditor && !Application.isPlaying)
        {
            ReloadNow();
            return;
        }

        then = Now;
        Now  = Now.AddSeconds(GameSpeed * Time.deltaTime);
    }
Example #7
0
 protected virtual void Tick()
 {
     if (IsRunning)
     {
         Time++;
         Now = Now.AddSeconds(1);
         if (Ontick != null)
         {
             Ontick();
         }
     }
 }
Example #8
0
 private IEnumerator Tick()
 {
     while (IsRunning)
     {
         Time++;
         Now = Now.AddSeconds(1);
         if (Ontick != null)
         {
             Ontick();
         }
         yield return(new WaitForSeconds(1 * UnityEngine.Time.timeScale));
     }
 }
Example #9
0
 private void OnTick(object sender, ElapsedEventArgs elapsedEventArgs)
 {
     if (IsRunning)
     {
         Time++;
         Now = Now.AddSeconds(1);
         Now = elapsedEventArgs.SignalTime;
         if (Ontick != null)
         {
             Ontick();
         }
     }
 }
Example #10
0
        public async Task WhenItMovesFromDisconnectedToSuspended_ShouldTryDefaultHostAgain()
        {
            var client = GetConnectedClient(opts =>
            {
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(10);
            });

            List <ConnectionState> states = new List <ConnectionState>();

            client.Connection.InternalStateChanged += (sender, args) =>
            {
                states.Add(args.Current);
            };

            List <string> retryHosts = new List <string>();

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo()
                {
                    StatusCode = HttpStatusCode.GatewayTimeout
                }
            });

            for (int i = 0; i < 5; i++)
            {
                Now = Now.AddSeconds(60);
                if (client.Connection.State == ConnectionState.Connecting)
                {
                    retryHosts.Add(LastCreatedTransport.Parameters.Host);
                }
                else
                {
                    await Task.Delay(50); //wait just enough for the disconnect timer to kick in

                    retryHosts.Add(LastCreatedTransport.Parameters.Host);
                }

                await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
                {
                    Error = new ErrorInfo()
                    {
                        StatusCode = HttpStatusCode.GatewayTimeout
                    }
                });
            }

            retryHosts.Should().Contain("realtime.ably.io");
            retryHosts.Count(x => x == "realtime.ably.io").Should().Be(1);
        }
Example #11
0
            public async void RequestMissed_RequestAgain()
            {
                var missedDeadline = Now.Add(-DeviceSyncConstants.PushMissed);
                var service        = new PushSyncService(MockPushSyncStore(new[] { new SyncAction()
                                                                                   {
                                                                                       Id       = "test",
                                                                                       Deadline = missedDeadline
                                                                                   } }).Object, MockDigitPushServiceCLient(),
                                                         Mock.Of <IFocusStore>());

                var res = await service.RequestLocationSync(userId, Now.AddSeconds(1), Now.AddSeconds(1));

                Assert.True(res.SyncRequested);
                Assert.Null(res.SyncPendingFor);
            }
Example #12
0
        /// <summary>
        /// Method scans miscellaneous files in "Misc" file
        /// </summary>
        static void MiscScan()
        {
            WriteLine("-- Miscellaneous File Scanner --");
            WriteLine();

            if (!File.Exists(Globals.MiscFile))  // safeguard misc file search
            {
                ForegroundColor = Yellow;
                WriteLine("No miscellaneous file to scan");
                ResetColor();
                Exit(0);
            }

            var miscFeed = new System.Collections.Generic.Dictionary <string, string>();

            foreach (var entry in File.ReadAllLines(Globals.MiscFile))
            {
                var split = entry.Split('|');
                miscFeed.Add(split[0], split[1]);
            }

            ForegroundColor = Blue;
            WriteLine($"[*] Scan Started At {Globals.CurrentDateTime}");
            foreach (var hash in miscFeed.Keys)
            {
                ForegroundColor = Yellow;
                WriteLine($"[~] Scanning {miscFeed[hash]}");
                var report    = Report(hash);
                int detection = 0;
                foreach (var av in report.Scans.Keys)
                {
                    if (report.Scans[av].Detected)
                    {
                        detection++;
                    }
                }
                FormatDetection(detection);
                WriteLine($"[#] Next Scan At {Now.AddSeconds(30):dd/MM/yyyy hh:mm:ss tt}");
                Sleep(30000);
            }
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Completed At {Globals.CurrentDateTime}");
            ResetColor();
            File.Delete(Globals.MiscFile); // delete file
        }
Example #13
0
        public static (string, DateTime) GetAPIToken(string user, string pw)
        {
            using (var myWebClient = new WebClientNoRedir()
            {
                Proxy = GetProxy()
            })
            {
                //string key = "nQv6CqtxJuXWP74xf3CJwUEP";
                //string secret = "1zDHx6un4cDjybLENN3kyfumX2kEYigWPcQpdvDRpIBk7rOJ";
                //string basic = ($"{key}:{secret}").ToBase64String();

                var WS_Data = new NameValueCollection
                {
                    { "username", user },
                    { "password", pw },
                    { "scope", "authenticate_user remote_services vehicle_data" },
                    { "client_id", "dbf0a542-ebd1-4ff0-a9a7-55172fbfce35" },
                    { "response_type", "token" },
                    { "redirect_uri", "https://www.bmw-connecteddrive.com/app/static/external-dispatch.html" }
                };
                // myWebClient.Headers.Add("Authorization", "Basic " + basic);
                myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                string response = "";

                try
                {
                    response = myWebClient.UploadString($"{AuthServer}", WS_Data.ToQueryString(isEscaped: false));
                }
                catch (System.Exception ex)
                {
                    Trace.Write("TokenRenew");
                    Trace.WriteLine(ex.Message);
                }

                string tokenInside = new Uri(myWebClient.ResponseHeaders["Location"]).Fragment.Remove(0, 1);
                response = System.Web.HttpUtility.ParseQueryString(tokenInside)["access_token"];
                string expires = System.Web.HttpUtility.ParseQueryString(tokenInside)["expires_in"];
                return(response, DateTime.Now.AddSeconds(int.Parse(expires) - 10));
            }
        }
Example #14
0
        protected virtual void OnTick(object state)
        {
            if (IsRunning)
            {
                Time++;
                Now = Now.AddSeconds(1);

                if (Ontick != null)
                {
                    Ontick();
                }

                clocks.ForEach(c => c.Update());
                for (int i = 0; i < reminders.Count; i++)
                {
                    if (reminders[i].Update(Now) && reminders[i].Type == ReminderType.OneTime)
                    {
                        reminders.RemoveAt(i);
                    }
                }
            }
        }
Example #15
0
        public async Task Authorise_WithTokenExpiringIn15Seconds_RenewsToken(int secondsLeftToExpire, bool shouldRenew)
        {
            var client       = GetRestClient();
            var initialToken = new TokenDetails()
            {
                Expires = Now.AddSeconds(secondsLeftToExpire)
            };

            client.AblyAuth.CurrentToken = initialToken;

            var token = await client.Auth.AuthoriseAsync();

            if (shouldRenew)
            {
                Assert.Contains("requestToken", LastRequest.Url);
                token.Should().NotBeSameAs(initialToken);
            }
            else
            {
                token.Should().BeSameAs(initialToken);
            }
        }
        public async Task WhenTransportFails_ShouldGoFromConnectingToDisconectedUntilConnectionStateTtlIsReachedAndStateIsSuspended()
        {
            Now = DateTimeOffset.UtcNow;

            _fakeTransportFactory.initialiseFakeTransport =
                transport => transport.OnConnectChangeStateToConnected = false;
            //this will keep it in connecting state

            var client = GetClientWithFakeTransport(opts =>
            {
                opts.AutoConnect = false;
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
            });

            client.Connect();
            List <ConnectionStateChange> stateChanges = new List <ConnectionStateChange>();

            client.Connection.InternalStateChanged += (sender, args) =>
            {
                stateChanges.Add(args);
            };

            do
            {
                LastCreatedTransport.Listener?.OnTransportEvent(TransportState.Closing, new Exception());
                await WaitForConnectingOrSuspended(client);

                Now = Now.AddSeconds(30);
            } while (client.Connection.State != ConnectionState.Suspended);

            client.Connection.State.Should().Be(ConnectionState.Suspended);

            stateChanges.Select(x => x.Current).Distinct()
            .ShouldBeEquivalentTo(new[] { ConnectionState.Connecting, ConnectionState.Disconnected, ConnectionState.Suspended, });
            int numberOfAttemps = (int)Math.Floor(Defaults.ConnectionStateTtl.TotalSeconds / 30);

            stateChanges.Count(x => x.Current == ConnectionState.Connecting).Should().Be(numberOfAttemps);
        }
Example #17
0
        /// <summary>
        /// Method Scans the curr dir.
        /// </summary>
        static void ScanCurrDir()
        {
            int total = 0;

            WriteLine("-- Directory Scanner --");
            WriteLine();
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Started At {Globals.CurrentDateTime}");
            ResetColor();

            // getting filenames
            var files = Directory.GetFiles(CurrentDirectory, "*", SearchOption.AllDirectories);
            // instacing misc to store misc files
            var misc   = new System.Collections.Generic.List <string>();
            var isMisc = false; // flag to check if any misc file

            foreach (var file in files)
            {
                if (++total > 5000)  // safeguard api calls
                {
                    ForegroundColor = Red;
                    WriteLine("You reached  5000/per day scan limit");
                    WriteLine("If you try to scan again then your API may be blocked");
                    ResetColor();
                    Exit(1);
                }
                var fileInfo = new FileInfo(file);
                if (fileInfo.Length < 1.28e+8)  // safeguard file size
                {
                    ForegroundColor = Yellow;
                    WriteLine($"[~] Scanning {fileInfo.FullName}");
                    ResetColor();
                    var report = Report(Globals.GetSHA256(fileInfo.FullName));
                    if (report.ResponseCode == FileReportResponseCode.Present)
                    {
                        // execute detection and format detection if file is present on server
                        int detected = 0;
                        foreach (var av in report.Scans.Keys)
                        {
                            if (report.Scans[av].Detected)
                            {
                                detected++;
                            }
                        }
                        FormatDetection(detected);
                    }
                    // otherwise misc file is not there or is being scanned
                    else if (report.ResponseCode == FileReportResponseCode.Queued)
                    {
                        // file is queued
                        ForegroundColor = Magenta;
                        WriteLine("[!] Not found - Misc File");
                        ResetColor();
                    }
                    else
                    {
                        ForegroundColor = Magenta;
                        WriteLine("[!] Not found - Misc File");
                        ResetColor();
                        var scan = SendScan(fileInfo);
                        misc.Add($"{scan.SHA256}|{fileInfo.FullName}");  // adding to misc file
                        isMisc = true;
                        //break;
                    }
                    WriteLine($"[#] Next Scan At {Now.AddSeconds(30):dd/MM/yyyy hh:mm:ss tt}");
                    Sleep(30000); // sleep to prevent spamming
                }
                else
                {
                    ForegroundColor = Yellow;
                    WriteLine($"[!] Skipping {fileInfo.FullName} - Beyond 128mB");
                    ResetColor();
                }
            }
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Completed At {Globals.CurrentDateTime}");
            ResetColor();
            if (isMisc)
            {
                // writing misc files
                File.WriteAllLines(Globals.MiscFile, misc.ToArray());
                WriteLine();
                WriteLine("We found some miscellaneous files");
                WriteLine($"Try scaning misc file after {Now.AddHours(5):dd/MM/yyyy hh:mm:ss tt}");
            }
        }