示例#1
0
        /// <summary>
        /// Gets the hash.
        /// </summary>
        /// <returns>The hash.</returns>
        /// <param name="result">Result.</param>
        internal static string ToHash(this IDocumentResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var c = (result.Content?.ToString(Cultures.Invariant) ?? string.Empty) +
                    (result.Date == null ? "(none)" : result.Date.Value.ToEpoch().ToString(Cultures.Invariant)) +
                    (result.Slug ?? "(none)") +
                    (result.Draft) +
                    (result.DocumentIdentifier.ProjectId ?? "(none)") +
                    (result.DocumentIdentifier.DocumentType.ToString() ?? "(none)") +
                    (result.DocumentIdentifier.DocumentTypeId ?? "(none)") +
                    (result.DocumentIdentifier.DocumentId ?? "(none)") +
                    ((result.DocumentIdentifier.Index ?? 0).ToString(Cultures.Invariant));

            if (result.OriginalMeta != null)
            {
                c += JsonConvert.SerializeObject(result.OriginalMeta);
            }

            if (result.Meta != null)
            {
                c += JsonConvert.SerializeObject(result.Meta);
            }

            return(HashTools.GetHash(c, HashTools.HashType.SHA1));
        }
        public static void ThrowIfNotSuccess <T>(this IDocumentResult <T> result)
        {
            if (result.Success)
            {
                return;
            }
            switch (result.Status)
            {
            case ResponseStatus.KeyNotFound:
                throw new DocumentNotFoundException(result, result.Document.Id);

            case ResponseStatus.AuthenticationError:
                throw new CouchbaseAuthenticationException(result);

            case ResponseStatus.ItemNotStored:
            case ResponseStatus.VBucketBelongsToAnotherServer:
            case ResponseStatus.OutOfMemory:
            case ResponseStatus.InternalError:
            case ResponseStatus.Busy:
            case ResponseStatus.TemporaryFailure:
                throw new CouchbaseServerException(result, result.Document.Id);

            case ResponseStatus.ValueTooLarge:
                throw new CouchbaseDataException(result);

            case ResponseStatus.ClientFailure:
            case ResponseStatus.OperationTimeout:
                throw new CouchbaseClientException(result, result.Document.Id);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#3
0
        /// <summary>
        /// Creates a new CouchbaseKeyValueResponseException.
        /// </summary>
        /// <param name="result">Result from Couchbase</param>
        internal static CouchbaseKeyValueResponseException FromResult(IDocumentResult result)

        {
            return(new CouchbaseKeyValueResponseException(
                       ExceptionUtil.GetResponseExceptionMessage(result.Message, result.Status),
                       result.Status, result.Exception));
        }
示例#4
0
 private static void CheckResultForError <T>(IDocumentResult <T> result)
 {
     if (!result.Success)
     {
         throw new CouchbaseGetDocumentException <T>(result);
     }
 }
示例#5
0
        public void UpsertWeirdness()
        {
            var id    = Guid.NewGuid().ToString();
            var pizza = new Pizza {
                SizeInches = 14, Toppings = new List <string> {
                    "Pepperoni", "Mushroom"
                }, ExtraCheese = true
            };

            // upsert with CAS - completely new doc
            var upsertNewDoc = new Document <Pizza>
            {
                Id      = id,
                Content = pizza,
                Cas     = 12345         // this is a completely new document, so what does CAS mean?
            };
            IDocumentResult <Pizza> upsertNewResult =
                Bucket.Upsert(upsertNewDoc);

            // if a CAS value is present, upsert == replace
            // since this is a brand new document, it will fail
            // because document can't be found
            Assert.That(upsertNewResult.Exception, Is.Not.Null);
            Assert.That(upsertNewResult.Success, Is.False);
        }
示例#6
0
        public static void ThrowIfFailure(this IDocumentResult result)
        {
            if (result.Success)
            {
                return;
            }

            result.EnsureSuccess();
        }
示例#7
0
        internal CouchbaseGetDocumentException(IDocumentResult <T> documentResult)
            : base(documentResult.Status, "Couchbase Get operation returned an error: " + documentResult.Message, documentResult.Exception)
        {
            if (documentResult == null)
            {
                throw new ArgumentNullException("documentResult");
            }

            _documentResult = documentResult;
        }
示例#8
0
        async Task <bool> IProductService.UpsertProduct(IProductBucketProvider productBucket, ProductUpdateInputModel productUpdate)
        {
            IDocumentResult upsertResult = await productBucket.GetBucket().UpsertAsync(new Document <ProductDO>
            {
                Id      = productUpdate.Id,
                Content = new ProductDO(productUpdate.Name, productUpdate.Price)
            });

            return(upsertResult.Success);
        }
        /// <summary>
        /// Throws a <see cref="CouchbaseKeyValueResponseException"/> on any error.
        /// </summary>
        /// <param name="result">The result.</param>
        public static void EnsureSuccess(this IDocumentResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (!result.Success)
            {
                throw CouchbaseKeyValueResponseException.FromResult(result);
            }
        }
        public void Setup()
        {
            this._searchParameters = new List <ISearchParameter>();

            this._result = new DocumentResult <TestDocument>();

            // Data using http://www.json-generator.com/
            var assembly      = typeof(DocumentResultBenchmarks).GetTypeInfo().Assembly;
            var jsonPlainText = EmbeddedResourceHelper.GetByName(assembly, $"SolrExpress.Benchmarks.Solr4.Search.Result.DocumentResultBenchmarks{this.ElementsCount}.json");

            this._jsonStream = new MemoryStream(Encoding.GetEncoding(0).GetBytes(jsonPlainText));
        }
示例#11
0
        async Task <ProductModel> IProductService.GetProduct(IProductBucketProvider productBucket, string id)
        {
            IDocumentResult <ProductDO> productDO = await productBucket.GetBucket().GetDocumentAsync <ProductDO>(id);

            if (productDO.Success)
            {
                return(ProductModel.FromProductDO(productDO.Id, productDO.Content));
            }
            else
            {
                return(null);
            }
        }
 /// <summary>
 /// Logs the reason why an operation fails and throws and exception if <see cref="ThrowOnError"/> is
 /// <c>true</c> and logging the issue as WARN.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="key">The key.</param>
 /// <exception cref="InvalidOperationException"></exception>
 private void LogAndOrThrow(IDocumentResult result, string key)
 {
     if (result.Exception != null)
     {
         LogAndOrThrow(result.Exception, key);
         return;
     }
     _log.Error($"Could not retrieve, remove or write key '{key}' - reason: {result.Status}");
     if (ThrowOnError)
     {
         throw new InvalidOperationException(result.Status.ToString());
     }
 }
示例#13
0
        async Task <List <ProductModel> > IProductService.GetAllProducts(IProductBucketProvider productBucket)
        {
            IQueryable <string> allProducts = (from productDO in new BucketContext(productBucket.GetBucket()).Query <string>()
                                               select N1QlFunctions.Meta(productDO).Id);
            List <ProductModel> products = new List <ProductModel>();

            foreach (string productId in allProducts)
            {
                IDocumentResult <ProductDO> productDO = await productBucket.GetBucket().GetDocumentAsync <ProductDO>(productId);

                products.Add(ProductModel.FromProductDO(productId, productDO.Content));
            }
            return(products);
        }
        public override TEntity Update(TEntity entity)
        {
            ActionFilterExecuter.ExecuteModificationAuditFilter <TEntity, string>(entity);

            IDocumentResult <TEntity> result = Session.Bucket.Upsert(new Document <TEntity>
            {
                Content = entity,
                Id      = $"{typeof(TEntity).Name}:{entity.Id}"
            });

            result.EnsureSuccess();

            return(result.Content);
        }
        public override TEntity Insert(TEntity entity)
        {
            entity.Id = GuidGenerator.Create().ToString("N");
            ActionFilterExecuter.ExecuteCreationAuditFilter <TEntity, string>(entity);

            IDocumentResult <TEntity> result = Session.Bucket.Insert(new Document <TEntity>
            {
                Content = entity,
                Id      = $"{typeof(TEntity).Name}:{entity.Id}"
            });

            result.EnsureSuccess();

            return(result.Content);
        }
        /// <summary>
        /// Initialises a new instance of the <see cref="Solution" /> class.
        /// </summary>
        internal Solution(
            ISolutionResult solutionResult,
            IEnumerable <ISolutionCapabilityListResult> solutionCapabilityListResult,
            IEnumerable <IMarketingContactResult> contactResult,
            ISolutionSupplierResult solutionSupplierResult,
            IDocumentResult documentResult,
            IEnumerable <ISolutionEpicListResult> solutionEpicListResults)
        {
            var contactResultList         = contactResult.ToList();
            var solutionEpicsByCapability = solutionEpicListResults?.ToLookup(e => e.CapabilityId);

            Id          = solutionResult.Id;
            Name        = solutionResult.Name;
            LastUpdated = GetLatestLastUpdated(solutionResult, contactResultList);
            Summary     = solutionResult.Summary;
            Description = solutionResult.Description;
            Features    = string.IsNullOrWhiteSpace(solutionResult.Features)
                ? new List <string>()
                : JsonConvert.DeserializeObject <IEnumerable <string> >(solutionResult.Features);
            Integrations = new Integrations
            {
                Url = solutionResult.IntegrationsUrl, DocumentName = documentResult?.IntegrationDocumentName
            };
            ImplementationTimescales =
                new ImplementationTimescales {
                Description = solutionResult.ImplementationTimescales
            };
            AboutUrl = solutionResult.AboutUrl;
            RoadMap  = new RoadMap
            {
                Summary = solutionResult.RoadMap, DocumentName = documentResult?.RoadMapDocumentName
            };
            ClientApplication = string.IsNullOrWhiteSpace(solutionResult.ClientApplication)
                ? new ClientApplication()
                : JsonConvert.DeserializeObject <ClientApplication>(solutionResult.ClientApplication);
            IsFoundation = solutionResult.IsFoundation;
            Capabilities = solutionCapabilityListResult.Select(c =>
                                                               new ClaimedCapability(c, solutionEpicsByCapability?[c.CapabilityId]));
            Contacts        = contactResultList.Select(c => new Contact(c));
            PublishedStatus = solutionResult.PublishedStatus;

            Hosting = string.IsNullOrWhiteSpace(solutionResult.Hosting)
                ? new Hosting()
                : JsonConvert.DeserializeObject <Hosting>(solutionResult.Hosting);
            Supplier = solutionSupplierResult != null ? new SolutionSupplier(solutionSupplierResult) : new SolutionSupplier();

            SolutionDocument = new SolutionDocument(documentResult?.SolutionDocumentName);
        }
        public override TEntity Update(TEntity entity)
        {
            ActionFilterExecuter.ExecuteModificationAuditFilter<TEntity, string>(entity);

            EntityChangeEventHelper.PublishEntityUpdatingEvent(entity);

            IDocumentResult<TEntity> result = Session.Bucket.Upsert(new Document<TEntity>
            {
                Content = entity,
                Id = $"{typeof(TEntity).Name}:{entity.Id}"
            });

            result.EnsureSuccess();

            EntityChangeEventHelper.PublishEntityUpdatedEventOnUowCompleted(entity);

            return result.Content;
        }
示例#18
0
        public void WhereCanIUseCas()
        {
            // insert a new document
            var id    = Guid.NewGuid().ToString();
            var pizza = new Pizza {
                SizeInches = 14, Toppings = new List <string> {
                    "Pepperoni", "Mushroom"
                }, ExtraCheese = true
            };

            Bucket.Insert(id, pizza);

            // get document with CAS
            IOperationResult <Pizza> getResult = Bucket.Get <Pizza>(id);

            Assert.That(getResult.Cas, Is.GreaterThan(0));

            // replace with CAS
            pizza.ExtraCheese = false;
            var replaceDoc = new Document <Pizza>
            {
                Id      = id,
                Content = pizza,
                Cas     = getResult.Cas
            };
            IDocumentResult <Pizza> replaceResult = Bucket.Replace(replaceDoc);

            Assert.That(replaceResult.Document.Cas,
                        Is.GreaterThan(0));
            Assert.That(replaceResult.Document.Cas,
                        Is.Not.EqualTo(getResult.Cas));

            // upsert with CAS
            pizza.ExtraCheese = true;
            var upsertDoc = new Document <Pizza>
            {
                Id      = id,
                Content = pizza,
                Cas     = replaceDoc.Cas
            };
            IDocumentResult <Pizza> upsertResult = Bucket.Upsert(upsertDoc);

            Assert.That(upsertResult.Success, Is.True);
        }
        public override TEntity Insert(TEntity entity)
        {
            entity.Id = GuidGenerator.Create().ToString("N");
            ActionFilterExecuter.ExecuteCreationAuditFilter<TEntity, string>(entity);

            EntityChangeEventHelper.PublishEntityCreatingEvent(entity);

            IDocumentResult<TEntity> result = Session.Bucket.Insert(new Document<TEntity>
            {
                Content = entity,
                Id = $"{typeof(TEntity).Name}:{entity.Id}"
            });

            result.EnsureSuccess();

            EntityChangeEventHelper.PublishEntityCreatedEventOnUowCompleted(entity);

            return result.Content;
        }
示例#20
0
        private static void WriteToFile(IDocumentResult result, PSDocumentOption option, IPipelineWriter writer, ShouldProcess shouldProcess)
        {
            var rootedPath = PSDocumentOption.GetRootedPath(option.Output.Path);
            var filePath   = !string.IsNullOrEmpty(result.Culture) && option.Output?.Culture?.Length > 1 ?
                             Path.Combine(rootedPath, result.Culture, result.Name) : Path.Combine(rootedPath, result.Name);
            var parentPath = Directory.GetParent(filePath);

            if (!parentPath.Exists && shouldProcess(target: parentPath.FullName, action: PSDocsResources.ShouldCreatePath))
            {
                Directory.CreateDirectory(path: parentPath.FullName);
            }
            if (shouldProcess(target: rootedPath, action: PSDocsResources.ShouldWriteFile))
            {
                var encoding = GetEncoding(option.Markdown.Encoding.Value);
                File.WriteAllText(filePath, result.ToString(), encoding);

                // Write file info instead
                var fileInfo = new FileInfo(filePath);
                writer.WriteObject(fileInfo, false);
            }
        }
        public override JobData GetJobData(string jobId)
        {
            if (jobId == null)
            {
                throw new ArgumentNullException(nameof(jobId));
            }

            IDocumentResult <Documents.Job> result = bucket.GetDocument <Documents.Job>(jobId);

            if (result.Success && result.Content != null)
            {
                Documents.Job  data           = result.Content;
                InvocationData invocationData = data.InvocationData;
                invocationData.Arguments = data.Arguments;

                Common.Job       job           = null;
                JobLoadException loadException = null;

                try
                {
                    job = invocationData.Deserialize();
                }
                catch (JobLoadException ex)
                {
                    loadException = ex;
                }

                return(new JobData
                {
                    Job = job,
                    State = data.StateName,
                    CreatedAt = data.CreatedOn,
                    LoadException = loadException
                });
            }

            return(null);
        }
        public virtual async Task <bool> DebitAccount(int accountID, TransactionRecord transactionRecord)
        {
            //IBucket bucket = await ClusterHelper.GetBucketAsync("Bank");
            var miniStatement = await GetTransactionStatement(accountID);

            var transactions = miniStatement.Transactions.ToList();

            transactions.Add(transactionRecord);
            miniStatement.Transactions = transactions;
            Document <MiniStatement> document = new Document <MiniStatement>
            {
                Id      = miniStatement.AccountID.ToString(),
                Content = miniStatement
            };
            IDocumentResult <MiniStatement> upsert = await bucket.UpsertAsync(document);

            if (!upsert.Success)
            {
                return(false);
                //throw upsert.Exception;
            }
            return(true);
        }
示例#23
0
        private static void WriteToFile(IDocumentResult result, PSDocumentOption option, IPipelineWriter writer, ShouldProcess shouldProcess)
        {
            // Calculate paths
            var fileName   = string.Concat(result.InstanceName, result.Extension);
            var outputPath = PSDocumentOption.GetRootedPath(result.OutputPath);
            var filePath   = Path.Combine(outputPath, fileName);
            var parentPath = Directory.GetParent(filePath);

            if (!parentPath.Exists && shouldProcess(target: parentPath.FullName, action: PSDocsResources.ShouldCreatePath))
            {
                Directory.CreateDirectory(path: parentPath.FullName);
            }

            if (shouldProcess(target: outputPath, action: PSDocsResources.ShouldWriteFile))
            {
                var encoding = GetEncoding(option.Markdown.Encoding.Value);
                File.WriteAllText(filePath, result.ToString(), encoding);

                // Write file info instead
                var fileInfo = new FileInfo(filePath);
                writer.WriteObject(fileInfo, false);
            }
        }
 public CouchbaseException(IDocumentResult result)
     : this(result.Message, result.Exception)
 {
     Status = result.Status;
 }
 public CouchbaseAuthenticationException(IDocumentResult result)
     : base(result)
 {
 }
 public DocumentExistsException(IDocumentResult result, string key)
     : base(result, key)
 {
 }
示例#27
0
 public CouchbaseServerException(IDocumentResult result, string key)
     : base(result, key)
 {
 }
示例#28
0
 public CouchbaseAuthenticationException(IDocumentResult result)
     : base(result)
 {
 }
示例#29
0
 public DocumentNotFoundException(IDocumentResult result, string key)
     : base(result, key)
 {
 }
 public CouchbaseClientException(IDocumentResult result, string key)
     : base(result, key)
 {
 }
示例#31
0
 private static void WriteToString(IDocumentResult result, bool enumerate, IPipelineWriter writer)
 {
     writer.WriteObject(result.ToString(), enumerate);
 }
 public CouchbaseException(IDocumentResult result, string key)
     : this(result.Message, result.Exception)
 {
     Status = result.Status;
     Key    = key;
 }
 public CouchbaseDataException(IDocumentResult result, string key)
     : this(result.Message, result.Exception)
 {
     Status = result.Status;
     Key = key;
 }
 public CouchbaseDataException(IDocumentResult result)
     : this(result.Message, result.Exception)
 {
     Status = result.Status;
 }
        private void Acquire(TimeSpan timeout)
        {
            logger.Trace($"Trying to acquire lock for {resource} within {timeout.TotalSeconds} seconds");

            System.Diagnostics.Stopwatch acquireStart = new System.Diagnostics.Stopwatch();
            acquireStart.Start();

            string id = $"{resource}:{DocumentTypes.Lock}".GenerateHash();

            while (string.IsNullOrEmpty(resourceId))
            {
                // default ttl for lock document
                TimeSpan ttl = DateTime.UtcNow.Add(timeout).AddMinutes(1).TimeOfDay;

                // read the document
                IDocumentResult <Lock> document = bucket.GetDocument <Lock>(id);

                // false means the document does not exists got ahead and create
                if (document.Success == false)
                {
                    Lock @lock = new Lock
                    {
                        Id       = id,
                        Name     = resource,
                        ExpireOn = DateTime.UtcNow.Add(timeout).ToEpoch()
                    };

                    IOperationResult <Lock> result = bucket.Insert(@lock.Id, @lock, ttl);
                    if (result.Success)
                    {
                        resourceId = id;
                        break;
                    }
                }
                else if (document.Content != null)
                {
                    if (document.Content.ExpireOn < DateTime.UtcNow.ToEpoch())
                    {
                        IDocumentFragment <Lock> result = bucket.MutateIn <Lock>(id)
                                                          .WithCas(document.Document.Cas)
                                                          .WithExpiry(ttl)
                                                          .Upsert(l => l.ExpireOn, DateTime.UtcNow.Add(timeout).ToEpoch(), false)
                                                          .Execute();

                        if (result.Success)
                        {
                            resourceId = id;
                            break;
                        }
                    }
                }

                // check the timeout
                if (acquireStart.ElapsedMilliseconds > timeout.TotalMilliseconds)
                {
                    throw new CouchbaseDistributedLockException($"Could not place a lock on the resource '{resource}': Lock timeout.");
                }

                // sleep for 2000 millisecond
                logger.Trace($"Unable to acquire lock for {resource}. Will check try after 2 seconds");
                System.Threading.Thread.Sleep(2000);
            }

            logger.Trace($"Acquired lock for {resource} in {acquireStart.Elapsed.TotalSeconds} seconds");
        }
 public DocumentNotFoundException(IDocumentResult result, string key)
     : base(result, key)
 {
 }