public async Task RawJsonEncode()
        {
            // #tag::raw-json-encode[]
            var userBytes = JsonSerializer.SerializeToUtf8Bytes(new User
            {
                Name = "John Smith",
                Age  = 27
            }, typeof(User));

            await _collection.UpsertAsync("john-smith", userBytes, options => options.Transcoder(new RawJsonTranscoder()));

            // #end::raw-json-encode[]
        }
예제 #2
0
        private static async Task ScanConsistencyAtPlusExample(ICluster cluster, ICouchbaseCollection collection)
        {
            // tag::atplus[]
            // create / update document (mutation)
            var upsertResult = await collection.UpsertAsync("doc1", new { name = "Mike AtPlus", type = "user" });

            // create mutation state from mutation results
            var state = MutationState.From(upsertResult);

            // use mutation state with query option
            var result = await cluster.QueryAsync <dynamic>(
                "SELECT t.* FROM `travel-sample` t WHERE t.type=$1",
                options => options.ConsistentWith(state)
                .Parameter("user")
                );

            // end::atplus[]

            // check query was successful
            if (result.MetaData.Status != QueryStatus.Success)
            {
                // error
            }

            // iterate over rows
            // NOTE: because the query is using AtPlus, the new user will be indexed, but notice
            // the extra step of creating the 'state' object and passing it in as a 'ConsistentWith' option
            await foreach (var row in result)
            {
                // each row is an instance of the Query<T> call (e.g. dynamic or custom type)
                var name = row.name;        // "Mike AtPlus"
                Console.WriteLine($"{name}");
            }
        }
예제 #3
0
        private static async Task ScanConsistencyNotBoundedExample(ICluster cluster, ICouchbaseCollection collection)
        {
            // create / update document (mutation)
            var upsertResult = await collection.UpsertAsync("doc3", new { name = "Mike NotBounded", type = "user" });

            // tag::notbounded[]
            var result = await cluster.QueryAsync <dynamic>(
                "SELECT t.* FROM `travel-sample` t WHERE t.type=$1",
                options => options.Parameter("user")
                .ScanConsistency(QueryScanConsistency.NotBounded)
                );

            // end::notbounded[]

            // check query was successful
            if (result.MetaData.Status != QueryStatus.Success)
            {
                // error
            }

            // iterate over rows
            // NOTE: because the query is using NotBounded, the new user may not be indexed yet
            await foreach (var row in result)
            {
                // each row is an instance of the Query<T> call (e.g. dynamic or custom type)
                var name = row.name;        // "Mike NotBounded"
                Console.WriteLine($"{name}");
            }
        }
        public static Task <IMutationResult> UpsertAsync <T>(this ICouchbaseCollection collection, string id, T content,
                                                             Action <UpsertOptions> configureOptions)
        {
            var options = new UpsertOptions();

            configureOptions(options);

            return(collection.UpsertAsync(id, content, options));
        }
        public async Task CollectionIdChanged_RetriesAutomatically()
        {
            const string scopeName      = "CollectionIdChanged";
            const string collectionName = "coll";
            const string key            = nameof(CollectionIdChanged_RetriesAutomatically);

            var bucket = await _fixture.GetDefaultBucket().ConfigureAwait(false);

            var collectionManager = bucket.Collections;

            try
            {
                await collectionManager.CreateScopeAsync(scopeName);

                await collectionManager.CreateCollectionAsync(new CollectionSpec(scopeName, collectionName));

                await Task.Delay(1000);

                var scope = await bucket.ScopeAsync(scopeName);

                ICouchbaseCollection collection = await scope.CollectionAsync(collectionName);

                await collection.UpsertAsync(key, new { name = "mike" }).ConfigureAwait(false);

                await collectionManager.DropCollectionAsync(new CollectionSpec(scopeName, collectionName));

                await Task.Delay(500);

                await collectionManager.CreateCollectionAsync(new CollectionSpec(scopeName, collectionName));

                await Task.Delay(500);

                await collection.UpsertAsync(key, new { name = "mike" }).ConfigureAwait(false);
            }
            finally
            {
                await collectionManager.DropScopeAsync(scopeName);
            }
        }
예제 #6
0
 private static async Task UpdateDocument(ICouchbaseCollection collection, string documentId)
 {
     // hiába kezdődnek nagy betűvel a property nevek, a CB-be beírt JSON-ban kis betűvel kezdődnek; minden CB művelet kis-nagybetű érzékeny!
     var person = new
     {
         Name         = "András 2",
         Sex          = "male",
         Status       = "offline",
         BooksByTitle = new[]
         {
             "Tom Jones",
             "Treasure Island",
             "RoboCop 2"
         }
     };
     var mutationResult = await collection.UpsertAsync(documentId, person);
 }
        private async Task ReceivingAsync()
        {
            try
            {
                while (true)
                {
                    var query  = String.Format("SELECT id, status, streamIndex, data FROM {0} WHERE status = 0 ORDER BY id ASC LIMIT 1;", _config.Bucket);
                    var result = await _cluster.QueryAsync <CouchbaseMessage>(query);

                    if (result == null)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(150));
                        continue;
                    }

                    await foreach (var row in result)
                    {
                        try
                        {
                            var _scaleoutmsg = row.ToScaleoutMessage();
                            OnReceived(row.StreamIndex, (ulong)DateTime.Parse(row.Id).Ticks, _scaleoutmsg);
                            row.Status = 1;
                            await _collection.UpsertAsync(row.Id, row);
                        }

                        catch (Exception ex)
                        {
                            _trace.TraceInformation("Error adding message to InProcessBus. Id={0}, Data={1}. Error={2}, Stack={3}",
                                                    row.Id, row.Data, ex.Message, ex.StackTrace);
                            Debug.WriteLine(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _connectionReady = false;
                Debug.WriteLine(ex.Message);
            }
        }
 public static Task <IMutationResult> UpsertAsync <T>(this ICouchbaseCollection collection, string id, T content)
 {
     return(collection.UpsertAsync(id, content, UpsertOptions.Default));
 }
예제 #9
0
 private static Task Upsert(ICouchbaseCollection collection, KeyValuePair <string, object> document)
 {
     return(collection.UpsertAsync(document.Key, document.Value));
 }
        /// <summary>
        /// Executes a query and ingests the results as documents into Couchbase server for further analytics.
        /// <para>
        /// NOTE: This is an experimental API and may change in the future.
        /// </para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cluster"></param>
        /// <param name="collection"></param>
        /// <param name="statement"></param>
        /// <param name="ingestOptions"></param>
        /// <returns></returns>
        public static async Task <IEnumerable <IMutationResult> > IngestAsync <T>(this ICluster cluster, string statement, ICouchbaseCollection collection, IngestOptions ingestOptions = null)
        {
            //use defaults if not options not explicitly passed
            ingestOptions ??= new IngestOptions();

            if (ingestOptions.TokenValue.IsCancellationRequested)
            {
                ingestOptions.TokenValue.ThrowIfCancellationRequested();
            }

            //execute the analytics query
            var result = await cluster.AnalyticsQueryAsync <T>(
                statement,
                options => options.CancellationToken(ingestOptions.TokenValue)
                ).ConfigureAwait(false);

            // ingest result into collection
            var results = new ConcurrentBag <Task <IMutationResult> >();

            await foreach (var row in result.WithCancellation(ingestOptions.TokenValue).ConfigureAwait(false))
            {
                Task <IMutationResult> op;
                switch (ingestOptions.IngestMethodValue)
                {
                case IngestMethod.Insert:
                    op = collection.InsertAsync(
                        ingestOptions.IdGeneratorValue(row),
                        row,
                        options =>
                    {
                        options.Expiry(ingestOptions.ExpiryValue);
                        options.Timeout(ingestOptions.TimeoutValue);
                    });
                    break;

                case IngestMethod.Upsert:
                    op = collection.UpsertAsync(
                        ingestOptions.IdGeneratorValue(row),
                        row,
                        options =>
                    {
                        options.Expiry(ingestOptions.ExpiryValue);
                        options.Timeout(ingestOptions.TimeoutValue);
                    });
                    break;

                case IngestMethod.Replace:
                    op = collection.ReplaceAsync(
                        ingestOptions.IdGeneratorValue(row),
                        row,
                        options =>
                    {
                        options.Expiry(ingestOptions.ExpiryValue);
                        options.Timeout(ingestOptions.TimeoutValue);
                    });
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                results.Add(op);
            }

            return(await Task.WhenAll(results).ConfigureAwait(false));
        }