示例#1
0
        public async Task InitializeCouchBase()
        {
            var cluster = await _clusterProvider.GetClusterAsync();

            var bucketExist =
                (await cluster.Buckets.GetAllBucketsAsync()).ContainsKey(_setupAction.Bucket);
            IBucket bucket = null;

            if (bucketExist)
            {
                bucket = await _bucketProvider.GetBucketAsync(_setupAction.Bucket);
            }
            else
            {
                bucket = await cluster.BucketAsync(_setupAction.Bucket);
            }


            var settingExist = await bucket.DefaultCollection().ExistsAsync(_setupAction.ConfigId);

            //Seed To DB from Appsettings
            if (settingExist.Exists)
            {
                return;
            }

            var nLogJson = BuildJson(_configuration.GetSection("NLog"));

            await _logConfigAppService.UpsertAsync(nLogJson.ToObject <object>());
        }
        public async Task <IActionResult> List([FromQuery] ProfileListRequestQuery request)
        {
            try
            {
                var cluster = await _clusterProvider.GetClusterAsync();

                var query = $@"SELECT p.*
FROM `{_couchbaseConfig.BucketName}`.`{_couchbaseConfig.ScopeName}`.`{_couchbaseConfig.CollectionName}` p
WHERE lower(p.firstName) LIKE '%' || $search || '%'
OR lower(p.lastName) LIKE '%' || $search || '%'
LIMIT $limit OFFSET $skip";

                var results = await cluster.QueryAsync <Profile>(query, options =>
                {
                    options.Parameter("search", request.Search.ToLower());
                    options.Parameter("limit", request.Limit);
                    options.Parameter("skip", request.Skip);
                });

                var items = await results.Rows.ToListAsync <Profile>();

                if (items.Count == 0)
                {
                    return(NotFound());
                }

                return(Ok(items));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError, $"Error: {ex.Message} {ex.StackTrace} {Request.GetDisplayUrl()}"));
            }
        }
            public async Task <IActionResult> IndexAsync()
            {
                var cluster = await _provider.GetClusterAsync();

                //do some work

                return(View());
            }
        public async Task <IActionResult> Get(string icao)
        {
            using var span =
                      DiagListener.StartActivity(new Activity(nameof(AirlineController) + "." + nameof(Get)), new { icao });
            Airline airline;
            var     membucket = await _membucket.GetBucketAsync().ConfigureAwait(false);

            var memCollection      = membucket.DefaultCollection();
            var travelSampleBucket = await _travelSample.GetBucketAsync().ConfigureAwait(false);

            var collection = travelSampleBucket.DefaultCollection();

            if (int.TryParse(icao, out var id))
            {
                var fullId    = $"airline_{id}";
                var getResult = await collection.GetAsync(fullId).ConfigureAwait(false);

                airline = getResult.ContentAs <Airline>();
            }
            else
            {
                try
                {
                    var memGetResult = await memCollection.GetAsync(icao).ConfigureAwait(false);

                    airline = memGetResult.ContentAs <Airline>();
                    if (airline.Name == null)
                    {
                        throw new DocumentNotFoundException();
                    }

                    return(View(airline));
                }
                catch (DocumentNotFoundException)
                {
                    var cluster = await _clusterProvider.GetClusterAsync().ConfigureAwait(false);

                    var queryResult = await cluster.QueryAsync <Airline>(
                        "SELECT `travel-sample`.* FROM `travel-sample` WHERE type='airline' AND icao = $icao",
                        options => options.Parameter("icao", icao)).ConfigureAwait(false);

                    airline = await queryResult.Rows.FirstOrDefaultAsync().ConfigureAwait(false);
                }
            }

            if (airline == null)
            {
                return(NotFound());
            }

            if (airline?.Icao != null)
            {
                var memUpsertResult = await memCollection.UpsertAsync <Airline>(airline.Icao, airline, options => options.Expiry(TimeSpan.FromSeconds(30)));
            }

            return(View(airline));
        }
示例#5
0
        public async Task CreateIndex()
        {
            ICluster cluster = null;

            //try to create index - if fails it probably already exists
            try
            {
                _logger.LogInformation("**INFO** Trying to create Indexes...");
                cluster = await _clusterProvider.GetClusterAsync().ConfigureAwait(false);

                _logger.LogInformation("**INFO** Create Indexes - Cluster returned.");
                if (cluster != null)
                {
                    var queries = new List <string>
                    {
                        $"CREATE PRIMARY INDEX default_profile_index ON {_couchbaseConfig.BucketName}.{_couchbaseConfig.ScopeName}.{_couchbaseConfig.CollectionName}",
                        $"CREATE Primary INDEX on {_couchbaseConfig.BucketName}"
                    };
                    foreach (var query in queries)
                    {
                        _logger.LogInformation("**INFO** Running Create Index query: {query}", query);
                        var result = await cluster.QueryAsync <dynamic>(query).ConfigureAwait(false);

                        if (result.MetaData.Status != QueryStatus.Success)
                        {
                            _logger.LogError("**ERROR** Couldn't create index required with {Query}", query);
                            throw new System.Exception($"Error create index didn't return proper results for index {query}");
                        }
                    }
                }
                else
                {
                    _logger.LogError("**ERROR** Couldn't create indexes, cluster is null");
                }
            }
            catch (IndexExistsException)
            {
                _logger.LogWarning($"Collection {_couchbaseConfig.CollectionName} already exists in {_couchbaseConfig.BucketName}.");
            }
            catch (System.Exception ex)
            {
                _logger.LogError("**ERROR** {Message}", ex.Message);
            }
        }
示例#6
0
        public async Task <IActionResult> Get(
            int skip = 0,
            int take = 100,
            CancellationToken cancellationToken = default
            )
        {
            var cluster = await _clusterProvider.GetClusterAsync();

            var queryResult = await cluster.QueryAsync <Customer>(
                "SELECT default.* FROM default WHERE type = 'customer' AND lname IS NOT MISSING ORDER BY lname, fname OFFSET $skip LIMIT $take",
                new Couchbase.Query.QueryOptions()
                .AdHoc(false)
                .Parameter("$skip", skip)
                .Parameter("$take", take)
                .CancellationToken(cancellationToken));

            var customers = await queryResult.ToListAsync(cancellationToken);

            return(Ok(customers));
        }
        /// <inheritdoc />
        public ValueTask <IBucket> GetBucketAsync(string bucketName)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(BucketProvider));
            }
            if (bucketName == null)
            {
                throw new ArgumentNullException(nameof(bucketName));
            }

            // We're wrapping the Task in a ValueTask here for future-proofing, this will allow us to change the
            // implementation in the future to one with fewer allocations.
            return(new ValueTask <IBucket>(
                       _buckets.GetOrAdd(bucketName, async name =>
            {
                var cluster = await _clusterProvider.GetClusterAsync().ConfigureAwait(false);

                return await cluster.BucketAsync(name).ConfigureAwait(false);
            })));
        }
 public CouchbaseBucketBase(IClusterProvider clusterProvider, string bucketName)
 {
     Cluster           = clusterProvider.GetClusterAsync().GetAwaiter().GetResult();
     Bucket            = Cluster.BucketAsync(bucketName).GetAwaiter().GetResult();
     DefaultCollection = GetCollection();
 }
        private static async Task <IBucket> GetBucketFromClusterAsync(string bucketName, IClusterProvider clusterProvider)
        {
            var cluster = await clusterProvider.GetClusterAsync().ConfigureAwait(false);

            return(await cluster.BucketAsync(bucketName).ConfigureAwait(false));
        }