public async Task <ResourceResponse <DocumentCollection> > CreateCollectionIfNotExistsAsync(
            string databaseName,
            string id,
            string partitionKeyName = null)
        {
            RangeIndex         index          = Index.Range(DataType.String, -1);
            DocumentCollection collectionInfo = new DocumentCollection
            {
                IndexingPolicy = new IndexingPolicy(new Index[] { index }),
                Id             = id,
            };

            if (!string.IsNullOrEmpty(partitionKeyName))
            {
                collectionInfo.PartitionKey = new PartitionKeyDefinition
                {
                    Paths = new Collection <string> {
                        $"/{partitionKeyName}"
                    },
                };
            }

            // Azure Cosmos DB collections can be reserved with
            // throughput specified in request units/second.
            RequestOptions requestOptions = new RequestOptions
            {
                OfferThroughput  = this.storageThroughput,
                ConsistencyLevel = ConsistencyLevel.Strong,
            };
            string dbUrl = "/dbs/" + databaseName;

            try
            {
                await this.CreateDatabaseIfNotExistsAsync(databaseName);
            }
            catch (Exception e)
            {
                throw new Exception($"While attempting to create collection {id}, an error occured while attepmting to create its database {databaseName}.", e);
            }

            ResourceResponse <DocumentCollection> response;

            try
            {
                response = await this.client.CreateDocumentCollectionIfNotExistsAsync(
                    dbUrl,
                    collectionInfo,
                    requestOptions);
            }
            catch (Exception e)
            {
                this.logger.LogError(e, "Error creating collection with ID {id}, database URL {databaseUrl}, and collection info {collectionInfo}", id, dbUrl, collectionInfo);
                throw;
            }

            return(response);
        }
        static async Task Main(string[] args)
        {
            // This is my simple testable wrapper around the
            var client = new DocumentClient(new Uri("https://localhost:8081"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", JsonConvert.DefaultSettings());

            var cosmosDb = new CosmosDbBuilder()
                           .WithId("upsertFailure")
                           .AddCollection <DateTimeError>("datetimeerror", builder =>
            {
                builder.IncludeIndexPath("/*", Index.Range(DataType.Number, -1), Index.Range(DataType.String, -1));
            })
                           .Build(client);

            var repo = cosmosDb.Repository <DateTimeError>();

            var orig = new DateTimeError
            {
                Id   = Guid.NewGuid(),
                Date = DateTimeOffset.UtcNow
            };

            // round the time to hundredths of a second to expose formatting problems
            orig.Date = new DateTimeOffset(orig.Date.Ticks - orig.Date.Ticks % (TimeSpan.TicksPerSecond / 100), TimeSpan.Zero);

            await repo.AddAsync(orig);

            var successfulFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            successfulFind.Should().BeEquivalentTo(orig);

            await repo.UpsertAsync(orig);

            var unsuccessfulUpsertFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            unsuccessfulUpsertFind.Should().BeNull();

            await repo.ReplaceAsync(orig);

            var unsuccessfulReplaceFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            unsuccessfulReplaceFind.Should().BeNull();

            var successfulGet = await repo.GetAsync(orig.Id);

            successfulGet.Should().BeEquivalentTo(orig);
        }
예제 #3
0
        public async Task InitializeAsync(CancellationToken ct = default)
        {
            await documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseId });

            await documentClient.CreateDocumentCollectionIfNotExistsAsync(databaseUri,
                                                                          new DocumentCollection
            {
                PartitionKey = new PartitionKeyDefinition
                {
                    Paths = new Collection <string>
                    {
                        "/PartitionId"
                    }
                },
                Id = Constants.LeaseCollection
            });

            await documentClient.CreateDocumentCollectionIfNotExistsAsync(databaseUri,
                                                                          new DocumentCollection
            {
                PartitionKey = new PartitionKeyDefinition
                {
                    Paths = new Collection <string>
                    {
                        "/eventStream"
                    }
                },
                IndexingPolicy = new IndexingPolicy
                {
                    IncludedPaths = new Collection <IncludedPath>
                    {
                        new IncludedPath
                        {
                            Path    = "/*",
                            Indexes = new Collection <Index>
                            {
                                Index.Range(DataType.Number),
                                Index.Range(DataType.String)
                            }
                        }
                    }
                },
                UniqueKeyPolicy = new UniqueKeyPolicy
                {
                    UniqueKeys = new Collection <UniqueKey>
                    {
                        new UniqueKey
                        {
                            Paths = new Collection <string>
                            {
                                "/eventStream",
                                "/eventStreamOffset"
                            }
                        }
                    }
                },
                Id = Constants.Collection
            },
                                                                          new RequestOptions
            {
                PartitionKey = new PartitionKey("/eventStream")
            });
        }