private async Task CreateBucketAsync()
        {
            _logger.LogInformation("Attempting to create bucket...");
            var bucketManager  = _cluster.Buckets;
            var bucketSettings = new BucketSettings
            {
                BucketType = BucketType.Couchbase,
                Name       = _config.TargetBucket,
                RamQuotaMB = _config.TargetBucketRamQuotaMB
            };

            _logger.LogInformation($"Creating bucket `{_config.TargetBucket}`...");
            try
            {
                await bucketManager.CreateBucketAsync(bucketSettings);

                _logger.LogInformation("Bucket creation complete.");
            }
            catch (BucketExistsException)
            {
                _logger.LogInformation("already exists.");
            }

            _bucket = await _cluster.BucketAsync(_config.TargetBucket);

            var opts = new WaitUntilReadyOptions();

            opts.DesiredState(ClusterState.Online);
            opts.ServiceTypes(ServiceType.KeyValue, ServiceType.Query);
            await _bucket.WaitUntilReadyAsync(TimeSpan.FromSeconds(30), opts);

            _collManager = _bucket.Collections;
        }
Exemple #2
0
        private async Task <PerBucketCleaner> CleanerForBucket(string bucketName, bool startDisabled)
        {
            var bucket = await _cluster.BucketAsync(bucketName).CAF();

            var collection = bucket.DefaultCollection();

            return(CleanerForCollection(collection, startDisabled));
        }
Exemple #3
0
        public async Task <ICouchbaseCollection> GetCollection(ICluster cluster)
        {
            var bucket = await cluster.BucketAsync(BucketName).CAF();

            var scope = bucket.Scope(ScopeName);

            return(scope.Collection(CollectionName));
        }
        public async Task InitializeAsync()
        {
            var opts = GetClusterOptions();

            Cluster = await Couchbase.Cluster.ConnectAsync(
                _settings.ConnectionString,
                opts)
                      .ConfigureAwait(false);

            var bucketSettings = new BucketSettings()
            {
                BucketType  = BucketType.Couchbase,
                Name        = BucketName,
                RamQuotaMB  = 100,
                NumReplicas = 0
            };

            try
            {
                await Cluster.Buckets.CreateBucketAsync(bucketSettings).ConfigureAwait(false);
            }
            catch (BucketExistsException)
            {
            }
            catch (System.Net.Http.HttpRequestException)
            {
                // why did it fail?
            }

            try
            {
                var bucket = await Cluster.BucketAsync(BucketName);

                try
                {
                    await bucket.Collections.CreateScopeAsync(CustomScopeName);

                    await Task.Delay(5_000);
                }
                catch (ScopeExistsException)
                {}

                try
                {
                    var collectionSpec = new CollectionSpec(scopeName: CustomScopeName, CustomCollectionName);
                    await bucket.Collections.CreateCollectionAsync(collectionSpec);

                    await Task.Delay(5_000);
                }
                catch (CollectionExistsException)
                {}
            }
            catch
            {
                throw;
            }
        }
        private async Task ConnectToCouchbaseAsync()
        {
            _trace.TraceInformation("Connecting...");
            _cluster = await Cluster.ConnectAsync(_config.ConnectionString, _config.Username, _config.Password);

            _bucket = await _cluster.BucketAsync(_config.Bucket);

            _collection = _bucket.DefaultCollection();

            _trace.TraceInformation("Connected to Couchbase collection - ", _collection.Name);
        }
Exemple #6
0
        public async Task Setup()
        {
            Cluster = await Couchbase.Cluster.ConnectAsync(
                "couchbase://localhost",
                "Administrator",
                "password");

            Bucket = await Cluster.BucketAsync("matt");

            Collection = Bucket.DefaultCollection();
        }
        protected async Task ConnectAsync()
        {
            var options = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .Build()
                          .GetSection("couchbase")
                          .Get <ClusterOptions>();

            Cluster = await Couchbase.Cluster.ConnectAsync(options).ConfigureAwait(false);

            Bucket = await Cluster.BucketAsync("default").ConfigureAwait(false);
        }
        public async Task <Employees> PutEmployeById(ICluster cluster, int id, Employees value)
        {
            var bucket = await cluster.BucketAsync("Employees");

            var collection     = bucket.DefaultCollection();
            var collectiondata = await collection.UpsertAsync(id.ToString(), value);

            if (collectiondata == null)
            {
                logger.LogError("Error in update");
            }
            return(null);
        }
        //create
        public async Task <Employees> PostEmploye(ICluster cluster, Employees value)
        {
            var bucket = await cluster.BucketAsync("Employees");

            var collection      = bucket.DefaultCollection();
            int idvalue         = value.id;
            var collectiondataa = await collection.InsertAsync(idvalue.ToString(), value);

            if (collectiondataa == null)
            {
                logger.LogError("Error in creating");
            }

            return(null);
        }
        async Task <ICouchbaseCollectionManager> getCollectionManager(String username, String password)
        {
            Console.WriteLine("create-collection-manager");

            // tag::create-collection-manager[]
            ICluster cluster = await Cluster.ConnectAsync("couchbase://localhost", username, password);

            IBucket bucket = await cluster.BucketAsync("travel-sample");

            ICouchbaseCollectionManager collectionMgr = bucket.Collections;

            // end::create-collection-manager[]

            return(collectionMgr);
        }
Exemple #11
0
        public async Task GlobalSetup()
        {
            var options = new ClusterOptions()
                          .WithConnectionString("couchbase://localhost")
                          .WithCredentials("Administrator", "password");

            _cluster = await Cluster.ConnectAsync(options);

            var bucket = await _cluster.BucketAsync("default");

            _collection = bucket.DefaultCollection();

            _key = Guid.NewGuid().ToString();

            await _collection.InsertAsync(_key, new { name = "mike" }).ConfigureAwait(false);
        }
Exemple #12
0
        public async Task Setup()
        {
            var connectionString = Environment.GetEnvironmentVariable("COUCHBASE_CONNECTION_STRING") ?? "couchbase://localhost";
            var username         = Environment.GetEnvironmentVariable("COUCHBASE_USERNAME") ?? "Administrator";
            var password         = Environment.GetEnvironmentVariable("COUCHBASE_PASSWORD") ?? "password";
            var bucketName       = Environment.GetEnvironmentVariable("COUCHBASE_BUCKET_NAME") ?? "tests";

            _cluster = await Cluster.ConnectAsync(connectionString, username, password);

            var bucket = await _cluster.BucketAsync(bucketName);

            _collection = bucket.DefaultCollection();

            _dal = new DataAccess(_collection);

            _documentsToDelete = new List <string>();
        }
        public async Task <Employees> DeleteEmployeById(ICluster cluster, int id)
        {
            try
            {
                //  var queryResult = await cluster.QueryAsync<Employees>("SELECT username,name,email,age,location,srccs,phoneNumber,salary,skill,managerName,address,id FROM Employees where id= "  + id.ToString()  , new Couchbase.Query.QueryOptions());
                var bucket = await cluster.BucketAsync("Employees");


                var collection = bucket.DefaultCollection();

                await collection.RemoveAsync(id.ToString());

                return(null);
            }
            catch (BucketNotFoundException)
            {
                logger.LogError("Bucket not found");
                throw;
            }
        }
        private async Task Initialize()
        {
            /* Logging here used the following dependencies in the associated .csproj file
             *     <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.3" />
             *     <PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0-dev-00039" />
             */

            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(builder => builder
                                         .AddFilter(level => level >= LogLevel.Information) // change to Debug if trying to diagnose
                                         );
            loggerFactory = serviceCollection.BuildServiceProvider().GetService <ILoggerFactory>();
            loggerFactory.AddFile("Logs/myapp-{Date}.txt"); // change to Debug if trying to diagnose


            /* Note: in the configuration below, EnableTls is required as Couchbase Capella is
             * always TLS. Also, the IgnoreRemoteCertificateNameMismatch will trust the asserted
             * CA Cert by Couchbase Capella. There is a known issue that prevents programmatically
             * adding the cert, so either this or adding it to the platform is required.
             */
            var config = new ClusterOptions
            {
                UserName = "******",
                Password = "******",
                IgnoreRemoteCertificateNameMismatch = true, // workaround for CA Cert
                EnableTls = true
            }.WithLogging(loggerFactory);

            cluster = await Cluster.ConnectAsync(
                "couchbases://6b115491-a379-4bc3-bedb-780c5fbdf8a8.dp.cloud.couchbase.com", config);

            Thread.Sleep(500);

            bucket = await cluster.BucketAsync("travel-sample");

            collection = bucket.DefaultCollection();
        }
        public virtual async Task Setup()
        {
            var connectionString = Environment.GetEnvironmentVariable("COUCHBASE_CONNECTION_STRING") ?? "couchbase://localhost";
            var username         = Environment.GetEnvironmentVariable("COUCHBASE_USERNAME") ?? "Administrator";
            var password         = Environment.GetEnvironmentVariable("COUCHBASE_PASSWORD") ?? "password";
            var bucketName       = Environment.GetEnvironmentVariable("COUCHBASE_BUCKET_NAME") ?? "tests";

            TestCluster = await Cluster.ConnectAsync(connectionString, username, password);

            // from this point on, any test using this base class assumes:
            // - that a bucket with name in bucketName exists
            // - that a primary index in that bucket exists
            // Locally, you'll need to make sure this is setup manually
            // Also see the .github folder for how this is setup for Github Actions CI/CD

            Bucket = await TestCluster.BucketAsync(bucketName);

            Collection        = Bucket.DefaultCollection();
            DocumentsToRemove = new List <string>();
            BucketProvider    = new IntegrationTestBucketProvider(Bucket);
            TestKeyGen        = new TestKeyGenerator(DocumentsToRemove);
            TestConfiguration = new FakeConfiguration();
        }
Exemple #16
0
        public async Task Setup()
        {
            var connectionString = Environment.GetEnvironmentVariable("COUCHBASE_CONNECTION_STRING") ?? "couchbase://localhost";
            var username         = Environment.GetEnvironmentVariable("COUCHBASE_USERNAME") ?? "Administrator";
            var password         = Environment.GetEnvironmentVariable("COUCHBASE_PASSWORD") ?? "password";
            var bucketName       = Environment.GetEnvironmentVariable("COUCHBASE_BUCKET_NAME") ?? "tests";

            _cluster = await Cluster.ConnectAsync(connectionString, username, password);

            // try
            // {
            await _cluster.Buckets.CreateBucketAsync(new BucketSettings
            {
                Name         = bucketName,
                BucketType   = BucketType.Couchbase,
                FlushEnabled = true,
                RamQuotaMB   = 100,
                NumReplicas  = 0
            });

            await _cluster.QueryIndexes.CreatePrimaryIndexAsync(bucketName);

            // }
            // catch
            // {
            //     // assume the bucket already exists
            // }

            var bucket = await _cluster.BucketAsync(bucketName);

            _collection = bucket.DefaultCollection();

            _dal = new DataAccess(_collection);

            _documentsToDelete = new List <string>();
        }
Exemple #17
0
        protected async Task ConnectAsync()
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(builder => builder
                                         .AddFilter(level => level >= LogLevel.Debug)
                                         );
            var loggerFactory = serviceCollection.BuildServiceProvider().GetService <ILoggerFactory>();

            loggerFactory.AddFile("Logs/myapp-{Date}.txt", LogLevel.Debug);

            Logger = loggerFactory.CreateLogger("examples");

            var options = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .Build()
                          .GetSection("couchbase")
                          .Get <ClusterOptions>()
                          .WithLogging(loggerFactory);

            Cluster = await Couchbase.Cluster.ConnectAsync(options).ConfigureAwait(false);

            Bucket = await Cluster.BucketAsync("default").ConfigureAwait(false);
        }
Exemple #18
0
        public async Task CreateJobs(int nbr, Database databases, bool useStronglyTyped = false)
        {
            jsonObjects.Clear();
            for (int i = 1; i <= nbr; i++)
            {
                JObject temp = JObject.FromObject(_baseJsonObject);
                temp["JobId"]        = i;
                temp["CustomerName"] = $"{firstnames[rand.Next(0, firstnames.Count - 1)]} {lastnames[rand.Next(0, lastnames.Count - 1)]}";
                jsonObjects.Add(temp);

                pocoObjects.Add(JsonConvert.DeserializeObject <Root>(temp.ToString())); // added option to use strongly typed stuff
            }
            Console.WriteLine($"Done initializing dummy objects");

            Stopwatch sw = new Stopwatch();

            if (databases.HasFlag(Database.Couchbase))
            {
                // TODO You need to setup Couchbase with the buckets etc as listed here
                IBucket bucket = await cluster.BucketAsync("myBucket");

                IScope scope      = bucket.Scope("myScope");
                var    collection = scope.Collection("myCollection");

                // avoid measuring lazy loading:
                JObject t = JObject.FromObject(_baseJsonObject);
                t["JobId"]        = 0;
                t["CustomerName"] = $"{firstnames[rand.Next(0, firstnames.Count - 1)]} {lastnames[rand.Next(0, lastnames.Count - 1)]}";
                await collection.InsertAsync("0", t);

                await collection.RemoveAsync("0");

                // List<Task> inserTasks = new List<Task>();
                sw.Start();
                if (useStronglyTyped)
                {
                    foreach (Root root in pocoObjects)
                    {
                        await collection.InsertAsync(root.JobId.ToString(), root);
                    }
                }
                else
                {
                    foreach (JObject temp in jsonObjects)
                    {
                        await collection.InsertAsync(temp.GetValue("JobId").ToString(), temp);
                    }
                }
                // await Task.WhenAll(inserTasks);
                sw.Stop();
                Console.WriteLine($"Adding {nbr} to Couchbase took {sw.ElapsedMilliseconds} ms");
                sw.Reset();
            }

            if (databases.HasFlag(Database.Redis))
            {
                sw.Restart();
                using (var client = redisManager.GetClient())
                {
                    // no concepts of strongly typed in redis...
                    foreach (JObject temp in jsonObjects)
                    {
                        client.Set($"jobId:{temp.GetValue("JobId")}", temp.ToString());
                    }
                }
                sw.Stop();
                Console.WriteLine($"Adding {nbr} to Redis took {sw.ElapsedMilliseconds} ms");
                sw.Reset();
            }

            if (databases.HasFlag(Database.MySql))                                                                                             // file 'mysql-table-sql' has table def
            {
                MySqlConnection mySqlConnection = new MySqlConnection("Server=localhost;Database=test;port=3306;User Id=root;password=root;"); // TODO replace user / pass
                mySqlConnection.Open();
                sw.Restart();
                foreach (JObject temp in jsonObjects)
                {
                    MySqlCommand cmd = new MySqlCommand($"INSERT INTO test (id, data) VALUES ('{temp.GetValue("JobId")}', @data)", mySqlConnection);
                    cmd.Parameters.AddWithValue("@data", temp.ToString());
                    cmd.ExecuteNonQuery();
                }
                sw.Stop();
                Console.WriteLine($"Adding {nbr} to MySql took {sw.ElapsedMilliseconds} ms");
                sw.Reset();
            }

            if (databases.HasFlag(Database.Aerospike))
            {
                /* namespace = database
                 * sets = tables
                 * records = rows
                 * bins = columns */

                sw.Restart();
                // no concept of strongly typed
                foreach (JObject temp in jsonObjects)
                {
                    aeroClient.Put(null, new Key("test", "cache", temp.GetValue("JobId").ToString()), new Bin[]
                    {
                        new Bin("Id", temp.GetValue("JobId").ToString()),
                        new Bin("Data", temp.ToString())
                    });
                }
                sw.Stop();
                Console.WriteLine($"Adding {nbr} to Aerospike took {sw.ElapsedMilliseconds} ms");
                sw.Reset();
            }

            if (databases.HasFlag(Database.RediSql))
            {
                var dbName = "db";
                using (var client = redisManager.GetClient())
                {
                    client.Custom($"DEL", dbName);
                    client.Custom($"REDISQL.CREATE_DB", dbName);
                    client.Custom($"REDISQL.EXEC", dbName, $"CREATE TABLE alfacom_jobcache (Id INT, Data TEXT)");
                    client.Custom($"REDISQL.EXEC", dbName, $"CREATE INDEX jobid_idx ON jobcache (Id)");
                }

                sw.Restart();
                using (var client = redisManager.GetClient())
                {
                    // no concepts of strongly typed in redis...
                    foreach (JObject temp in jsonObjects)
                    {
                        RediSqlCommand(client, dbName, $"INSERT INTO jobcache VALUES ({temp.GetValue("JobId")}, '{temp.ToString(Formatting.Indented)}')");
                    }
                }
                sw.Stop();
                Console.WriteLine($"Adding {nbr} to RediSql took {sw.ElapsedMilliseconds} ms");
                sw.Reset();
            }
        }
        public async Task ExecuteAsync()
        {
            Console.WriteLine("scopeAdmin");
            {
                // tag::scopeAdmin[]
                ICluster clusterAdmin = await Cluster.ConnectAsync(
                    "couchbase://localhost", "Administrator", "password");

                IUserManager users = clusterAdmin.Users;

                var user = new User("scopeAdmin")
                {
                    Password    = "******",
                    DisplayName = "Manage Scopes [travel-sample:*]",
                    Roles       = new List <Role>()
                    {
                        new Role("scope_admin", "travel-sample"),
                        new Role("data_reader", "travel-sample")
                    }
                };

                await users.UpsertUserAsync(user);

                // end::scopeAdmin[]
            }

            ICluster cluster = await Cluster.ConnectAsync("couchbase://localhost", "scopeAdmin", "password");

            IBucket bucket = await cluster.BucketAsync("travel-sample");

            // tag::create-collection-manager[]
            ICouchbaseCollectionManager collectionMgr = bucket.Collections;
            // end::create-collection-manager[]
            {
                Console.WriteLine("create-scope");
                // tag::create-scope[]
                try {
                    await collectionMgr.CreateScopeAsync("example-scope");
                }
                catch (ScopeExistsException) {
                    Console.WriteLine("The scope already exists");
                }
                // end::create-scope[]
            }
            {
                Console.WriteLine("create-collection");
                // tag::create-collection[]
                var spec = new CollectionSpec("example-scope", "example-collection");

                try {
                    await collectionMgr.CreateCollectionAsync(spec);
                }
                catch (CollectionExistsException) {
                    Console.WriteLine("Collection already exists");
                }
                catch (ScopeNotFoundException) {
                    Console.WriteLine("The specified parent scope doesn't exist");
                }
                // end::create-collection[]

                Console.WriteLine("listing-scope-collection");
                // tag::listing-scope-collection[]
                var scopes = await collectionMgr.GetAllScopesAsync();

                foreach (ScopeSpec scopeSpec in scopes)
                {
                    Console.WriteLine($"Scope: {scopeSpec.Name}");

                    foreach (CollectionSpec collectionSpec in scopeSpec.Collections)
                    {
                        Console.WriteLine($" - {collectionSpec.Name}");
                    }
                }
                // end::listing-scope-collection[]

                Console.WriteLine("drop-collection");
                // tag::drop-collection[]
                try {
                    await collectionMgr.DropCollectionAsync(spec);
                }
                catch (CollectionNotFoundException) {
                    Console.WriteLine("The specified collection doesn't exist");
                }
                catch (ScopeNotFoundException) {
                    Console.WriteLine("The specified parent scope doesn't exist");
                }
                // end::drop-collection[]
            }
            {
                Console.WriteLine("drop-scope");
                // tag::drop-scope[]
                try {
                    await collectionMgr.DropScopeAsync("example-scope");
                }
                catch (ScopeNotFoundException) {
                    Console.WriteLine("The specified scope doesn't exist");
                }
                // end::drop-scope[]
            }
        }
Exemple #20
0
 public DiagnosticsReportTests(ClusterFixture fixture)
 {
     _fixture = fixture;
     _cluster = _fixture.Cluster;
     _cluster.BucketAsync("default").GetAwaiter().GetResult();
 }
        async Task QueryExamples()
        {
            // this isn't meant to run, merely to compile correctly.
            ICluster cluster      = null;
            var      transactions = Transactions.Create(cluster);
            {
                // tag::queryExamplesSelect[]
                var st = "SELECT * FROM `travel-sample`.inventory.hotel WHERE country = $1";
                var transactionResult = await transactions.RunAsync(async ctx => {
                    IQueryResult <object> qr = await ctx.QueryAsync <object>(st,
                                                                             new TransactionQueryOptions().Parameter("United Kingdom"));

                    await foreach (var result in qr.Rows)
                    {
                        Console.Out.WriteLine($"result = {result}", result);
                    }
                });

                // end::queryExamplesSelect[]
            }

            {
                // tag::queryExamplesSelectScope[]
                IBucket travelSample = await cluster.BucketAsync("travel-sample");

                IScope inventory = travelSample.Scope("inventory");

                var transactionResult = await transactions.RunAsync(async ctx =>
                {
                    var st = "SELECT * FROM `travel-sample`.inventory.hotel WHERE country = $1";
                    IQueryResult <object> qr = await ctx.QueryAsync <object>(st,
                                                                             options: new TransactionQueryOptions().Parameter("United Kingdom"),
                                                                             scope: inventory);
                });

                // end::queryExamplesSelectScope[]
            }

            {
                IBucket travelSample = await cluster.BucketAsync("travel-sample");

                IScope inventory = travelSample.Scope("inventory");
                // tag::queryExamplesUpdate[]
                var hotelChain = "http://marriot%";
                var country    = "United States";

                await transactions.RunAsync(async ctx => {
                    var qr = await ctx.QueryAsync <object>(
                        statement: "UPDATE hotel SET price = $price WHERE url LIKE $url AND country = $country",
                        configure: options => options.Parameter("price", 99.99m)
                        .Parameter("url", hotelChain)
                        .Parameter("country", country),
                        scope: inventory);

                    Console.Out.WriteLine($"Records Updated = {qr?.MetaData.Metrics.MutationCount}");
                });

                // end::queryExamplesUpdate[]
            }

            {
                IBucket travelSample = await cluster.BucketAsync("travel-sample");

                IScope inventory  = travelSample.Scope("inventory");
                var    hotelChain = "http://marriot%";
                var    country    = "United States";
                //private class Review { };
                // tag::queryExamplesComplex[]
                await transactions.RunAsync(async ctx => {
                    // Find all hotels of the chain
                    IQueryResult <Review> qr = await ctx.QueryAsync <Review>(
                        statement: "SELECT reviews FROM hotel WHERE url LIKE $1 AND country = $2",
                        configure: options => options.Parameter(hotelChain).Parameter(country),
                        scope: inventory);

                    // This function (not provided here) will use a trained machine learning model to provide a
                    // suitable price based on recent customer reviews.
                    var updatedPrice = PriceFromRecentReviews(qr);

                    // Set the price of all hotels in the chain
                    await ctx.QueryAsync <object>(
                        statement: "UPDATE hotel SET price = $1 WHERE url LIKE $2 AND country = $3",
                        configure: options => options.Parameter(hotelChain, country, updatedPrice),
                        scope: inventory);
                });

                // end::queryExamplesComplex[]
            }

            {
                // tag::queryInsert[]
                await transactions.RunAsync(async ctx => {
                    await ctx.QueryAsync <object>("INSERT INTO `default` VALUES ('doc', {'hello':'world'})", TransactionQueryConfigBuilder.Create());  // <1>

                    // Performing a 'Read Your Own Write'
                    var st = "SELECT `default`.* FROM `default` WHERE META().id = 'doc'"; // <2>
                    IQueryResult <object> qr = await ctx.QueryAsync <object>(st, TransactionQueryConfigBuilder.Create());
                    Console.Out.WriteLine($"ResultCount = {qr?.MetaData.Metrics.ResultCount}");
                });

                // end::queryInsert[]
            }

            {
                // tag::querySingle[]
                var bulkLoadStatement = "<a bulk-loading N1QL statement>";

                try
                {
                    SingleQueryTransactionResult <object> result = await transactions.QueryAsync <object>(bulkLoadStatement);

                    IQueryResult <object> queryResult = result.QueryResult;
                }
                catch (TransactionCommitAmbiguousException e)
                {
                    Console.Error.WriteLine("Transaction possibly committed");
                    foreach (var log in e.Result.Logs)
                    {
                        Console.Error.WriteLine(log);
                    }
                }
                catch (TransactionFailedException e)
                {
                    Console.Error.WriteLine("Transaction did not reach commit point");
                    foreach (var log in e.Result.Logs)
                    {
                        Console.Error.WriteLine(log);
                    }
                }
                // end::querySingle[]
            }

            {
                string bulkLoadStatement = null /* your statement here */;

                // tag::querySingleScoped[]
                IBucket travelSample = await cluster.BucketAsync("travel-sample");

                IScope inventory = travelSample.Scope("inventory");

                await transactions.QueryAsync <object>(bulkLoadStatement, scope : inventory);

                // end::querySingleScoped[]
            }


            {
                string bulkLoadStatement = null; /* your statement here */

                // tag::querySingleConfigured[]
                // with the Builder pattern.
                await transactions.QueryAsync <object>(bulkLoadStatement, SingleQueryTransactionConfigBuilder.Create()
                                                       // Single query transactions will often want to increase the default timeout
                                                       .ExpirationTime(TimeSpan.FromSeconds(360)));

                // using the lambda style
                await transactions.QueryAsync <object>(bulkLoadStatement, config => config.ExpirationTime(TimeSpan.FromSeconds(360)));

                // end::querySingleConfigured[]
            }

            {
                ICouchbaseCollection collection = null;
                // tag::queryRyow[]
                await transactions.RunAsync(async ctx => {
                    _ = await ctx.InsertAsync(collection, "doc", new { Hello = "world" }); // <1>

                    // Performing a 'Read Your Own Write'
                    var st = "SELECT `default`.* FROM `default` WHERE META().id = 'doc'"; // <2>
                    var qr = await ctx.QueryAsync <object>(st);
                    Console.Out.WriteLine($"ResultCount = {qr?.MetaData.Metrics.ResultCount}");
                });

                // end::queryRyow[]
            }

            {
                // tag::queryOptions[]
                await transactions.RunAsync(async ctx => {
                    await ctx.QueryAsync <object>("INSERT INTO `default` VALUES ('doc', {'hello':'world'})",
                                                  new TransactionQueryOptions().FlexIndex(true));
                });

                // end::queryOptions[]
            }

            {
                // tag::custom-metadata[]
                ICouchbaseCollection metadataCollection = null; // this is a Collection opened by your code earlier
                Transactions         transactionsWithCustomMetadataCollection = Transactions.Create(cluster,
                                                                                                    TransactionConfigBuilder.Create().MetadataCollection(metadataCollection));
                // end::custom-metadata[]
            }
        }
Exemple #22
0
        static async Task Main(string[] args)
        {
            // SETUP: connect to Couchbase
            _cluster = await Cluster.ConnectAsync(
                "couchbase://localhost",
                "Administrator",
                "password");

            _bucket = await _cluster.BucketAsync("matt");

            _scope = await _bucket.ScopeAsync("myScope");

            _coll = await _scope.CollectionAsync("myCollection");

            // SETUP: create a 'conference' document and a 'conference activities' document
            await SetupInitialDocuments();

            // STEP 1: create transactions object
            var transactions = Transactions.Create(_cluster,
                                                   TransactionConfigBuilder.Create()
                                                   .DurabilityLevel(DurabilityLevel.MajorityAndPersistToActive) // since I have 1 node, replication must be 0, or this will throw exception
                                                   .Build());

            Console.WriteLine("Press ENTER to continue");
            Console.ReadLine();

            // STEP 2: transaction operations
            await transactions.RunAsync(async (ctx) =>
            {
                var now = DateTime.Now;

                // FIRST: get the two document I want to change
                var confDoc = await ctx.GetAsync(_coll, "dataLove2021");
                var actsDoc = await ctx.GetAsync(_coll, "dataLove2021::activities");
                var conf    = confDoc.ContentAs <Conference>();
                var acts    = actsDoc.ContentAs <ConferenceActivities>();

                // SECOND: add an event to the "activities" document
                acts.Events.Add(new ConferenceEvent
                {
                    Type       = "CFP",
                    DtActivity = now,
                    Desc       = "Submitted to the CFP"
                });
                // acts.Events.Add(new ConferenceEvent
                // {
                //     Type = "PRESENTATION",
                //     DtActivity = now,
                //     Desc = "Delivered ACID presentation"
                // });
                // acts.Events.Add(new ConferenceEvent
                // {
                //     Type = "SPATIAL",
                //     DtActivity = now,
                //     Desc = "Answered questions in Spatial Chat"
                // });

                // THIRD: change the "conference" document
                conf.Followups    = (conf.Followups ?? 0) + 1;
                conf.LastActivity = now;

                // FOURTH: write the changes
                await ctx.ReplaceAsync(confDoc, conf);

                // OPTIONAL STEP: fail right in the middle of the transaction making two writes
                // var fail = true;
                // if(fail) throw new Exception("Something went wrong!");

                await ctx.ReplaceAsync(actsDoc, acts);

                // FIFTH: commit (implied)
            });

            await _cluster.DisposeAsync();
        }