Ejemplo n.º 1
0
            public async Task WithOptions_AddsParametersToRequest_UsingCompatHistoryParams()
            {
                /*
                 * In a breaking change in the 1.1 release HistoryRequestParams was replaced with PaginatedRequestParams.
                 * To fix this backward compatibility issue a new HistoryRequestParams class the inherits from PaginatedRequestParams
                 * has been created.
                 *
                 * This test demonstrates that HistoryRequestParams can be used to call
                 * HistoryAsync (which accepts a PaginatedRequestParams instance as a parameter.
                 */

#pragma warning disable CS0618 // Type or member is obsolete
                var query = new HistoryRequestParams();
#pragma warning restore CS0618 // Type or member is obsolete
                var now = DateTimeOffset.Now;
                query.Start     = now.AddHours(-1);
                query.End       = now;
                query.Direction = QueryDirection.Forwards;
                query.Limit     = 1000;
                await _channel.HistoryAsync(query);

                LastRequest.AssertContainsParameter("start", query.Start.Value.ToUnixTimeInMilliseconds().ToString());
                LastRequest.AssertContainsParameter("end", query.End.Value.ToUnixTimeInMilliseconds().ToString());
                LastRequest.AssertContainsParameter("direction", query.Direction.ToString().ToLower());
                LastRequest.AssertContainsParameter("limit", query.Limit.Value.ToString());
            }
Ejemplo n.º 2
0
        public void UpdateMessages(RtspMessage request, RtspMessage response)
        {
            if (Common.IDisposedExtensions.IsNullOrDisposed(request).Equals(false) &&
                Common.IDisposedExtensions.IsNullOrDisposed(LastRequest).Equals(false))
            {
                LastRequest.IsPersistent = false;

                LastRequest.Dispose();
            }

            if (Common.IDisposedExtensions.IsNullOrDisposed(LastRequest = request).Equals(false))
            {
                LastRequest.IsPersistent = true;
            }

            if (Common.IDisposedExtensions.IsNullOrDisposed(LastResponse).Equals(false))
            {
                LastResponse.IsPersistent = false;

                LastResponse.Dispose();
            }

            if (Common.IDisposedExtensions.IsNullOrDisposed(LastResponse = response).Equals(false))
            {
                LastResponse.IsPersistent = true;
            }
        }
Ejemplo n.º 3
0
            public async Task WithClientIdAndConnectionId_ShouldSetQueryParameters()
            {
                const string clientId     = "123";
                const string connectionId = "333";
                await _channel.Presence.GetAsync(clientId : clientId, connectionId : connectionId);

                LastRequest.AssertContainsParameter("clientId", clientId);
                LastRequest.AssertContainsParameter("connectionId", connectionId);
            }
        private void Throttle()
        {
            if (LastRequest != null && !LastRequest.HasElapsed(RequestDelay, true))
            {
                var sleepTime = RequestDelay - (DateTime.UtcNow - LastRequest.Value);
                Trace.TraceInformation("Throttle: " + sleepTime.TotalSeconds + " seconds.");
                Thread.Sleep(sleepTime);
            }

            LastRequest = DateTime.UtcNow;
        }
Ejemplo n.º 5
0
        public async Task ShouldPassLimitWithDefaultof100(int?limit)
        {
            var query = new StatsRequestParams();

            if (limit.HasValue)
            {
                query.Limit = limit.Value;
            }

            await ExecuteStatsQuery(query);

            LastRequest.AssertContainsParameter("limit", limit.GetValueOrDefault(100).ToString());
        }
Ejemplo n.º 6
0
        public async Task ShouldPassStatsByToQueryWithDefaultOfMinute(StatsIntervalGranularity?statsGranularity)
        {
            var query = new StatsRequestParams();

            if (statsGranularity.HasValue)
            {
                query.Unit = statsGranularity.Value;
            }

            await ExecuteStatsQuery(query);

            LastRequest.AssertContainsParameter("by", statsGranularity.GetValueOrDefault(StatsIntervalGranularity.Minute).ToString().ToLower());
        }
Ejemplo n.º 7
0
            public async Task WithLimitParameter_ShouldSetLimitHeaderOrThrowForInvalidValues(int?limit, string expectedLimitHeader, bool throws)
            {
                if (throws)
                {
                    _ = await Assert.ThrowsAsync <ArgumentException>(() => _channel.Presence.GetAsync(limit));
                }
                else
                {
                    _ = await _channel.Presence.GetAsync(limit);

                    LastRequest.AssertContainsParameter("limit", expectedLimitHeader);
                }
            }
Ejemplo n.º 8
0
        public async Task ShouldAcceptStartAndEndDateTimes(int startOffset, int endOffset, QueryDirection direction)
        {
            var query = new StatsRequestParams
            {
                Start     = Now.AddHours(startOffset),
                End       = Now.AddHours(endOffset),
                Direction = direction
            };

            await ExecuteStatsQuery(query);

            LastRequest.AssertContainsParameter("start", query.Start.Value.ToUnixTimeInMilliseconds().ToString());
            LastRequest.AssertContainsParameter("end", query.End.Value.ToUnixTimeInMilliseconds().ToString());
        }
Ejemplo n.º 9
0
        public BroadcastProcess(TickRates tickRates)
        {
            this.tickRates   = tickRates;
            this.lastRequest = new LastRequest
            {
                gps      = DateTime.UtcNow,
                traffic  = DateTime.UtcNow,
                attitude = DateTime.UtcNow
            };

            simConnect = new SimConnectInterface(OnConnectHandler, OnDisconnectHandler, OnExceptionHandler);
            simConnect.Connect();
            simConnect.InitDataRequest(OnRecieveAircraftData, OnRecieveTrafficData, OnRecieveAttitudeData);

            efbBroadcast = new EFBBroadcast();
        }
Ejemplo n.º 10
0
            public async Task WithOptions_AddsParametersToRequest()
            {
                var query = new HistoryRequestParams();
                var now   = DateTimeOffset.Now;

                query.Start     = now.AddHours(-1);
                query.End       = now;
                query.Direction = QueryDirection.Forwards;
                query.Limit     = 1000;
                await _channel.HistoryAsync(query);

                LastRequest.AssertContainsParameter("start", query.Start.Value.ToUnixTimeInMilliseconds().ToString());
                LastRequest.AssertContainsParameter("end", query.End.Value.ToUnixTimeInMilliseconds().ToString());
                LastRequest.AssertContainsParameter("direction", query.Direction.ToString().ToLower());
                LastRequest.AssertContainsParameter("limit", query.Limit.Value.ToString());
            }
Ejemplo n.º 11
0
        private async Task ThrottleRequestsAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine();
            var ratelimit   = TimeSpan.FromTicks(Math.Max(Ratelimit.Ticks, _minRatelimit.Ticks));
            var availableAt = LastRequest.Add(ratelimit);

            if (DateTime.UtcNow < availableAt)
            {
                var availableIn = availableAt.Subtract(DateTime.UtcNow);

                Console.WriteLine($"Delay for {availableIn} (until {availableAt}).");
                await Task.Delay(availableIn, cancellationToken);
            }

            LastRequest = DateTime.UtcNow;
        }
Ejemplo n.º 12
0
        internal Tuple <int, int, int, int> Pour()
        {
            if (BucketCount < 0)
            {
                BucketCount = 0;
            }
            DateTime Last = LastRequest;

            if (BucketCount > 0)
            {
                while (true)
                {
                    Last = Last.AddMilliseconds(RestoreRatePeriod);
                    if (Last > DateTime.Now)
                    {
                        break;
                    }
                    else
                    {
                        BucketCount -= RestoreRateCount;
                    }
                }
            }
            if (BucketCount < 0)
            {
                BucketCount = 0;
            }

            if (BucketCount >= MaximumRequestQuota)
            {
                LastRequest = LastRequest.AddMilliseconds(RestoreRatePeriod);
                while (LastRequest >= DateTime.Now)
                {
                    Thread.Sleep(100);
                }
            }
            if (BucketCount + 1 <= MaximumRequestQuota)
            {
                BucketCount += 1;
            }
            LastRequest = DateTime.Now;
            RequestsSent++;
            return(new Tuple <int, int, int, int>(BucketCount, MaximumRequestQuota, RestoreRateCount, RestoreRatePeriod));
        }
Ejemplo n.º 13
0
        public async Task ShouldSetCorrectHeaders()
        {
            var rest = GetRestClient();

            var query = new StatsRequestParams
            {
                Start     = Now.AddHours(-1),
                End       = Now,
                Direction = QueryDirection.Forwards,
                Limit     = 1000
            };

            await rest.StatsAsync(query);

            LastRequest.AssertContainsParameter("start", query.Start.Value.ToUnixTimeInMilliseconds().ToString());
            LastRequest.AssertContainsParameter("end", query.End.Value.ToUnixTimeInMilliseconds().ToString());
            LastRequest.AssertContainsParameter("direction", query.Direction.ToString().ToLower());
            LastRequest.AssertContainsParameter("limit", query.Limit.Value.ToString());
        }
Ejemplo n.º 14
0
        public async Task ShouldPassDirectionToRequestWithBackwardsAsDefault(QueryDirection?direction)
        {
            var query = new StatsRequestParams
            {
                Start = Now,
                End   = Now
            };

            if (direction.HasValue)
            {
                query.Direction = direction.Value;
            }

            await ExecuteStatsQuery(query);

            var expectedDirection = direction.GetValueOrDefault(QueryDirection.Backwards).ToString().ToLower();

            LastRequest.AssertContainsParameter("direction", expectedDirection);
        }
Ejemplo n.º 15
0
        public void UpdateMessages(RtspMessage request, RtspMessage response)
        {
            if (request != null && LastRequest != null)
            {
                LastRequest.IsPersistent = false;

                LastRequest.Dispose();
            }

            LastRequest = request;

            LastRequest.IsPersistent = true;

            if (LastResponse != null)
            {
                LastResponse.IsPersistent = false;

                LastResponse.Dispose();
            }

            LastResponse = response;

            LastResponse.IsPersistent = true;
        }
Ejemplo n.º 16
0
        internal void SetResults(string script = null)
        {
            if (ResultTable == null)
                return;

            if (script == null)
                script = Request.ChartScript.Script;

            FillGridView();

            if (Request.GroupResults)
            {
                //so the values don't get affected till next SetResults
                var filters = Request.Filters.Select(f => new FilterOption { ColumnName = f.Token.FullKey(), Value = f.Value, Operation = f.Operation }).ToList();
                var keyColunns = Request.Columns
                    .Zip(ResultTable.Columns, (t, c) => new { t.Token, Column = c })
                    .Where(a => !(a.Token.Token is AggregateToken)).ToArray();

                lastRequest = new LastRequest
                {
                    KeyColumns = Request.Columns.Iterate()
                    .Where(a => a.Value.ScriptColumn.IsGroupKey)
                    .Select(a => new KeyColumn { Position = a.Position, Token = a.Value.Token?.Token })
                    .ToList(),
                    Filters = Request.Filters.Where(a => !(a.Token is AggregateToken)).Select(f => new FilterOption
                    {
                        Token = f.Token,
                        Operation = f.Operation,
                        Value = f.Value,
                    }).ToList(),
                    GroupResults = Request.GroupResults,
                    GetFilter = rr => keyColunns.Select(t => GetTokenFilters(t.Token.Token, rr[t.Column])).ToList()
                };
            }
            else lastRequest = new LastRequest { GroupResults = false };

            lvResult.ItemsSource = ResultTable.Rows;
            if (ResultTable.Rows.Length > 0)
            {
                lvResult.SelectedIndex = 0;
                lvResult.ScrollIntoView(ResultTable.Rows.FirstEx());
            }

            lvResult.Background = Brushes.White;

            var jsonData = ChartUtils.DataJson(Request, ResultTable);

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);

            if (webBrowserLoaded)
                WebBroserInvoke(script, json);
            else
                webBrowser.LoadCompleted += (s, e) => WebBroserInvoke(script, json);
           
        }
Ejemplo n.º 17
0
        internal void SetResults(string script = null)
        {
            if (ResultTable == null)
            {
                return;
            }

            if (script == null)
            {
                script = Request.ChartScript.Script;
            }

            FillGridView();

            if (Request.GroupResults)
            {
                //so the values don't get affected till next SetResults
                var filters = Request.Filters.Select(f => new FilterOption {
                    ColumnName = f.Token.FullKey(), Value = f.Value, Operation = f.Operation
                }).ToList();
                var keyColunns = Request.Columns
                                 .Zip(ResultTable.Columns, (t, c) => new { t.Token, Column = c })
                                 .Where(a => !(a.Token.Token is AggregateToken)).ToArray();

                lastRequest = new LastRequest
                {
                    KeyColumns = Request.Columns.Iterate()
                                 .Where(a => a.Value.ScriptColumn.IsGroupKey)
                                 .Select(a => new KeyColumn {
                        Position = a.Position, Token = a.Value.Token?.Token
                    })
                                 .ToList(),
                    Filters = Request.Filters.Where(a => !(a.Token is AggregateToken)).Select(f => new FilterOption
                    {
                        Token     = f.Token,
                        Operation = f.Operation,
                        Value     = f.Value,
                    }).ToList(),
                    GroupResults = Request.GroupResults,
                    GetFilter    = rr => keyColunns.Select(t => GetTokenFilters(t.Token.Token, rr[t.Column])).ToList()
                };
            }
            else
            {
                lastRequest = new LastRequest {
                    GroupResults = false
                }
            };

            lvResult.ItemsSource = ResultTable.Rows;
            if (ResultTable.Rows.Length > 0)
            {
                lvResult.SelectedIndex = 0;
                lvResult.ScrollIntoView(ResultTable.Rows.FirstEx());
            }

            lvResult.Background = Brushes.White;

            var jsonData = ChartUtils.DataJson(Request, ResultTable);

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);

            if (webBrowserLoaded)
            {
                WebBroserInvoke(script, json);
            }
            else
            {
                webBrowser.LoadCompleted += (s, e) => WebBroserInvoke(script, json);
            }
        }
Ejemplo n.º 18
0
            public async Task WithOutLimit_ShouldUseDefaultOf100()
            {
                await _channel.HistoryAsync();

                LastRequest.AssertContainsParameter("limit", "100");
            }
Ejemplo n.º 19
0
            public async Task WithoutDirection_ShouldDefaultToBackwards()
            {
                await _channel.HistoryAsync();

                LastRequest.AssertContainsParameter("direction", QueryDirection.Backwards.ToString().ToLower());
            }
    public void _request(string endPoint, RequestData requestData)
    {
        requestData.timestamp  = PredictedServerTimestamp;
        requestData.version    = Version;
        requestData.versionKey = VersionKey;

        LastRequest             = new LastRequest();
        LastRequest.EndPoint    = endPoint;
        LastRequest.RequestData = requestData;

        Byte[] payload = Encoding.UTF8.GetBytes(JsonUtility.ToJson(requestData));

        if (localSendInvalidRequestData)
        {
            Array.Clear(payload, 0, payload.Length);
        }

        payload = _encryptionHelper.Encrypt(payload, this.nonce);

        string payloadBase64 = Convert.ToBase64String(payload);

        var postForm = new RawJsonForm();

        postForm.AddField("payloadBase64", payloadBase64);

        // signature
        Byte[] digest      = md5.ComputeHash(payload);                   // md5(payload);
        Byte[] nonceByte   = BitConverter.GetBytes(this.nonce);          // nonce to byte
        Byte[] signMessage = new Byte[digest.Length + nonceByte.Length]; // nonceByte + digest

        Array.Copy(nonceByte, signMessage, nonceByte.Length);
        Array.Copy(digest, 0, signMessage, nonceByte.Length, digest.Length);

        signMessage = _encryptionHelper.SignMessage(signMessage);
        string signedBase64 = Convert.ToBase64String(signMessage);

        if (localSendInvalidSignBase64)
        {
            signedBase64 = "1234";
        }

        // query
        Dictionary <string, string> queryDict = new Dictionary <string, string>();

        queryDict.Add("signedBase64", signedBase64);
        queryDict.Add("token", token);

        if (remoteTimeout)
        {
            queryDict.Add("remoteTimeout", "true");
        }

        if (remoteSendInvalidPayload)
        {
            queryDict.Add("remoteSendInvalidPayload", "true");
        }

        var query = this.getQuery(queryDict);

        // send request
        var url = $"{Host}{endPoint}?{query}";

        var nonceSent = nonce;

        HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Post, (originalRequest, response) =>
        {
            isSending = false;

            try
            {
                if (response != null && response.IsSuccess)
                {
                    var isEncrypted = false;
                    if (response.Headers.TryGetValue("content-encoding", out var isEncryptString))
                    {
                        if (isEncryptString.Count > 0 && isEncryptString[0] == "encrypted")
                        {
                            isEncrypted = true;
                        }
                    }

                    if (isEncrypted)
                    {
                        // decrypt
                        var decrypted = _encryptionHelper.Decrypt(response.Data, nonceSent);

                        // decompress
                        var memoryStream   = new MemoryStream(decrypted);
                        var toMemoryStream = new MemoryStream();
                        var gZipStream     = new GZipStream(memoryStream, CompressionMode.Decompress);
                        gZipStream.CopyTo(toMemoryStream);
                        memoryStream.Close();
                        var decompressed = toMemoryStream.ToArray();

                        var text = Encoding.UTF8.GetString(decompressed);

                        // Debug.Log( $"response Data: {text}." );

                        RespondData = JsonUtility.FromJson <RespondData>(text);
                    }
                    else
                    {
                        RespondData = JsonUtility.FromJson <RespondData>(response.DataAsText);
                    }

                    if (!string.IsNullOrEmpty(RespondData.token))
                    {
                        token = RespondData.token;
                    }

                    if (RespondData.user.userId > 0)
                    {
                        user = RespondData.user;
                    }

                    card  = RespondData.body.card;
                    cards = RespondData.body.cards;

                    serverTimestamp   = RespondData.timestamp;
                    receivedTimestamp = CurrentTimestamp;
                }
                else
                {
                    RespondData.errorCode = ErrorCode.Timeout;
                }
            }
            catch (Exception e)
            {
                RespondData.errorCode = ErrorCode.FailedToDecryptServerPayload;
            }
        });

        // request.ConnectTimeout = TimeSpan.FromSeconds( Timeout );
        request.Timeout = TimeSpan.FromSeconds(Timeout);
        request.SetForm(postForm);

        request.Send();

        isSending = true;

        nonce++;
    }