public async Task RawJsonDecode() { // #tag::raw-json-decode[] var result = await _collection.GetAsync("john-smith", options => options.Transcoder(new RawJsonTranscoder())); var returnedJson = result.ContentAs <byte[]>(); var user = JsonSerializer.Deserialize(returnedJson, typeof(User)); // #end::raw-json-decode[] }
private static async Task UpdateSamePersonUsingOptimisticLockingWithCasValue(ICouchbaseCollection collection, string documentId) { var getResult = await collection.GetAsync(documentId); var person = getResult.ContentAs <Person>(); var newPerson1 = person.WithSomeNumber(1); var replaceOptions = new ReplaceOptions().Cas(getResult.Cas); // csak akkor replace-el, ha a doksi CAS-ja egyezik a ReplaceOptions-ben megadottal // az UpsertAsync()-nek beadható UpsertOption()-nek nincs Cas() művelete, ezért használom Replace()-t var mutationResult1 = await collection.ReplaceAsync(documentId, newPerson1, replaceOptions); try { var newPerson2 = person.WithSomeNumber(2); // a doksi CAS-ja nem egyezik a korábban lekérttel, ezért dob var mutationResult2 = await collection.ReplaceAsync(documentId, newPerson2, replaceOptions); } catch (Couchbase.Core.Exceptions.KeyValue.DocumentExistsException ex) { // a hiba részeleteit tartalmazza; típusa: Couchbase.Core.Exceptions.KeyValue.KeyValueErrorContext: több minden van benne, mint IErrorContext-en var replaceContext = ex.Context; } }
private static async Task Get(ICouchbaseCollection collection, string key) { using (var result = await collection.GetAsync(key)) { // Trigger deserialization result.ContentAs <dynamic>(); } }
public static Task <IGetResult> GetAsync(this ICouchbaseCollection collection, string id, Action <GetOptions> configureOptions) { var options = new GetOptions(); configureOptions?.Invoke(options); return(collection.GetAsync(id, options)); }
private async Task <IGetResult> GetResultAsync(ICouchbaseCollection collection, string id) { try { var getResult = await collection.GetAsync(id); return(getResult); } catch (DocumentNotFoundException) { return(null); } }
async Task CompleteErrorHandling() { // #tag::full-error-handling[] try { var result = await _transactions.RunAsync(async (ctx) => { // ... transactional code here ... }); // The transaction definitely reached the commit point. Unstaging // the individual documents may or may not have completed if (result.UnstagingComplete) { // Operations with non-transactional actors will want // unstagingComplete() to be true. await _cluster.QueryAsync <dynamic>(" ... N1QL ... ", new QueryOptions()).ConfigureAwait(false); var documentKey = "a document key involved in the transaction"; var getResult = await _collection.GetAsync(documentKey).ConfigureAwait(false); } else { // This step is completely application-dependent. It may // need to throw its own exception, if it is crucial that // result.unstagingComplete() is true at this point. // (Recall that the asynchronous cleanup process will // complete the unstaging later on). } } catch (TransactionCommitAmbiguousException err) { // The transaction may or may not have reached commit point Console.Error.WriteLine("Transaction returned TransactionCommitAmbiguous and" + " may have succeeded, logs:"); // Of course, the application will want to use its own logging rather // than System.err Console.Error.WriteLine(err); } catch (TransactionFailedException err) { // The transaction definitely did not reach commit point Console.Error.WriteLine("Transaction failed with TransactionFailed, logs:"); Console.Error.WriteLine(err); } // #end::full-error-handling[] }
public async Task ParallelOperations() { async Task DoOneHundredGets() { for (var i = 0; i < 100; i++) { using var result = await _collection.GetAsync(_key).ConfigureAwait(false); } } var parallelTasks = Enumerable.Range(1, 8) .Select(_ => DoOneHundredGets()) .ToList(); await Task.WhenAll(parallelTasks).ConfigureAwait(false); }
public async Task Does_data_access_create_the_document() { // arrange var widgetId = Guid.NewGuid().ToString(); var widget = new Widget { Name = "dota2attitude " + Guid.NewGuid() }; _documentsToDelete.Add(widgetId); // act await _dal.CreateWidget(widgetId, widget); // assert var result = await _collection.GetAsync(widgetId); Assert.That(result.ContentAs <Widget>().Name, Is.EqualTo(widget.Name)); }
private async Task RunTest() { var getResult = await collection.GetAsync("airline_5209").ConfigureAwait(false); var docContent = getResult.ContentAs <dynamic>(); Console.WriteLine($"The airline is {docContent.name}."); try { var queryResult = await cluster.QueryAsync <dynamic>("SELECT * FROM `travel-sample` LIMIT 10", parameter => { parameter.Parameter("type", "airline"); }).ConfigureAwait(false); await foreach (var o in queryResult.ConfigureAwait(false)) { Console.WriteLine(JsonConvert.SerializeObject(o, Formatting.None)); } } catch (CouchbaseException ex) { Console.WriteLine(ex); } }
private static async Task <Person> GetDocument(ICouchbaseCollection collection, string documentId) { using (var result = await collection.GetAsync(documentId)) { // a korábban INSERT-ált doksinak olyan property-jei vannak, mint a Person osztálynak, ezért működik var person = result.ContentAs <Person>(); // azért működik, mert a CB kliens Newtonsoft JSON sorosítót használ, és JObject a lekért doksi eredeti nyers formája var jObject = result.ContentAs <JObject>(); try { // Az online tutorial-ban (https://docs.couchbase.com/dotnet-sdk/3.0/howtos/kv-operations.html) a result.ContentAs<string>() hívást mutatják, pedig nem jó... // Elszáll azzal a hibával, hogy nem tudja parse-olni azt, hogy "{.Path"; azért, mert a JObject példányt akarja parse-olni (aminek van Path prop-ja), // és megdöglik. A CB kliens itt is hülyén működik, mert a használt visszasorosítót hozzádrótozták az interface-hez. Legalább tettek volna // IGetResult-ra egy GetAsRawString() metódust, és akkor nem kéne nekünk foglalkozni azzal, hogy milyen library-t használnak belsőleg, ha // csak a doksi nyers string formátuma érdekel. Ehelyett a lenti módszerrel kell vacakolni: lekérni egy JObject-et, aztán azon hívni ToString()-et. string rawDocumentString = result.ContentAs <string>(); } catch (Exception ex) { } string documentRawString = jObject.ToString(); return(person); } }
public async Task <Widget> GetWidget(string widgetId) { var result = await _collection.GetAsync(widgetId); return(result.ContentAs <Widget>()); }
public static Task <IGetResult> GetAsync(this ICouchbaseCollection collection, string id) { return(collection.GetAsync(id, GetOptions.Default)); }
/// <inheritdoc/> public async Task Renew(TimeSpan expiration, CancellationToken cancellationToken = default) { if (expiration <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(expiration), "Value must be positive."); } var key = LockDocument.GetKey(Name); var document = new LockDocument { Holder = Holder, RequestedDateTime = DateTime.UtcNow }; bool lockAcquired = false; IMutationResult?result = null; try { if (_cas == 0) { // We're creating a new lock _logger.LogDebug("Requesting lock '{name}' for holder '{holder}' for {expiration}", Name, Holder, expiration); result = await _collection.InsertAsync(key, document, new InsertOptions().Expiry(expiration).CancellationToken(cancellationToken)) .ConfigureAwait(false); } else { _logger.LogDebug("Renewing lock '{name}' for holder '{holder}' for {expiration}", Name, Holder, expiration); result = await _collection.ReplaceAsync(key, document, new ReplaceOptions().Expiry(expiration).CancellationToken(cancellationToken).Cas(_cas)) .ConfigureAwait(false); } lockAcquired = true; } catch (CasMismatchException) { // This is a valid case, trap the exception _logger.LogDebug("CAS mismatch updating lock '{name}'", Name); } catch (DocumentExistsException) { // This is a valid case, trap the exception _logger.LogDebug("Lock document already exists for lock '{name}'", Name); } catch (DocumentNotFoundException) { // This is a valid, but rare, case where the document being renewed expired before // the renewal. In this case, we'll let the logic move on, which will recreate the document. _logger.LogDebug("Lock document missing for lock '{name}'", Name); } if (lockAcquired) { _logger.LogDebug("Lock '{name}' issued to holder '{holder}'", Name, Holder); _expirationInterval = expiration; _cas = result !.Cas; return; } if (!lockAcquired) { _logger.LogDebug("Lock '{name}' unavailable, getting lock info", Name); IGetResult getResult; try { getResult = await _collection.GetAsync(key).ConfigureAwait(false); } catch (DocumentNotFoundException) { try { // Couldn't find the lock, must have expired between Insert and Get, try one more time result = await _collection.InsertAsync(key, document, new InsertOptions().Expiry(expiration).CancellationToken(cancellationToken)) .ConfigureAwait(false); } catch (DocumentExistsException) { throw new CouchbaseLockUnavailableException(Name); } _logger.LogDebug("Lock '{name}' issued to holder '{holder}'", Name, Holder); _expirationInterval = expiration; _cas = result.Cas; return; } _logger.LogDebug("Unable to acquire lock '{name}' for holder '{holder}'", Name, Holder); throw new CouchbaseLockUnavailableException(Name) { Holder = getResult.ContentAs <LockDocument>().Holder }; } }