internal static string ToUriString(ViewQuery viewQuery, ISerializer serializer = null) { if (viewQuery.ViewName.HasNoValue() || (viewQuery.DesignDocumentName.HasNoValue() && !SpecialViewNames.Any(n => n == viewQuery.ViewName))) { return(null); } serializer = serializer ?? new NewtonsoftSerializer(); var uri = new StringBuilder(); if (!String.IsNullOrEmpty(viewQuery.DesignDocumentName)) { uri.Append("_design/").Append(viewQuery.DesignDocumentName).Append("/_view/"); } uri.Append(viewQuery.ViewName); var queryString = Serializer.ToQueryString(viewQuery, serializer); if (queryString.Length > 0) { uri.Append("?").Append(queryString); } return(uri.ToString()); }
public void When_Poco_Is_Supplied_Map_Results_To_It() { var query = new ViewQuery(). From("beer_ext", "all_beers"). Bucket("beer-sample"). Limit(10). Development(false); var client = new ViewClient(new HttpClient(), new JsonDataMapper(new ClientConfiguration()), new BucketConfig { Name = "beer-sample" }, new ClientConfiguration()); var result = client.Execute <Beer>(query); foreach (var viewRow in result.Rows) { Assert.IsNotNull(viewRow.Id); } Console.WriteLine(result.Error); Assert.IsNotNull(result.Rows); Assert.IsTrue(result.Success); Assert.AreEqual(result.Rows.Count(), result.Values.Count()); }
/// <summary>Loads view request result from provided <see cref="TextReader"/>.</summary> public static IViewQueryResult Parse(TextReader textReader, ViewQuery viewQuery) { var response = ParseRawResponse(textReader); var totalRows = GetTotalRows(response); var offset = GetOffset(response); var rawRows = GetRawRows(response); var rows = ( from rawRow in rawRows let viewKey = rawRow.TryGetValue("key") let documentId = rawRow.GetPrimitiveProperty <string>("id") let value = rawRow.TryGetValue("value") let documentJsonObject = rawRow.TryGetValue("doc") as JsonObject let document = documentJsonObject == null ? null : new Document(documentJsonObject) select new ViewResultRow(viewKey, value, documentId, document) ).ToArray(); try { return(new ViewQueryResult(viewQuery, rows, totalRows, offset)); } catch (ArgumentOutOfRangeException e) { throw new ParseException(e); } }
/// <summary>Loads view request result from provided <see cref="TextReader"/>.</summary> public static IViewQueryResult Parse(TextReader textReader, ViewQuery viewQuery) { var response = ParseRawResponse(textReader); var totalRows = GetTotalRows(response); var offset = GetOffset(response); var rawRows = GetRawRows(response); var rows = ( from rawRow in rawRows let viewKey = rawRow.TryGetValue("key") let documentId = rawRow.GetPrimitiveProperty<string>("id") let value = rawRow.TryGetValue("value") let documentJsonObject = rawRow.TryGetValue("doc") as JsonObject let document = documentJsonObject == null ? null : new Document(documentJsonObject) select new ViewResultRow(viewKey, value, documentId, document) ).ToArray(); try { return new ViewQueryResult(viewQuery, rows, totalRows, offset); } catch (ArgumentOutOfRangeException e) { throw new ParseException(e); } }
public void ThrowViewNotFoundExceptionIfNedded(ViewQuery query) { if (statusCode == HttpStatusCode.NotFound && reason == MissingNamedView) { throw new ViewNotFoundException(query); } }
public async Task Test_Views(string file, HttpStatusCode httpStatusCode, Type errorType) { var retryOrchestrator = CreateRetryOrchestrator(); using (var response = ResourceHelper.ReadResourceAsStream(@"Documents\Views\" + file)) { var buffer = new byte[response.Length]; response.Read(buffer, 0, buffer.Length); var responses = GetResponses(20, buffer, httpStatusCode); var client = MockedHttpClients.ViewClient(responses); using var cts = new CancellationTokenSource(); cts.CancelAfter(1000); var viewQuery = new ViewQuery("default", "beers", "brewery_beers") { Token = cts.Token }; async Task <IViewResult <dynamic, dynamic> > Func() { var client1 = client; return(await client1.ExecuteAsync <dynamic, dynamic>(viewQuery)); } await AssertThrowsIfExpectedAsync(errorType, () => retryOrchestrator.RetryAsync(Func, viewQuery)); } }
public void When_Row_Is_Dynamic_Query_By_Key_Succeeds() { var query = new ViewQuery(). From("beer_ext", "all_beers"). Bucket("beer-sample"). Limit(1). Development(false);; var client = new ViewClient(new HttpClient(), new JsonDataMapper(new ClientConfiguration()), new BucketConfig { Name = "beer-sample" }, new ClientConfiguration()); var result = client.Execute <Beer>(query); var query2 = new ViewQuery(). From("beer_ext", "all_beers"). Bucket("beer-sample").Key(result.Rows.First().Id); var result2 = client.Execute <Beer>(query2); Assert.AreEqual(result.Rows.First().Id, result2.Rows.First().Id); }
public void MaxViewRetries_IsOne_RequestIsNotRetried() { var controller = new Mock <IClusterController>(); controller.Setup(x => x.Configuration).Returns(new ClientConfiguration { MaxViewRetries = 0 }); var server = new Mock <IServer>(); server.Setup(x => x.Send <dynamic>(It.IsAny <IViewQueryable>())).Returns( new ViewResult <dynamic> { StatusCode = HttpStatusCode.RequestTimeout, Success = false }); server.Setup(x => x.EndPoint).Returns(new IPEndPoint(IPAddress.Loopback, 8091)); var configInfo = new Mock <IConfigInfo>(); configInfo.Setup(x => x.IsViewCapable).Returns(true); configInfo.Setup(x => x.GetViewNode()).Returns(server.Object); configInfo.Setup(x => x.ClientConfig).Returns(controller.Object.Configuration); var pending = new ConcurrentDictionary <uint, IOperation>(); var executor = new CouchbaseRequestExecuter(controller.Object, configInfo.Object, "default", pending); //arrange var query = new ViewQuery(). From("beer", "brewery_beers"). Bucket("beer-sample"); var result = executor.SendWithRetry <dynamic>(query); Assert.AreEqual(0, query.RetryAttempts); Assert.AreEqual(false, result.CannotRetry()); }
public async Task ViewClient_Submits_ViewQuery_Using_Post() { var keys = Enumerable.Range(1, 10).Select(i => $"key-{i}").ToList(); var expectedJson = JsonConvert.SerializeObject(new { keys }, Formatting.None); var handler = FakeHttpMessageHandler.Create(request => { // verify request was a post Assert.Equal(HttpMethod.Post, request.Method); // get the post body and verify content var content = request.Content.ReadAsStringAsync().Result; Assert.Equal(expectedJson, content); // return empty json response return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{ }") }); }); var httpClient = new CouchbaseHttpClient(handler); var serializer = new DefaultSerializer(); var queryClient = new ViewClient(httpClient, serializer, new Mock <ILogger <ViewClient> >().Object, new Mock <IRedactor>().Object); var query = new ViewQuery("bucket-name", "http://localhost"); query.Keys(keys); await queryClient.ExecuteAsync <dynamic, dynamic>(query).ConfigureAwait(false); }
public void Test_View_Certificate_Authentication() { var config = TestConfiguration.GetConfiguration("basic"); config.UseSsl = true; ClientConfiguration.IgnoreRemoteCertificateNameMismatch = true; //ignore for now config.EnableDeadServiceUriPing = true; //temp must fix config.EnableCertificateAuthentication = true; config.CertificateFactory = CertificateFactory.GetCertificatesByPathAndPassword( new PathAndPasswordOptions { Path = TestContext.CurrentContext.TestDirectory + "\\client.pfx", Password = "******" }); using (var cluster = new Cluster(config)) { cluster.Authenticate(new CertAuthenticator()); var bucket = cluster.OpenBucket(); var viewQuery = new ViewQuery("default", "test", "test"); var viewResult = bucket.Query <dynamic>(viewQuery); Assert.True(viewResult.Success); } }
public ViewsFixture() { Artists = TestData.Artists.CreateArtists(10); _client = IntegrationTestsRuntime.CreateClient(); var bulk = new BulkCommand(); bulk.Include(Artists.Select(i => _client.Entities.Serializer.Serialize(i)).ToArray()); var bulkResponse = _client.Documents.BulkAsync(bulk); foreach (var row in bulkResponse.Result.Rows) { var artist = Artists.Single(i => i.ArtistId == row.Id); _client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev); } _client.Documents.PostAsync(TestData.Views.Artists).Wait(); var touchView1 = new ViewQuery(TestData.Views.ArtistsAlbumsViewId).Configure(q => q.Stale(Stale.UpdateAfter)); var touchView2 = new ViewQuery(TestData.Views.ArtistsNameNoValueViewId).Configure(q => q.Stale(Stale.UpdateAfter)); _client.Views.RunQueryAsync(touchView1).Wait(); _client.Views.RunQueryAsync(touchView2).Wait(); }
public void When_Row_Is_Dynamic_Query_By_Key_Succeeds() { //arrange var query = new ViewQuery(). From("beer_ext", "all_beers"). Bucket("beer-sample"). Limit(1). Development(false). BaseUri(_baseUri); var client = GetViewClient("beer-sample"); //act var result = client.Execute <Beer>(query); var query2 = new ViewQuery(). From("beer_ext", "all_beers"). Bucket("beer-sample"). Key(result.Rows.First().Id). BaseUri(_baseUri); var result2 = client.Execute <Beer>(query2); //assert Assert.AreEqual(result.Rows.First().Id, result2.Rows.First().Id); }
internal static bool TryParse(string uriString, out ViewQuery viewQuery) { Uri uri; viewQuery = null; return(Uri.TryCreate(uriString, UriKind.Relative, out uri) && TryParse(uri, out viewQuery)); }
public void ViewClient_Submits_ViewQuery_Using_Post() { var keys = Enumerable.Range(1, 10).Select(i => $"key-{i}").ToList(); var expectedJson = JsonConvert.SerializeObject(new { keys }, Formatting.None); var handler = FakeHttpMessageHandler.Create(request => { // verify request was a post Assert.AreEqual(HttpMethod.Post, request.Method); // get the post body and verify content var content = request.Content.ReadAsStringAsync().Result; Assert.AreEqual(expectedJson, content); // return empty json response return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{ }") }); }); var httpClient = new HttpClient(handler); var queryClient = new ViewClient(httpClient, new JsonDataMapper(new DefaultSerializer())); var query = new ViewQuery("bucket-name", "http://localhost"); query.Keys(keys); var result = queryClient.Execute <dynamic>(query); Assert.IsTrue(result.Success); }
/* Função para demonstrar o uso do */ static void MapReduce() { Console.WriteLine("Map/Reduce"); Console.WriteLine(""); ClientConfiguration config = new ClientConfiguration() { Servers = new List <Uri>() { new Uri("http://localhost:8091") } }; config.SetAuthenticator(new PasswordAuthenticator("test", "123456")); using (Cluster cluster = new Cluster(config)) using (IBucket bucket = cluster.OpenBucket("viajanet")) { IViewQuery query = new ViewQuery().From("clients", "clientCountNavigation").GroupLevel(2); IViewResult <dynamic> clientNavigation = bucket.Query <dynamic>(query); string userToken = ""; foreach (var client in clientNavigation.Rows) { if (client.Key[0] != userToken) { Console.WriteLine("Client {0}", client.Key[0]); userToken = client.Key[0]; } Console.WriteLine(" Function: {0} -> Count: {1}", client.Key[1], client.Value); } } }
public void When_Query_Is_Valid_ViewQuery_Succeeds() { var bucket = new Mock <IBucket>(); bucket.Setup(x => x.Query <Beer>(It.IsAny <IViewQuery>())) .Returns(() => new FakeViewResult <Beer> { Success = true, Rows = new List <ViewRow <Beer> > { new ViewRow <Beer> { Id = "beer1", Key = "beer1", Value = new Beer() }, new ViewRow <Beer> { Id = "beer1", Key = "beer1", Value = new Beer() } } }); var dao = new DataAccessObject <Beer>(bucket.Object); var query = new ViewQuery() .Bucket("beer-sample") .DesignDoc("beer") .View("brewery_beers"); var result = dao.Select(query); Assert.AreEqual(2, result.Count()); }
public void ShouldQueryCochApiWithSameQueryObject() { ViewQuery sendQuery = null; var dbApiMock = new Mock <IDatabaseApi>(MockBehavior.Loose); dbApiMock .Setup(ca => ca.Query(It.IsAny <ViewQuery>())) .Returns( (ViewQuery query) => { sendQuery = query; return(new ViewQueryResult( query, new[] { new ViewResultRow( Entity.StandardDocId.ToJsonFragment(), new { rev = Entity.StandardRevision }.ToJsonFragment(), Entity.StandardDocId, Entity.CreateDocWithRevision() ) }, totalCount: 1, offset: 0).ToTask <IViewQueryResult>()); }); var session = new CouchSession(Default.Settings, Mock.Of <ICouchApi>(c => c.Db("testdb") == dbApiMock.Object)); var viewQuery = new ViewQuery { ViewName = "_all_docs", IncludeDocs = true }; session.Synchronously.Query <Entity>(viewQuery); Assert.Same(sendQuery, viewQuery); }
public void ShouldNotThrowAtAnyInput(string input) { ViewQuery viewQuery = null; Assert.DoesNotThrow(() => { viewQuery = ConvertFromString(input); }); Assert.Null(viewQuery); }
public void When_Query_Is_Not_Valid_ViewQuery_Throws_ViewRequestException() { var bucket = new Mock <IBucket>(); bucket.Setup(x => x.Query <Beer>(It.IsAny <IViewQuery>())) .Returns(() => new FakeViewResult <Beer> { Success = false, Rows = new List <ViewRow <Beer> >(), StatusCode = HttpStatusCode.InternalServerError, Error = "View was not found", Message = "View was not found" }); var dao = new DataAccessObject <Beer>(bucket.Object); var query = new ViewQuery() .Bucket("beer-sample") .DesignDoc("beer") .View("brewery-beers"); var exception = Assert.Throws <ViewRequestException>(() => dao.Select(query)); Assert.AreEqual(HttpStatusCode.InternalServerError, exception.StatusCode); Assert.AreEqual("View was not found", exception.Message); }
public void Test_ExecuteAsync() { var query = new ViewQuery(). From("docs", "all_docs"). Bucket("default"). BaseUri(_baseUri); var client = new ViewClient(new HttpClient(), new JsonDataMapper(new ClientConfiguration()), new BucketConfig { Name = "beer-sample" }, new ClientConfiguration()); int n = 10000; var options = new ParallelOptions { MaxDegreeOfParallelism = 4 }; Parallel.For(0, n, options, async i => { var result = await client.ExecuteAsync <dynamic>(query); Console.WriteLine("{0} {1} {2}", i, result.Success, result.Message); }); }
public Task <IViewQueryResult> Query(ViewQuery query) { return(Task.Factory.StartNew(() => { Thread.Sleep(50); //preventing returning already done task return Mock.Of <IViewQueryResult>(r => r.Count == 0 && r.Rows == new ViewResultRow[0]); })); }
public string Couchbase_ViewQuery() { var bucket = _connection.Bucket; var viewQuery = new ViewQuery().Limit(10); var result = bucket.Query <dynamic>(viewQuery); return(result.TotalRows.ToString()); }
public async Task <string> Couchbase_ViewQueryAsync() { var bucket = _connection.Bucket; var viewQuery = new ViewQuery().Limit(10); var result = await bucket.QueryAsync <dynamic>(viewQuery); return(result.TotalRows.ToString()); }
public void When_Query_Called_On_Memcached_Bucket_With_ViewQuery_NotSupportedException_Is_Thrown() { using (var bucket = _cluster.OpenBucket("memcached")) { var query = new ViewQuery(); bucket.Query <dynamic>(query); } }
public void Can_Set_IsStreaming() { var query = new ViewQuery(); Assert.IsFalse(query.IsStreaming); query.UseStreaming(true); Assert.IsTrue(query.IsStreaming); }
public static ParaEntityList <View> GetAccountViewList(long accountId) { var viewQuery = new ViewQuery() { RetrieveAllRecords = true }; return(Service.GetList <Account, View>(viewQuery)); }
public void When_Key_is_specified_using_entities_Then_matching_row_is_returned() { var artist = Artists[2]; var query = new ViewQuery(TestData.Views.ArtistsAlbumsViewId).Configure(cfg => cfg.Key(artist.Name)); var response = SUT.RunQueryAsync <Album[]>(query).Result; response.Should().BeSuccessfulGet(new[] { artist.Albums }); }
public void When_Key_is_specified_using_json_array_Then_matching_row_is_returned() { var artist = Artists[2]; var query = new ViewQuery(TestData.Views.ArtistsAlbumsViewId).Configure(cfg => cfg.Key(artist.Name)); var response = SUT.RunQueryAsync <string[]>(query).Result; response.Should().BeSuccessfulGet(new[] { artist.Albums.Select(i => Client.Serializer.Serialize(i)).ToArray() }); }
internal static IEnumerable <KeyValuePair <string, string> > ToParameters(this ViewQuery query) { var builder = new ParameterBuilder(); builder.Add("partialName", query?.PartialName); builder.Add("dataSetName", query?.DataSetName); builder.Add(query?.Page); return(builder.GetParameters()); }
public void When_Skipping_2_of_10_using_entities_Then_8_rows_are_returned() { var artists = Artists.Skip(2); var query = new ViewQuery(TestData.Views.ArtistsAlbumsViewId).Configure(cfg => cfg.Skip(2)); var response = SUT.RunQueryAsync <Album[]>(query).Result; response.Should().BeSuccessfulGet(artists.Select(a => a.Albums).ToArray()); }
public void Test_Build_Basic_Query_Using_From() { var expected = new Uri("http://127.0.0.1:8092/default/_design/cities/_view/by_name"); const string baseUri = "http://127.0.0.1:8092"; var query = new ViewQuery("default", baseUri). From("cities", "by_name"); Assert.Equal(expected, query.RawUri()); }
public void ShouldEnforceGroupingIfGroupLevelSet() { var query = new ViewQuery { Group = false }; query.GroupLevel = 42; Assert.True(query.Group); Assert.Throws<InvalidOperationException>(() => query.Group = false); }
public void ShouldResetGroupingIfSuppressReduce() { var query = new ViewQuery { Group = true, GroupLevel = 42 }; query.SuppressReduce = true; Assert.False(query.Group); Assert.Null(query.GroupLevel); Assert.Throws<InvalidOperationException>(() => query.Group = true); Assert.Throws<InvalidOperationException>(() => query.GroupLevel = 42); }
public IViewQueryResult Query(ViewQuery query) { return databaseApi.Query(query).WaitForResult(); }
private static string ConvertToString(ViewQuery viewQuery) { var converter = TypeDescriptor.GetConverter(typeof (ViewQuery)); return (string)converter.ConvertTo(viewQuery, typeof (string)); }
public Task<IViewQueryResult> Query(ViewQuery query) { if (query == null) throw new ArgumentNullException("query"); if (query.Skip >= 10) throw new ArgumentException("Query skip should be less then 10. http://bit.ly/d9iUeF", "query"); using (SyncContext.SwitchToDefault()) return QueryInternal(query); }
internal static bool TryParse(string uriString, out ViewQuery viewQuery) { Uri uri; viewQuery = null; return Uri.TryCreate(uriString, UriKind.Relative, out uri) && TryParse(uri, out viewQuery); }
async Task<IViewQueryResult> QueryInternal(ViewQuery query) { var response = await StartQuery(uriConstructor.GetQueryUri(query)); if (!response.IsSuccessStatusCode) { var error = new CouchError(parent.Settings.Serializer, response); error.ThrowDatabaseMissingExceptionIfNedded(uriConstructor); error.ThrowViewNotFoundExceptionIfNedded(query); error.ThrowCouchCommunicationException(); } using (var reader = await response.Content.ReadAsUtf8TextReaderAsync()) return ViewQueryResultParser.Parse(reader, query); }
internal static bool TryParse(Uri uri, out ViewQuery viewQuery) { if (uri.IsAbsoluteUri) { viewQuery = null; return false; } var match = Regex.Match( uri.ToString(), "^(?:(?<specialView>_all_docs)|_design/(?<designDocName>.*?)/_view/(?<viewName>.*?))(?:\\?(?<queryString>.*))?$"); if (match.Success) { viewQuery = new ViewQuery(); var specialViewGroup = match.Groups["specialView"]; if (specialViewGroup.Success) { var specialViewName = specialViewGroup.Value; if(!SpecialViewNames.Any(n => n == specialViewName)) throw new QueryException("Design document name is required for view {0} to be queried", specialViewName); viewQuery.ViewName = specialViewName; } else { viewQuery.DesignDocumentName = match.Groups["designDocName"].Value; viewQuery.ViewName = match.Groups["viewName"].Value; } var queryStringGroup = match.Groups["queryString"]; if (queryStringGroup.Success) Serializer.Parse(queryStringGroup.Value, ref viewQuery); return true; } viewQuery = null; return false; }
public void ShouldQueryCochApiWithSameQueryObject() { ViewQuery sendQuery = null; var dbApiMock = new Mock<IDatabaseApi>(MockBehavior.Loose); dbApiMock .Setup(ca => ca.Query(It.IsAny<ViewQuery>())) .Returns( (ViewQuery query) => { sendQuery = query; return new ViewQueryResult( query, new[] { new ViewResultRow( Entity.StandardDocId.ToJsonFragment(), new {rev = Entity.StandardRevision}.ToJsonFragment(), Entity.StandardDocId, Entity.CreateDocWithRevision() ) }, totalCount: 1, offset: 0).ToTask<IViewQueryResult>(); }); var session = new CouchSession(Default.Settings, Mock.Of<ICouchApi>(c => c.Db("testdb") == dbApiMock.Object)); var viewQuery = new ViewQuery {ViewName = "_all_docs", IncludeDocs = true}; session.Synchronously.Query<Entity>(viewQuery); Assert.Same(sendQuery, viewQuery); }
internal static Uri ToUri(ViewQuery viewQuery, ISerializer serializer = null) { var uriString = ToUriString(viewQuery); return uriString == null? null: new Uri(uriString, UriKind.Relative); }
internal static string ToUriString(ViewQuery viewQuery, ISerializer serializer = null) { if (viewQuery.ViewName.HasNoValue() || (viewQuery.DesignDocumentName.HasNoValue() && !SpecialViewNames.Any(n => n == viewQuery.ViewName))) return null; serializer = serializer ?? new NewtonsoftSerializer(); var uri = new StringBuilder(); if (!String.IsNullOrEmpty(viewQuery.DesignDocumentName)) uri.Append("_design/").Append(viewQuery.DesignDocumentName).Append("/_view/"); uri.Append(viewQuery.ViewName); var queryString = Serializer.ToQueryString(viewQuery, serializer); if (queryString.Length > 0) uri.Append("?").Append(queryString); return uri.ToString(); }
public Uri GetQueryUri(ViewQuery query) { return new Uri(databaseUriWithSlash, query.ToUri()); }
public Task<IViewQueryResult> Query(ViewQuery query) { return Task.Factory.StartNew(() => { Thread.Sleep(50); //preventing returning already done task return Mock.Of<IViewQueryResult>(r => r.Count == 0 && r.Rows == new ViewResultRow[0]); }); }
public void ThrowViewNotFoundExceptionIfNedded(ViewQuery query) { if (statusCode == HttpStatusCode.NotFound && reason == MissingNamedView) throw new ViewNotFoundException(query); }