private Task <List <NodeData> > GetEntities(string filter) { var query = _bucket.CreateQuery("entities", "all").GroupLevel(2); if (!string.IsNullOrEmpty(filter)) { query = query.StartKey(new string[] { filter, null }).EndKey(new string[] { filter, "\uefff" }).InclusiveEnd(true); } return(_bucket.QueryAsync <dynamic>(query).ContinueWith(t => { if (!string.IsNullOrEmpty(t.Result.Error)) { Console.WriteLine(t.Result.Error.ToString()); } if (t.Result.Exception != null) { Console.WriteLine(t.Result.Exception.ToString()); } return t.Result.Rows.Select(row => new NodeData { Key = row.Key[0], Type = row.Key[1] }).ToList(); })); }
public void Test_QueryAsyncNoDeadlock() { // Using an asynchronous view query within an MVC Web API action causes // a deadlock if you wait for the result synchronously. var context = new Mock <SynchronizationContext> { CallBase = true }; SynchronizationContext.SetSynchronizationContext(context.Object); try { _bucket.QueryAsync <dynamic>("SELECT * FROM `beer-sample` LIMIT 10").Wait(); // If view queries are incorrectly awaiting on the current SynchronizationContext // We will see calls to Post or Send on the mock context.Verify(m => m.Post(It.IsAny <SendOrPostCallback>(), It.IsAny <object>()), Times.Never); context.Verify(m => m.Send(It.IsAny <SendOrPostCallback>(), It.IsAny <object>()), Times.Never); } finally { SynchronizationContext.SetSynchronizationContext(null); } }
public async Task <User> Authenticate(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return(null); } var query = new QueryRequest("SELECT HelpToTeachBucket.* FROM HelpToTeachBucket WHERE type = 'user'"); var result = await bucket.QueryAsync <User>(query); // check if username exists if (!result.Success) { return(null); } var user = result.FirstOrDefault(u => u.Username == username); if (user == null) { return(null); } // check if password is correct if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) { return(null); } // authentication successful return(user); }
private static async void DemoCreateUserIndexes() { var bucketName = new CouchbaseConfiguration().GetBucket(); var createIndexQuery = new QueryRequest().Statement("CREATE PRIMARY INDEX ON `workshop`"); var result = await bucket.QueryAsync <dynamic>(createIndexQuery); if (result.Success) { Console.WriteLine("CREATE PRIMARY INDEX ON `workshop` succeeded"); } else { Console.WriteLine("CREATE PRIMARY INDEX ON `workshop` failed"); } var createIndex = new QueryRequest().Statement("CREATE INDEX `by_type_ix` ON `workshop`(type)"); var result2 = await bucket.QueryAsync <dynamic>(createIndex); if (result2.Success) { Console.WriteLine("CREATE INDEX ON `workshop`(type) succeeded"); } else { Console.WriteLine("CREATE INDEX ON `workshop`(type) failed"); } }
public async Task <List <User> > ListTenantUsers(int tenantId, int offset, int limit) { var users = new List <User>(); var n1ql = $@"Select meta().id as id, username, tenantId, firstName, lastname from `{_bucket.Name}` where type = 'user' and tenantId = $tenantId order by firstName asc limit $limit offset $offset"; var query = QueryRequest.Create(n1ql); query.AddNamedParameter("tenantId", tenantId); query.AddNamedParameter("limit", limit); query.AddNamedParameter("offset", offset); var results = await _bucket.QueryAsync <User>(query); if (results != null && results.Success && results.Rows.Count > 0) { users = results.Rows; } return(users); }
public async Task <List <Group> > GetAll() { var query = new QueryRequest("SELECT HelpToTeachBucket.* FROM HelpToTeachBucket WHERE type = 'group'"); var result = await bucket.QueryAsync <Group>(query); return(result.Rows); }
public async Task <List <Student> > GetAll() { var query = new QueryRequest( "SELECT s.*, g as `group` FROM HelpToTeachBucket s " + "JOIN HelpToTeachBucket g ON s.groupId = g.id " + "WHERE s.type = 'student' AND g.type = 'group'"); var result = await bucket.QueryAsync <Student>(query); return(result.Rows); }
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); }
public async Task <IActionResult> Patients() { var statement = $"SELECT META().id, `{_bucket.Name}`.* FROM `{_bucket.Name}` WHERE type='patient'"; var query = QueryRequest.Create(statement); var result = await _bucket.QueryAsync <Patient>(query); if (result.Success) { return(Ok(result.Rows)); } return(CouchbaseError(result)); }
/// <summary> /// Lists the indexes for a the current <see cref="IBucket" /> asynchronously. /// </summary> /// <returns></returns> public virtual async Task <IndexResult> ListN1qlIndexesAsync() { var request = new QueryRequest(string.Format(Statements.ListIndexes, BucketName)); var result = await _bucket.QueryAsync <IndexInfo>(request).ContinueOnAnyContext(); return(new IndexResult { Value = result.Rows, Exception = result.Exception, Message = result.Message, Success = result.Success }); }
public async Task <IActionResult> ProductsWDisc(string sort, [FromQuery] int pageSize = 10, [FromQuery] int pageIndex = 0) { // use the GetProducts function in the CatalogQueries interface to get the paginated products var pageView = await _catalogQueries.GetProducts(sort, pageSize, pageIndex); // iterate through each of the PageView objects foreach (PageView page in pageView.Data) { // build a new Couchbase query where we are looking for Discounts based on the product_key var queryRequest = new QueryRequest() .Statement("select * from Discounts where product_key = $id") .AddNamedParameter("$id", page.Id); var result = await _discounts.QueryAsync <Discounts>(queryRequest); // make sure the query was successful if (result.Success) { page.NumProductDiscounts = result.ToList().Count(); } // build another Couchbase query where we lookup information based on the offering_key var queryRequest2 = new QueryRequest() .Statement("select id, offering_keys, tiers, product_key, supplier_key, type from Discounts where any k in offering_keys satisfies k = $id end") .AddNamedParameter("$id", page.Offering_key); var result2 = await _discounts.QueryAsync <Discounts>(queryRequest2); if (result2.Success) { foreach (Discounts discounts in result2) // iterate through each of the Discounts from the returned query { // check to see if the result returned from the second Couchbase query containts the offering_key if (discounts.Offering_keys.Contains(page.Offering_key)) { if (discounts.Type == "PRODUCT_DISCOUNT") { page.Discount_price = Math.Round((page.Unit_retail * (1 - (discounts.tiers[0].DiscountPercentage / 100))), 2).ToString(); } else if (discounts.Type == "SUPPLIER_DISCOUNT") { // get the index of the offering_key, needed for the correct Tier int index = discounts.Offering_keys.IndexOf(page.Offering_key, 0); page.Discount_price = Math.Round((page.Unit_retail * (1 - (discounts.tiers[0].DiscountPercentage / 100))), 2).ToString(); } } } } } return(Ok(pageView)); }
/// <summary> /// Asynchronously execute a <see cref="LinqQueryRequest"/>. /// </summary> /// <typeparam name="T">Type returned by the query.</typeparam> /// <param name="queryRequest">Request to execute.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Task which contains a list of objects returned by the request when complete.</returns> public async Task <IEnumerable <T> > ExecuteCollectionAsync <T>(LinqQueryRequest queryRequest, CancellationToken cancellationToken) { if (!queryRequest.ScalarResultBehavior.ResultExtractionRequired) { var result = await _bucket.QueryAsync <T>(queryRequest, cancellationToken).ConfigureAwait(false); return(ParseResult(result)); } else { var result = await _bucket.QueryAsync <ScalarResult <T> >(queryRequest, cancellationToken).ConfigureAwait(false); return(queryRequest.ScalarResultBehavior.ApplyResultExtraction(ParseResult(result))); } }
public async Task GetEventsAsync(string actorName, ulong eventIndexStart, Action <object> callback) { var q = $"SELECT b.* FROM `{_bucket.Name}` b WHERE b.actorName='{actorName}' AND b.eventIndex>={eventIndexStart} AND b.type='event' ORDER BY b.eventIndex ASC"; var req = QueryRequest.Create(q); req.ScanConsistency(ScanConsistency.RequestPlus); var res = await _bucket.QueryAsync <Envelope>(req); ThrowOnError(res); var envelopes = res.Rows; foreach (var envelope in envelopes) { callback(envelope.Event); } }
public async Task <IList <Coleta> > GetAsync(string ip, string pagina) { var query = "SELECT `Coleta`.* FROM `Coleta`"; var where = string.Empty; if (!string.IsNullOrWhiteSpace(ip)) { where = $"ip = '{ip}' "; } if (!string.IsNullOrWhiteSpace(pagina)) { where += (!string.IsNullOrEmpty(where) ? " and " : "") + $"pagina = '{pagina}' "; } if (!string.IsNullOrEmpty(where)) { query += " WHERE " + where; } var result = await _bucket.QueryAsync <Coleta>(query); return(result.Rows); }
public override async Task <SpeechletResponse> Execute(IntentRequest intentRequest) { // get random fact from bucket var n1ql = @"select m.*, meta(m).id from boothduty m where m.type = 'mongodbcomparison' order by `number`, uuid() limit 1;"; var query = QueryRequest.Create(n1ql); var result = await _bucket.QueryAsync <BoothFact>(query); if (result == null || !result.Rows.Any()) { return(await CreateErrorResponseAsync()); } var fact = result.First(); // increment fact count await _bucket.MutateIn <dynamic>(fact.Id) .Counter("number", 1) .ExecuteAsync(); // return text of fact return(await CreatePlainTextSpeechletReponseAsync(fact.Text)); }
public void Test_QueryAsyncNoDeadlock() { // NCBC-1074 https://issues.couchbase.com/browse/NCBC-1074 // Using an asynchronous view query within an MVC Web API action causes // a deadlock if you wait for the result synchronously. var context = new Mock <SynchronizationContext> { CallBase = true }; SynchronizationContext.SetSynchronizationContext(context.Object); try { var query = _bucket.CreateQuery("beer", "brewery_beers") .Limit(1); _bucket.QueryAsync <object>(query).Wait(); // If view queries are incorrectly awaiting on the current SynchronizationContext // We will see calls to Post or Send on the mock context.Verify(m => m.Post(It.IsAny <SendOrPostCallback>(), It.IsAny <object>()), Times.Never); context.Verify(m => m.Send(It.IsAny <SendOrPostCallback>(), It.IsAny <object>()), Times.Never); } finally { SynchronizationContext.SetSynchronizationContext(null); } }
public async Task <List <GetTopicsByTermQueryResult> > GetTopicsByTerm(GetTopicsByTermQuery getTopicsByTermQuery) { var searchQuery = new SearchQuery { Index = "idx_topics", Query = new MatchQuery(getTopicsByTermQuery.Term).Fuzziness(1), SearchParams = new SearchParams().Limit(10).Timeout(TimeSpan.FromMilliseconds(10000)) }; searchQuery.Fields("name"); var searchQueryResults = await _topicsBucket.QueryAsync(searchQuery); if (!searchQueryResults.Success) { throw searchQueryResults.Exception; } var result = new List <GetTopicsByTermQueryResult>(); foreach (var hit in searchQueryResults.Hits) { result.Add(new GetTopicsByTermQueryResult { Id = Guid.Parse(hit.Id), Name = hit.Fields["name"] }); } return(result); }
public async Task <GroupCourse> Get(string id) { var query = new QueryRequest( "SELECT gc.*, c as `course`, g as `group`, l as `lecturer` " + "FROM HelpToTeachBucket gc " + "JOIN HelpToTeachBucket g ON gc.groupId = g.id " + "JOIN HelpToTeachBucket c ON gc.courseId = c.id " + "JOIN HelpToTeachBucket l ON gc.userId = l.id " + "WHERE c.type = 'course' AND g.type = 'group' " + "AND gc.type = 'groupcourse' AND l.type='user' AND gc.id = $id" ); query.AddNamedParameter("$id", id); var result = await bucket.QueryAsync <GroupCourse>(query); return(result.Rows.FirstOrDefault()); }
private async Task ExecuteGetEventsQueryAsync(string query, Action <object> callback) { var req = QueryRequest.Create(query); req.ScanConsistency(ScanConsistency.RequestPlus); var res = await _bucket.QueryAsync <Event>(req); ThrowOnError(res); var events = res.Rows; foreach (var @event in events) { callback(@event.Data); } }
public async Task DeletePredictedMarksByLesson(string lessonId) { var query = new QueryRequest("DELETE FROM HelpToTeachBucket m WHERE m.type = 'mark' AND m.isPredicted = true AND m.lessonid = $lessonId"); query.AddNamedParameter("$lessonId", lessonId); var result = await bucket.QueryAsync <Mark>(query); }
private async Task <long> ExecuteGetEventsQueryAsync(string query, Action <object> callback) { var req = QueryRequest.Create(query); req.ScanConsistency(ScanConsistency.RequestPlus); var res = await _bucket.QueryAsync <Event>(req); ThrowOnError(res); var events = res.Rows; foreach (var @event in events) { callback(@event.Data); } return(events.Any() ? events.LastOrDefault().EventIndex : -1); }
public IDisposable Subscribe(IObserver <T> observer) { var disposed = false; try { var task = _bucket.QueryAsync <T>(_query); // Pass exceptions to the observer as an error task.ContinueWith(t => { if (!disposed) { observer.OnError((Exception)t.Exception ?? new InvalidOperationException("Unknown Error")); } }, TaskContinuationOptions.OnlyOnFaulted); // Pass canceled tasks as completion to the observer task.ContinueWith(t => { if (!disposed) { observer.OnCompleted(); } }, TaskContinuationOptions.OnlyOnCanceled); // Handle successful task completion task.ContinueWith(t => { if (!disposed) { if (t.Result.Success) { // On success, deliver all rows to the observer foreach (var row in t.Result.Rows) { observer.OnNext(row); } observer.OnCompleted(); } else { observer.OnError(new CouchbaseN1QlQueryException <T>(t.Result)); } } }, TaskContinuationOptions.OnlyOnRanToCompletion); } catch (Exception ex) { observer.OnError(ex); } return(Disposable.Create(() => disposed = true)); }
public async Task <List <T> > GetAll(Type t) { var type = t.Name.ToLower(); var query = new QueryRequest("SELECT HelpToTeachBucket.* FROM HelpToTeachBucket WHERE type = $type"); query.AddNamedParameter("type", type); var result = await _bucket.QueryAsync <T>(query); return(!result.Success ? null : result.Rows); }
public async Task <IEnumerable <T> > GetAllAsync(string filter = null) { filter = PrepareFilter(filter); var statement = $"SELECT {BucketName}.* FROM {BucketName} {WhereEntity}{filter}"; var result = await _bucket.QueryAsync <T>(statement); result.ThrowIfFailure(); return(result.Rows); }
public async Task AddComment(AddCommentCommand addCommentCommand) { var queryRequest = new QueryRequest() .Statement($"UPDATE `{_eventsBucket.Name}` USE KEYS $eventId SET comments = ARRAY_APPEND(IFMISSINGORNULL(comments,[]), $comment);") .AddNamedParameter("$eventId", addCommentCommand.EventId) .AddNamedParameter("$comment", new EventCommentDocument { Comment = addCommentCommand.Comment, CommentatorId = addCommentCommand.CommentatorId, CommentedDate = addCommentCommand.CommentedDate }); var queryResult = await _eventsBucket.QueryAsync <dynamic>(queryRequest); if (!queryResult.Success) { throw queryResult.Exception; } }
public async Task <List <T> > GetByQueryAsync <T>(IQueryRequest query) { var result = await _bucket.QueryAsync <T>(query); if (!result.Success) { var errors = result.Errors.Select(er => er.Message).ToList(); _logger.Error(string.Format("GetByQueryAsync Error [{2}]: [{0}], exception: [{1}]", string.Join(",", errors), result.Exception, query)); } return(result.Rows); }
public async Task <ICollection <CrowdsourcedPlace> > GetClosePlaces(SimplePoint start, SimplePoint end) { var query = new SpatialViewQuery().From("doc", "crowdsourcedpoints") .Stale(StaleState.False) .StartRange(start.Longitude, start.Latitude) .EndRange(end.Longitude, end.Latitude); var result = await _bucket.QueryAsync <CrowdsourcedPlace>(query); return(result.Rows.Select(x => x.Value).ToList()); }
// This is used for testing purposes only async Task <List <User> > GetAllAsync() { var results = await _bucket?.QueryAsync <User>(GetAllQueryRequest()); if (results.Success && results != null) { return(results.Rows); } return(null); }
// end::AddEventsAsync[] // tag::FindLatestUserEvents[] public async Task <List <UserEvent> > FindLatestUserEvents(string userId, EventType eventType, int limit, int offset) { var n1ql = $@"SELECT META(e).id, e.userId, e.createdDate, e.eventType FROM `{_bucket.Name}` e WHERE e.type = 'userEvent' AND e.eventType = $eventType AND e.userId = $userId LIMIT $limit OFFSET $offset"; var query = QueryRequest.Create(n1ql); query.AddNamedParameter("eventType", eventType); query.AddNamedParameter("userId", userId); query.AddNamedParameter("limit", limit); query.AddNamedParameter("offset", offset); var result = await _bucket.QueryAsync <UserEvent>(query); return(result.Rows); }
public IActionResult Search(int rating) { string query; IEnumerable <Hotel> hotels; query = $"SELECT h.name,h.address,h.city,h.description from `travel-sample` as h UNNEST reviews AS r WHERE " + $"r.ratings.Rooms <{rating} limit 5"; hotels = _bucket.QueryAsync <Hotel>(query).Result.ToList(); return(View(hotels)); }
public static async Task<IEnumerable<User>> SimpleN1qlQuery(IBucket bucket, string lastname) { var query = string.Format("Select {0}.* from `{0}` where type=\"{1}\" and lastname=\"{2}\"", bucket.Name, "user", lastname); var queryN1ql = new QueryRequest().Statement(query); var result = await bucket.QueryAsync<dynamic>(queryN1ql); var users = new List<User>(); foreach (var row in result.Rows) { var user = JsonConvert.DeserializeObject<User>(Convert.ToString(row)); users.Add(user); } return users; }
public static async Task<IEnumerable<string>> JoinUserAndCompany(IBucket bucket, string userName, string companyName) { string query = string.Format( "select comp.id, comp.name compName, usr.uid" + " from {2} comp" + " join {2} usr on keys \"{0}\"" + " where comp.id = \"{1}\"" + " and comp.type = \"company\"", userName, companyName, bucket.Name); var queryN1ql = new QueryRequest().Statement(query); var results = new List<string>(); var result = await bucket.QueryAsync<dynamic>(queryN1ql); foreach (var row in result.Rows) { var res = Convert.ToString(row); results.Add(res); ; } return results; }