예제 #1
0
        public async Task <IAnalyticsResult <T> > AnalyticsQueryAsync <T>(string statement, AnalyticsOptions?options = default)
        {
            options ??= new AnalyticsOptions();
            options.TimeoutValue ??= _context.ClusterOptions.AnalyticsTimeout;

            ThrowIfNotBootstrapped();

            var query = new AnalyticsRequest(statement)
            {
                ClientContextId     = options.ClientContextIdValue,
                NamedParameters     = options.NamedParameters,
                PositionalArguments = options.PositionalParameters,
                Timeout             = options.TimeoutValue.Value
            };

            query.Priority(options.PriorityValue);
            query.ScanConsistency(options.ScanConsistencyValue);

            async Task <IAnalyticsResult <T> > Func()
            {
                var client1  = LazyAnalyticsClient.Value;
                var query1   = query;
                var options1 = options ?? new AnalyticsOptions();

                return(await client1.QueryAsync <T>(query1, options1.Token).ConfigureAwait(false));
            }

            return(await _retryOrchestrator.RetryAsync(Func, query).ConfigureAwait(false));
        }
예제 #2
0
        public void Client_sets_AnalyticsPriority_Header(bool priority)
        {
            var configuration = new Configuration().WithServers("http://localhost");

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request =>
            {
                if (priority)
                {
                    Assert.True(request.Headers.TryGetValues(AnalyticsClient.AnalyticsPriorityHeaderName, out var values));
                    Assert.Equal("-1", values.First());
                }
                else
                {
                    Assert.False(request.Headers.TryGetValues(AnalyticsClient.AnalyticsPriorityHeaderName, out _));
                }

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{}")
                });
            })
                );

            var client = new AnalyticsClient(httpClient, new JsonDataMapper(new DefaultSerializer()), configuration);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");

            queryRequest.Priority(priority);

            client.Query <dynamic>(queryRequest);
        }
예제 #3
0
        public async Task <IAnalyticsResult <T> > AnalyticsQueryAsync <T>(string statement, AnalyticsOptions?options = default)
        {
            options ??= new AnalyticsOptions();

            if (!options.TimeoutValue.HasValue)
            {
                options.Timeout(_context.ClusterOptions.AnalyticsTimeout);
            }

            if (string.IsNullOrWhiteSpace(options.ClientContextIdValue))
            {
                options.ClientContextId(Guid.NewGuid().ToString());
            }

            ThrowIfNotBootstrapped();

            if (options.RetryStrategyValue == null)
            {
                options.RetryStrategy(_retryStrategy);
            }

            async Task <IAnalyticsResult <T> > Func()
            {
                var client1  = LazyAnalyticsClient.Value;
                var options1 = options;

                return(await client1.QueryAsync <T>(statement, options1).ConfigureAwait(false));
            }

            //for measuring latencies
            var recorder = _meter.ValueRecorder(OuterRequestSpans.ServiceSpan.AnalyticsQuery);

            return(await _retryOrchestrator.RetryAsync(Func, AnalyticsRequest.Create(statement, recorder, options)).ConfigureAwait(false));
        }
        public void TestAnalyticsModel()
        {
            RequestSettings settings = new RequestSettings("Unittests", this.userName, this.passWord);

            AnalyticsRequest request = new AnalyticsRequest(settings);

            Feed <Account> accounts = request.GetAccounts();

            foreach (Account a in accounts.Entries)
            {
                Assert.IsNotNull(a.AccountId);
                Assert.IsNotNull(a.ProfileId);
                Assert.IsNotNull(a.WebPropertyId);
                if (this.accountId == null)
                {
                    this.accountId = a.TableId;
                }
            }


            DataQuery q = new DataQuery(this.accountId, DateTime.Now.AddDays(-14), DateTime.Now.AddDays(-2), "ga:pageviews", "ga:pageTitle", "ga:pageviews");


            Dataset set = request.Get(q);

            foreach (Data d in set.Entries)
            {
                Assert.IsNotNull(d.Id);
                Assert.IsNotNull(d.Metrics);
                Assert.IsNotNull(d.Dimensions);
            }
        }
예제 #5
0
        public async Task QueryAsync_Sets_LastActivity()
        {
            var options = new ClusterOptions().WithServers("http://localhost");
            var context = new ClusterContext(null, options);

            context.AddNode(new ClusterNode(new ClusterContext(null, new ClusterOptions()))
            {
                AnalyticsUri = new Uri("http://localhost:8094/query"),
                EndPoint     = new IPEndPoint(IPAddress.Loopback, 8091),
                NodesAdapter = new NodeAdapter {
                    Analytics = 8094
                }
            });

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{}")
            })
                );

            var client = new AnalyticsClient(httpClient, new JsonDataMapper(new DefaultSerializer()), context);

            Assert.Null(client.LastActivity);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");
            await client.QueryAsync <dynamic>(queryRequest, CancellationToken.None).ConfigureAwait(false);

            Assert.NotNull(client.LastActivity);
        }
예제 #6
0
        public void Can_set_statement()
        {
            // set statement using constructor
            var request = new AnalyticsRequest(Statement);

            var formValues = request.GetFormValues();

            Assert.Equal(Statement, formValues["statement"]);

            var json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );

            Assert.Equal(Statement, json.statement.Value);

            // set statement using method
            const string statement = "SELECT 1 FROM `datset`;";

            request.WithStatement(statement);

            formValues = request.GetFormValues();
            Assert.Equal(statement, formValues["statement"]);

            json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );
            Assert.Equal(statement, json.statement.Value);
        }
        public async Task QueryAsync_Sets_LastActivity()
        {
            var httpClient = new CouchbaseHttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{}")
            })
                );

            var mockServiceUriProvider = new Mock <IServiceUriProvider>();

            mockServiceUriProvider
            .Setup(m => m.GetRandomAnalyticsUri())
            .Returns(new Uri("http://localhost:8096"));

            var serializer = new DefaultSerializer();
            var client     = new AnalyticsClient(httpClient, mockServiceUriProvider.Object, serializer,
                                                 new Mock <ILogger <AnalyticsClient> >().Object, NoopRequestTracer.Instance);

            Assert.Null(client.LastActivity);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");
            await client.QueryAsync <dynamic>(queryRequest, CancellationToken.None).ConfigureAwait(false);

            Assert.NotNull(client.LastActivity);
        }
        public void Can_add_credentials(string username, bool isAdmin, string expectedUser)
        {
            const string password = "******";
            var          request  = new AnalyticsRequest(Statement);

            var formValues = request.GetFormValues();

            Assert.False(formValues.ContainsKey("creds"));

            request.AddCredentials(username, password, isAdmin);
            formValues = request.GetFormValues();

            var creds = (List <dynamic>)formValues["creds"];

            Assert.Equal(1, creds.Count);

            var expected = $"{{ user = {expectedUser}, pass = {password} }}";

            foreach (var cred in creds)
            {
                Assert.Equal(expected, cred.ToString());
            }

            var json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );

            Assert.Equal(1, json.creds.Count);
            Assert.Equal($"{{\"user\":\"{expectedUser}\",\"pass\":\"password\"}}", json.creds[0].ToString(Formatting.None));
        }
예제 #9
0
        public void Client_sets_AnalyticsPriority_Header(bool priority)
        {
            var context = ContextFactory.GetCouchbaseContext();

            context.AnalyticsUris.Add(new FailureCountingUri("http://localhost"));

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request =>
            {
                if (priority)
                {
                    Assert.IsTrue(request.Headers.TryGetValues(AnalyticsClient.AnalyticsPriorityHeaderName, out var values));
                    Assert.AreEqual("-1", values.First());
                }
                else
                {
                    Assert.IsFalse(request.Headers.TryGetValues(AnalyticsClient.AnalyticsPriorityHeaderName, out _));
                }

                return(new HttpResponseMessage(HttpStatusCode.OK));
            })
                );

            var client = new AnalyticsClient(httpClient, new JsonDataMapper(context.ClientConfig), context);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");

            queryRequest.Priority(priority);

            client.Query <dynamic>(queryRequest);
        }
예제 #10
0
        public void When_deferred_is_true_query_result_is_DeferredAnalyticsResult()
        {
            var resultJson = JsonConvert.SerializeObject(new
            {
                status = "Success",
                handle = "handle"
            });

            var context = ContextFactory.GetCouchbaseContext();

            context.AnalyticsUris.Add(new FailureCountingUri("http://localhost"));

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(resultJson)
            })
                );

            var client = new AnalyticsClient(httpClient,
                                             new JsonDataMapper(context.ClientConfig),
                                             context);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");
            var result       = client.Query <dynamic>(queryRequest);

            Assert.IsInstanceOf <AnalyticsDeferredResultHandle <dynamic> >(result.Handle);
            Assert.AreEqual(QueryStatus.Success, result.Status);

            var deferredResult = (AnalyticsDeferredResultHandle <dynamic>)result.Handle;

            Assert.AreEqual("handle", deferredResult.HandleUri);
        }
        public void Query_Sets_LastActivity()
        {
            var configuration = new ClusterOptions().WithServers("http://localhost");

            configuration.GlobalNodes.Add(new ClusterNode {
                AnalyticsUri = new Uri("http://localhost:8094/query")
            });

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{}")
            })
                );

            var client = new AnalyticsClient(httpClient, new JsonDataMapper(new DefaultSerializer()), configuration);

            Assert.Null(client.LastActivity);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");

            client.Query <dynamic>(queryRequest);

            Assert.NotNull(client.LastActivity);
        }
예제 #12
0
        public Task <IAnalyticsResult <T> > AnalyticsQueryAsync <T>(string statement, AnalyticsOptions options = default)
        {
            if (options == default)
            {
                options = new AnalyticsOptions();
            }

            var query = new AnalyticsRequest(statement);

            query.ClientContextId(options.ClientContextId);
            query.Pretty(options.Pretty);
            query.IncludeMetrics(options.IncludeMetrics);
            query.NamedParameters     = options.NamedParameters;
            query.PositionalArguments = options.PositionalParameters;

            if (options.Timeout.HasValue)
            {
                query.Timeout(options.Timeout.Value);
            }

            query.Priority(options.Priority);
            query.Deferred(options.Deferred);

            query.ConfigureLifespan(30); //TODO: use configuration.AnalyticsTimeout

            if (_analyticsClient == null)
            {
                _analyticsClient = new AnalyticsClient(_configuration);
            }
            return(_analyticsClient.QueryAsync <T>(query, options.CancellationToken));
        }
        public void When_deferred_is_true_query_result_is_DeferredAnalyticsResult()
        {
            var resultJson = JsonConvert.SerializeObject(new
            {
                status = "Success",
                handle = "handle"
            });

            var configuration = new ClusterOptions().WithServers("http://localhost");

            configuration.GlobalNodes.Add(new ClusterNode {
                AnalyticsUri = new Uri("http://localhost:8094/query")
            });

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(resultJson)
            })
                );

            var client = new AnalyticsClient(httpClient, new JsonDataMapper(new DefaultSerializer()), configuration);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");
            var result       = client.Query <dynamic>(queryRequest);

            Assert.IsType <AnalyticsDeferredResultHandle <dynamic> >(result.Handle);
            Assert.Equal(QueryStatus.Success, result.MetaData.Status);

            var deferredResult = (AnalyticsDeferredResultHandle <dynamic>)result.Handle;

            Assert.Equal("handle", deferredResult.HandleUri);
        }
예제 #14
0
        public void Can_execute_deferred_query()
        {
            const string statement = "SELECT \"hello\" as greeting;";

            var token = default(CancellationToken);

            Assert.AreEqual(CancellationToken.None, token);

            var query = new AnalyticsRequest(statement)
                        .Deferred(true);

            var result = _bucket.Query <TestRequest>(query);

            Assert.IsTrue(result.Success);
            Assert.AreEqual(QueryStatus.Running, result.Status);

            Assert.IsNotNull(result.Handle);

            var status = result.Handle.GetStatus();

            Assert.AreEqual(QueryStatus.Success, status);

            var rows = result.Handle.GetRows();

            Assert.IsNotEmpty(rows);
            Assert.AreEqual("hello", rows.First().Greeting);
        }
예제 #15
0
        public async Task <IAnalyticsResult <T> > AnalyticsQueryAsync <T>(string statement, AnalyticsOptions options = default)
        {
            await EnsureBootstrapped();

            if (options == default)
            {
                options = new AnalyticsOptions();
            }

            var query = new AnalyticsRequest(statement);

            query.ClientContextId(options.ClientContextId);
            query.Pretty(options.Pretty);
            query.IncludeMetrics(options.IncludeMetrics);
            query.NamedParameters     = options.NamedParameters;
            query.PositionalArguments = options.PositionalParameters;

            if (options.Timeout.HasValue)
            {
                query.Timeout(options.Timeout.Value);
            }

            query.Priority(options.Priority);
            query.Deferred(options.Deferred);

            query.ConfigureLifespan(30); //TODO: use clusterOptions.AnalyticsTimeout

            return(await _lazyAnalyticsClient.Value.QueryAsync <T>(query, options.CancellationToken));
        }
        public void When_parameters_empty_GetParametersFromJson_returns_empty_object()
        {
            var request = new AnalyticsRequest(Statement);

            var json = request.GetParametersAsJson();

            Assert.Equal("{}", json);
        }
 public static AnalyticsEventQuery ToQuery(this AnalyticsRequest request)
 {
     return(new AnalyticsEventQuery()
     {
         OrganisationId = request.OrganisationId,
         StartDateTime = request.StartDate,
         EndDateTime = request.EndDate
     });
 }
        public void Can_fetch_JSON_from_PositionalParameters()
        {
            var request = new AnalyticsRequest(Statement);

            request.AddPositionalParameter("thevalue");

            var json = request.GetParametersAsJson();

            Assert.Equal("[\"thevalue\"]", json);
        }
        public void Can_fetch_JSON_from_NamedParameters()
        {
            var request = new AnalyticsRequest(Statement);

            request.AddNamedParameter("theykey", "thevalue");

            var json = request.GetParametersAsJson();

            Assert.Equal("{\"theykey\":\"thevalue\"}", json);
        }
예제 #20
0
        public async Task Test_Ingest()
        {
            const string statement = "SELECT \"hello\" as greeting;";

            var query = new AnalyticsRequest(statement);

            var result = await _bucket.IngestAsync <dynamic>(query, new IngestOptions()).ConfigureAwait(false);

            Assert.True(result.Count > 0);
        }
예제 #21
0
        public async Task Execute_Query_Async()
        {
            const string statement = "SELECT \"hello\" as greeting;";

            var query = new AnalyticsRequest(statement);

            var result = await _bucket.QueryAsync <TestRequest>(query, CancellationToken.None);

            Assert.IsTrue(result.Success);
            Assert.AreEqual("hello", result.Rows.First().Greeting);
        }
예제 #22
0
        public void Request_ID_changes_on_each_request()
        {
            var request          = new AnalyticsRequest(Statement);
            var formValues       = request.GetFormValues();
            var clientContextId1 = formValues["client_context_id"].ToString();

            formValues = request.GetFormValues(); // re-trigger as if going to re-submited the query
            var clientContextId2 = formValues["client_context_id"].ToString();

            Assert.NotEqual(clientContextId1, clientContextId2);
        }
예제 #23
0
        public void Execute_Query()
        {
            const string statement = "SELECT \"hello\" as greeting;";

            var query = new AnalyticsRequest(statement);

            var result = _bucket.Query <TestRequest>(query);

            Assert.IsTrue(result.Success);
            Assert.AreEqual("hello", result.Rows.First().Greeting);
        }
예제 #24
0
        public void Request_auto_generates_context_and_request_Ids()
        {
            var request = new AnalyticsRequest(Statement);

            request.WithClientContextId(Guid.NewGuid().ToString());

            var formValues = request.GetFormValues();
            var requestId  = formValues["client_context_id"].ToString();

            Assert.NotEmpty(requestId);
        }
        public void Pretty_default_is_false()
        {
            var request = new AnalyticsRequest(Statement);

            var formValues = request.GetFormValues();

            Assert.Equal(false, formValues["pretty"]);

            var json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );

            Assert.Equal(false, json.pretty.Value);
        }
예제 #26
0
        public void Can_set_client_context_id()
        {
            var request = new AnalyticsRequest(Statement);

            request.WithClientContextId("testing");
            request.WithClientContextId(Guid.NewGuid().ToString());

            var formValues = request.GetFormValues();
            var contextId  = formValues["client_context_id"].ToString();

            Assert.NotEmpty(contextId);

            Assert.True(Guid.TryParse(contextId, out Guid result));
        }
예제 #27
0
        static void Main(string[] args)
        {
            var email = inputReader.GetInput("Enter your email: ");
            var password = inputReader.GetPassword("Your Password: "******"linq2ga", email, password);
            var request = new AnalyticsRequest(settings);

            messenger.Send("Please wait. Loading your Accounts... ");
            var accounts = request.GetAccounts();
            foreach (var account in accounts.Entries)
                messenger.Send(account.AccountName);

            inputReader.GetInput("... press enter to continue ...");
        }
        public void Request_auto_generates_context_and_request_Ids()
        {
            var request = new AnalyticsRequest(Statement);

            var formValues = request.GetFormValues();
            var requestId  = formValues["client_context_id"].ToString();

            Assert.NotEmpty(requestId);

            var parts = requestId.Split(new [] { "::" }, StringSplitOptions.RemoveEmptyEntries);

            Assert.Equal(2, parts.Length);
            Assert.True(Guid.TryParse(parts[0], out _));
            Assert.True(Guid.TryParse(parts[1], out _));
        }
예제 #29
0
        public void Statement_is_cleaned(string statement)
        {
            const string expected = "SELECT 1;";
            var          request  = new AnalyticsRequest(statement);

            var formValues = request.GetFormValues();

            Assert.Equal(expected, formValues["statement"]);

            var json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );

            Assert.Equal(expected, json.statement.Value);
        }
예제 #30
0
        public void Can_set_priority()
        {
            var request = new AnalyticsRequest(Statement);

            Assert.Equal(0, request.PriorityValue);

            request.Priority(true);
            Assert.Equal(-1, request.PriorityValue);

            request.Priority(false);
            Assert.Equal(0, request.PriorityValue);

            request.Priority(5);
            Assert.Equal(5, request.PriorityValue);
        }
        public void Can_set_pretty_parameter()
        {
            var request = new AnalyticsRequest(Statement);

            request.Pretty(true);

            var formValues = request.GetFormValues();

            Assert.Equal(true, formValues["pretty"]);

            var json = JsonConvert.DeserializeObject <dynamic>(
                request.GetFormValuesAsJson()
                );

            Assert.Equal(true, json.pretty.Value);
        }
예제 #32
0
        public void TestAnalyticsModel()
        {
            RequestSettings settings = new RequestSettings("Unittests", this.userName, this.passWord);

            AnalyticsRequest request = new AnalyticsRequest(settings);

            Feed<Account> accounts = request.GetAccounts();

            foreach (Account a in accounts.Entries)
            {
                Assert.IsNotNull(a.AccountId);
                Assert.IsNotNull(a.ProfileId);
                Assert.IsNotNull(a.WebPropertyId);
                if (this.accountId == null)
                    this.accountId = a.TableId;
            }
            

            DataQuery q = new DataQuery(this.accountId, DateTime.Now.AddDays(-14), DateTime.Now.AddDays(-2), "ga:pageviews", "ga:pageTitle", "ga:pageviews");


            Dataset set = request.Get(q);

            foreach (Data d in set.Entries)
            {
                Assert.IsNotNull(d.Id);
                Assert.IsNotNull(d.Metrics);
                Assert.IsNotNull(d.Dimensions);
            }
        }