public async Task <NLogItemEntity> UpsertAsync(object item) { var bucket = await _provider.GetBucketAsync(_options.Bucket); NLogItemEntity nLogItemEntity; try { var configContent = await CollectionExtensions.GetAsync(bucket.DefaultCollection(), _options.ConfigId); nLogItemEntity = configContent.ContentAs <NLogItemEntity>(); } catch (DocumentNotFoundException e) { nLogItemEntity = new NLogItemEntity(); nLogItemEntity.CreationDate = DateTime.UtcNow; } nLogItemEntity.LastModifiedDate = DateTime.Now; nLogItemEntity.Config = item; await bucket.DefaultCollection().UpsertAsync(_options.ConfigId, nLogItemEntity); return(nLogItemEntity); }
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> AddEventToUser(string userId, UserEventPost evt) { var bucket = await _bucketProvider.GetBucketAsync("useractivity"); var coll = bucket.DefaultCollection(); var activityId = $"activity::{Guid.NewGuid()}"; await coll.InsertAsync(activityId, new { userId, evt.Description, evt.EventType, EventDt = DateTime.Now }); return(Ok()); }
/// <summary> /// Gets a Couchbase Lock Provider using a bucket provider. /// </summary> /// <param name="bucketProvider">Bucket Provider Instance to use.</param> /// <returns>Instance of <see cref="CouchbaseLockProvider"/>.</returns> public static async Task <CouchbaseLockProvider> GetInstance(IBucketProvider bucketProvider) { if (bucketProvider == null) { throw new ArgumentNullException(nameof(bucketProvider)); } var bucket = await bucketProvider.GetBucketAsync("default") .ConfigureAwait(false); return(GetInstance(bucket)); }
public async Task <IActionResult> GetById([FromRoute] Guid id) { try { var bucket = await _bucketProvider.GetBucketAsync(_couchbaseConfig.BucketName); var scope = bucket.Scope(_couchbaseConfig.ScopeName); var collection = await scope.CollectionAsync(_couchbaseConfig.CollectionName); var result = await collection.GetAsync(id.ToString()); return(Ok(result.ContentAs <Profile>())); } catch (DocumentNotFoundException) { return(NotFound()); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(StatusCodes.Status500InternalServerError, $"Error: {ex.Message} {ex.StackTrace} {Request.GetDisplayUrl()}")); } }
public async Task <IActionResult> RequestWithLock(int requester) { var bucket = await _bucketProvider.GetBucketAsync("default"); var collection = bucket.DefaultCollection(); _logger.LogInformation("Starting requester {requester}", requester); try { var startTime = DateTime.Now; // Retry policy will try 10 times to get the lock, and will wait 1 second between attempts // Lock will be held for 2 seconds if not renewed using (var mutex = await RetryPolicy.ExecuteAsync(() => collection.RequestMutexAsync("my_lock_name", TimeSpan.FromSeconds(2)))) { // Will renew the lock every second, up to a maximum of 15 seconds, so long as the process keeps running mutex.AutoRenew(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(15)); var lockTime = DateTime.Now; await Task.Delay(5000); return(View(new RequestWithLockModel { WasLocked = true, LockDelayTime = lockTime - startTime, LockHoldTime = DateTime.Now - lockTime })); // Lock will be released once we exit the using statement, and auto renew will cease } } catch (CouchbaseLockUnavailableException) { return(View(new RequestWithLockModel { WasLocked = false })); } }
public async Task LoadFromDbIfChangedAsync(DateTime?lastSyncTime) { var bucket = await _bucketProvider.GetBucketAsync(_couchBaseOptions.Bucket); var settingResult = await bucket.DefaultCollection().GetAsync(_couchBaseOptions.ConfigId); var contentAs = settingResult.ContentAs <NLogItemEntity>(); if (lastSyncTime.HasValue && !(lastSyncTime.Value < contentAs.LastModifiedDate)) { } else { var obj = new JObject(); obj.Add("NLog", JToken.Parse(JsonConvert.SerializeObject(contentAs))); var configuration = new ConfigurationBuilder() .AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(obj.ToString()))) .Build(); var configurationSection = configuration.GetSection("NLog"); NLogBuilder.ConfigureNLog(new NLogLoggingConfiguration(configurationSection)); } }
public ValueTask <IBucket> GetBucketAsync() { return(_bucketProvider.GetBucketAsync(BucketName)); }
public async Task CreateCollection() { IBucket bucket = null; try { _logger.LogInformation("**INFO** Opening Bucket <{BucketName}> with username: <{Username}> and password:<{Password}>", _couchbaseConfig.BucketName, _couchbaseConfig.Username, _couchbaseConfig.Password); bucket = await _bucketProvider.GetBucketAsync(_couchbaseConfig.BucketName); } catch (System.Exception ex) { _logger.LogError("**ERROR** Couldn't connect to bucket {BucketName} with username: <{Username}> and password: <{Password}> with Error: {Error}", _couchbaseConfig.BucketName, _couchbaseConfig.Username, _couchbaseConfig.Password, ex.Message); } if (bucket != null) { if (!_couchbaseConfig.ScopeName.StartsWith("_")) { //try to create scope - if fails it's ok we are probably using default try { await bucket.Collections.CreateScopeAsync(_couchbaseConfig.CollectionName); } catch (ScopeExistsException) { _logger.LogWarning($"Scope {_couchbaseConfig.ScopeName} already exists, probably default"); } catch (HttpRequestException) { _logger.LogWarning($"HttpRequestExcecption when creating Scope {_couchbaseConfig.ScopeName}"); } } //try to create collection - if fails it's ok the collection probably exists try { _logger.LogInformation("**INFO** Creating Collection: <{CollectionName}> with username: <{Username}> and password:<{Password}> in bucket <{BucketName}>", _couchbaseConfig.CollectionName, _couchbaseConfig.Username, _couchbaseConfig.Password, _couchbaseConfig.BucketName); await bucket.Collections.CreateCollectionAsync(new CollectionSpec(_couchbaseConfig.ScopeName, _couchbaseConfig.CollectionName)); } catch (CollectionExistsException) { _logger.LogWarning($"Collection {_couchbaseConfig.CollectionName} already exists in {_couchbaseConfig.BucketName}."); } catch (HttpRequestException) { _logger.LogWarning($"HttpRequestExcecption when creating collection {_couchbaseConfig.CollectionName}"); } } else { throw new System.Exception("Can't retreive bucket."); } }