private static async void DemoGetCompany() { var companyId = "couchbase"; var company = await bucket.GetAsync <string>(companyId); var companyObject = JsonConvert.DeserializeObject <Company>(company.Value); Console.WriteLine("Company: " + JsonConvert.SerializeObject(companyObject)); }
public async Task Test_GetAsync() { var key = "thekey"; var value = "thevalue"; await _bucket.RemoveAsync(key); await _bucket.InsertAsync(key, value); var result = await _bucket.GetAsync <string>(key); Assert.AreEqual(ResponseStatus.Success, result.Status); }
public async Task RetrieveAndUpdateAsync() { var key = "SampleAppAsync--" + DateTime.Now.Ticks; var data = new Data { Number = 42, Text = "Life, the Universe, and Everything", Date = DateTime.UtcNow }; // Get non-existent document. // Note that it's enough to check the Status property, // We're only checking all three to show they exist. var notFound = await _bucket.GetAsync <dynamic>(key); if (!notFound.Success && notFound.Status == ResponseStatus.KeyNotFound) { Console.WriteLine("Document doesn't exist!"); } // Prepare a JSON document value await _bucket.UpsertAsync(key, data); // Get a JSON document string value var docResult = await _bucket.GetAsync <Data>(key); Console.WriteLine("Found: " + docResult.Value); // Change the data data.Number++; data.Text = "What's 7 * 6 + 1?"; data.Date = DateTime.UtcNow; // Try to insert under the same key should fail var insertResult = await _bucket.InsertAsync(key, data); if (!insertResult.Success) { Console.WriteLine("Inserting under an existing key fails as expected."); } // Replace existing document // Note this only works if the key already exists var replaceResult = await _bucket.ReplaceAsync(key, data); var res = await _bucket.RemoveAsync(key); Console.WriteLine("Got: " + res.Status); }
public async Task <T> Get(string id) { var key = CreateKey(id); var result = await _bucket.GetAsync <T>(key); return(!result.Success ? null : result.Value); }
protected override Task <WorkloadOperationResult> OnExecuteStep(IBucket bucket, int workloadIndex, int docIndex, Func <TimeSpan> getTiming) { var key = DocKeyGenerator.Generate(workloadIndex, docIndex); var randomKey = DocKeyGenerator.Generate(workloadIndex, docIndex); if (UseSync) { var upsertResult = bucket.Upsert(key, SampleDocument); var getResult = bucket.Get <string>(randomKey); return(Task.FromResult( new WorkloadOperationResult(upsertResult.Success && getResult.Success, GetMessage(upsertResult, getResult), getTiming()) )); } return(Task.WhenAll( bucket.UpsertAsync(key, SampleDocument), bucket.GetAsync <string>(randomKey) ) .ContinueWith(tasks => new WorkloadOperationResult(tasks.Result[0].Success && tasks.Result[1].Success, GetMessage(tasks.Result[0], tasks.Result[1]), getTiming()) { DocSize = GetDocSize(tasks.Result[1]) + SampleDocument.Length })); }
/// <summary> /// Gets a document by key asynchronously. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> /// <exception cref="CouchbaseException">All server responses other than Success.</exception> /// <exception cref="Exception">Any client error condition.</exception> public async Task <T> GetAsync <T>(string key) { var result = await _bucket.GetAsync <T>(key); if (result.Success) { return(result.Value); } if (result.Status == ResponseStatus.KeyNotFound) { return(default(T)); } if (result.Exception != null) { // ReSharper disable once ThrowingSystemException throw result.Exception; } throw new CouchbaseException(result, key); }
public async Task <IActionResult> Patient(string id) { var result = await _bucket.GetAsync <Patient>(id); if (result.Success) { return(Ok(result.Value)); } return(CouchbaseError(result)); }
public async Task <ValidStaticCommands> Handle(StaticCommandsLookup request, CancellationToken cancellationToken) { var result = await _bucket.GetAsync <ValidStaticCommands>("staticContentCommands"); if (!result.Success) { return(new ValidStaticCommands()); } return(result.Value); }
public async Task <ValidSoundEffects> Handle(SoundEffectLookup request, CancellationToken cancellationToken) { var soundEffectResult = await _bucket.GetAsync <ValidSoundEffects>("validSoundEffects"); if (!soundEffectResult.Success) { return(new ValidSoundEffects()); } return(soundEffectResult.Value); }
public async Task <ActionResult <JObject> > Get(string id) { var ticket = await _bucket.GetAsync <dynamic>(id); if (!ticket.Success) { return(NotFound()); } return(Ok(JObject.FromObject(new { valid = ticket.Value.valid }))); }
public async Task <IActionResult> retrieveOrderHist() { var currentUser = HttpContext.User; if (!currentUser.HasClaim(c => c.Type == "user_id")) { return(BadRequest()); } var ID = currentUser.Claims.FirstOrDefault(c => c.Type == "user_id").Value; var result = await _checkoutBucket.GetAsync <Checkout>(ID); if (!result.Success) { return(NotFound()); } return(Ok(result.Value)); }
public static IObservable <KeyValuePair <string, T> > GetObservable <T>(this IBucket bucket, string key) { return(Observable.FromAsync(() => bucket.GetAsync <T>(key)) .Where(p => p.Status != ResponseStatus.KeyNotFound) .Select(p => { CheckResultForError(p); return new KeyValuePair <string, T>(key, p.Value); })); }
public async Task <Position?> GetAsync(string key) { var result = await _relationsBucket.GetAsync <CheckpointDocument>($"checkpoints|{key}"); if (result.Value == null) { return(null); } return(result.Value.Position); }
public async Task <BookEntity> GetById(string id) { var result = await _bucket.GetAsync <BookEntity>(id); if (result.Success) { return(result.Value); } return(null); }
public virtual async Task <MiniStatement> GetTransactionStatement(int accountID) { //IBucket bucket = await ClusterHelper.GetBucketAsync("Bank"); var miniStatement = await bucket.GetAsync <MiniStatement>(accountID.ToString()); return(miniStatement.Value ?? new MiniStatement() { AccountID = accountID, Transactions = new List <TransactionRecord>() }); }
public async Task <IActionResult> InvalidateTicket(string id) { var result = await _bucket.GetAsync <dynamic>(id); if (result.Value == null) { return(NotFound()); } await _bucket.UpsertAsync(id, new { valid = false }); return(Ok()); }
public async Task When_Key_Is_Touched_Expiration_Is_Extended_Async() { var key = "When_Key_Is_Touched_Expiration_Is_Extended_Async"; await _bucket.RemoveAsync(key); await _bucket.InsertAsync(key, "{value}", new TimeSpan(0, 0, 0, 2)); Thread.Sleep(3000); var result = await _bucket.GetAsync <string>(key); Assert.AreEqual(result.Status, ResponseStatus.KeyNotFound); await _bucket.RemoveAsync(key); await _bucket.InsertAsync(key, "{value}", new TimeSpan(0, 0, 0, 2)); await _bucket.TouchAsync(key, new TimeSpan(0, 0, 0, 5)); Thread.Sleep(3000); result = await _bucket.GetAsync <string>(key); Assert.AreEqual(result.Status, ResponseStatus.Success); }
public async Task <IActionResult> AddCategory(string userId, Category category) { var u = await _bucket.GetAsync <User>(userId); User user = u.Value; List <Todo> todoList = new List <Todo>(); category.CategoryId = Guid.NewGuid().ToString(); category.Todos = todoList; user.Categories.Add(category); _bucket.Upsert(user.UserId, user); return(Ok()); }
public async Task <User> FindByIdAsync(string id) { User user = null; var result = await _bucket.GetAsync <User>(id); if (result != null) { user = result.Value; user.Id = id; } return(user); }
/// <summary> /// Finds the role by it's unique identifier (key). /// </summary> /// <param name="roleId">The key for the role.</param> /// <returns></returns> /// <exception cref="CouchbaseException"></exception> public async Task <T> FindByIdAsync(string roleId) { var result = await _bucket.GetAsync <T>(roleId); if (!result.Success) { if (result.Exception != null) { throw result.Exception; } throw new CouchbaseException(result, roleId); } return(result.Value); }
public async Task <Unit> Handle(StaticMessage request, CancellationToken cancellationToken) { // assumes that the request is valid // look up the content var result = await _bucket.GetAsync <ValidStaticCommands>("staticContentCommands"); var contents = result.Value; var command = contents.Commands.First(c => c.Command == request.Command); // write the content to the chat room _twitchClient.SendMessage(request.Channel, command.Content); return(default);
public T Get <T>(string key, CacheRegion region) where T : class { // Was advised by Couchbase vendor to use ASYNC api in synchronous manor vs using the synchronous call // Said it was more optimized. Just so you know. var bytesBackOut = bucket.GetAsync <byte[]>(key).Result.Value; if (bytesBackOut == null) { return(null); } using (var stream = new MemoryStream(bytesBackOut)) { var retrievedObject = (T)formatter.Deserialize(stream); return(retrievedObject); } }
public static async Task <TEntity> GetSlimAsync <TEntity>(this IBucket bucket, string key, bool throwIfFailed = true) where TEntity : BaseEntity <TEntity>, IBaseEntity { var result = await bucket.GetAsync <TEntity>(key); if (result.Success) { return(result.Value); } if (throwIfFailed) { throw new CouchBaseException(result); } return(null); }
/// <summary> /// Reads a document representing a grain state object. /// </summary> /// <param name="collectionName">The type of the grain state object.</param> /// <param name="key">The grain id string.</param> /// <returns>Completion promise for this operation.</returns> public async Task <Tuple <string, string> > Read(string collectionName, string key) { var docID = GetDocumentID(collectionName, key); //If there is a value we read it and consider the CAS as ETag as well and return //both as a tuple var result = await bucket.GetAsync <string>(docID); if (result.Success) { return(Tuple.Create <string, string>(result.Value, result.Cas.ToString())); } if (!result.Success && result.Status == Couchbase.IO.ResponseStatus.KeyNotFound) //not found { return(Tuple.Create <string, string>(null, "")); } throw result.Exception; }
public async Task <T> GetAsync(string entityId) { if (entityId == null) { throw new ArgumentNullException(nameof(entityId)); } var documentId = _context.DocumentIdFor(entityId); var result = await _bucket.GetAsync <T>(documentId); if (result.Status == ResponseStatus.KeyNotFound) { return(null); } result.ThrowIfFailure(); return(result.Value); }
public async Task <HomePageInfo> Handle(GetHomePageInfo request, CancellationToken cancellationToken) { var homePageInfoExists = await _bucket.ExistsAsync("homePageInfo"); if (!homePageInfoExists) { return(new HomePageInfo()); } var result = await _bucket.GetAsync <HomePageInfo>("homePageInfo"); if (!result.Success) { return(new HomePageInfo()); } return(result.Value); }
public async Task <IActionResult> Get(string id = null) { if (string.IsNullOrEmpty(id)) { return(BadRequest("Missing or empty 'id' query string parameter")); } var result = await _bucket.GetAsync <Person>(id); if (!result.Success) { return(StatusCode((int)HttpStatusCode.InternalServerError, result.Exception?.Message ?? result.Message)); } result.Value.Id = id; return(Ok(result.Value)); }
public async Task JoinEvent(JoinEventCommand joinEventCommand) { var attempts = 0; Exception exception = null; do { var @event = await _eventsBucket.GetAsync <EventDocument>(joinEventCommand.EventId.ToString()); if (@event.Value.Capacity == @event.Value.AttendeeCount) { throw new CapacityLimitExceededException(); } if (@event.Value.Attendees.Any((x) => x.AttendeeId == joinEventCommand.AttendeeId)) { throw new AttendeeIdAlreadyExistsException(); } var original = @event.Value; var documentResult = await _eventsBucket.MutateIn <EventDocument>(joinEventCommand.EventId.ToString()) .Replace("attendeeCount", ++original.AttendeeCount) .ArrayAppend("attendees", new EventAttendeeDocument { AttendeeId = joinEventCommand.AttendeeId, JoinedDate = joinEventCommand.JoinedDate }) .WithCas(@event.Cas) .ExecuteAsync(); if (documentResult.Success) { break; } exception = documentResult.Exception; } while (attempts++ < 10); if (exception != null) { throw exception; } }
protected override Task <WorkloadOperationResult> OnExecuteStep(IBucket bucket, int workloadIndex, int docIndex, Func <TimeSpan> getTiming) { var key = DocKeyGenerator.Generate(workloadIndex, docIndex); if (UseSync) { var result = Randomizer.NextDouble() <= _mutationPercentage ? bucket.Upsert(key, SampleDocument) : bucket.Get <string>(key); return(Task.FromResult( new WorkloadOperationResult(result.Success, result.Message, getTiming()) )); } return((Randomizer.NextDouble() <= _mutationPercentage ? bucket.UpsertAsync(key, SampleDocument) : bucket.GetAsync <string>(key)) .ContinueWith( task => new WorkloadOperationResult(task.Result.Success, task.Result.Message, getTiming()) )); }
/// <inheritdoc /> public async Task <ReadResponse> ReadAsync(string grainTypeName, string key) { var documentId = GetDocumentId(grainTypeName, key); var result = await bucket.GetAsync <string>(documentId); if (result.Success) { return(new ReadResponse { Document = result.Value, ETag = result.Cas.ToString() }); } if (!result.Success && result.Status == ResponseStatus.KeyNotFound) { return(new ReadResponse { Document = null, ETag = string.Empty }); } throw result.Exception; }