private async Task GetDocumentsLink()
        {
            var docLink = await _collectionProvider.GetCollectionDocumentsLink();

            Assert.NotNull(docLink);

            Assert.NotNull(
                _documentClient.CreateDocumentCollectionQuery(
                    UriFactory.CreateDatabaseUri(_databaseId))
                .ToList()
                .FirstOrDefault(c => c.DocumentsLink == docLink));
        }
示例#2
0
        public static Task <DocumentCollection> GetOrAddDocumentCollection(string collectionId, IDocumentClient client, Database database, CancellationToken token, int throughput, int?timeToLive, Func <string, DocumentCollection> factory = null)
        {
            return(Policy
                   .Handle <DocumentClientException>(e => { return true; })
                   .WaitAndRetryForeverAsync(attempt => TimeSpan.FromSeconds(1 << Math.Min(attempt, 3)))
                   .ExecuteAsync(async() =>
            {
                token.ThrowIfCancellationRequested();
                var query = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).AsDocumentQuery();

                if (query.HasMoreResults)
                {
                    var res = await query.ExecuteNextAsync <DocumentCollection>();
                    if (res.Any())
                    {
                        return res.First();
                    }
                }

                var collection = factory == null ? new DocumentCollection {
                    Id = collectionId
                } : factory(collectionId);


                collection.DefaultTimeToLive = timeToLive <= 0 ? -1 : timeToLive * 60 * 60 * 24;     // expire all documents after timeToLive no of days. -1 indicates never expire

                throughput = throughput == 0 ? 400 : throughput;

                return (await client.CreateDocumentCollectionAsync(database.SelfLink, collection, new RequestOptions {
                    OfferThroughput = throughput
                }).ConfigureAwait(false)).Resource;
            }));
        }
示例#3
0
        public static async Task <DocumentCollection> EnsureDatabaseAndCollection(this IDocumentClient client, string dbId, string collectionId, string[] partitionKeys = null)
        {
            var db = client.CreateDatabaseQuery().Where(d => d.Id == dbId).AsEnumerable().FirstOrDefault()
                     ?? await client.CreateDatabaseAsync(new Database()
            {
                Id = dbId
            });

            var collection = client.CreateDocumentCollectionQuery(db.SelfLink)
                             .Where(c => c.Id == collectionId).AsEnumerable().FirstOrDefault();

            if (collection == null)
            {
                var collectionDefinition = new DocumentCollection()
                {
                    Id = collectionId
                };
                if (partitionKeys != null && partitionKeys.Length > 0)
                {
                    foreach (var partitionKey in partitionKeys)
                    {
                        collectionDefinition.PartitionKey.Paths.Add(partitionKey);
                    }
                }

                collection = await client.CreateDocumentCollectionAsync(db.SelfLink, collectionDefinition);
            }

            return(collection);
        }
示例#4
0
        private async Task SetupUserSettingsCollection()
        {
            var collectionName = typeof(Models.UserSettings).Name;
            var databaseUri    = UriFactory.CreateDatabaseUri(_configuration.DatabaseId);

            var collection = _client.CreateDocumentCollectionQuery(databaseUri)
                             .Where(c => c.Id == collectionName)
                             .AsEnumerable()
                             .FirstOrDefault();

            if (collection == null)
            {
                collection = new DocumentCollection
                {
                    Id             = collectionName,
                    IndexingPolicy = { IndexingMode = IndexingMode.Consistent }
                };

                collection.IndexingPolicy.IncludedPaths.Add(
                    new IncludedPath
                {
                    Path    = "/",
                    Indexes = new Collection <Index>
                    {
                        Index.Hash(DataType.String, -1)
                    }
                });

                var codeProperty = nameof(Models.UserSettings.UserId);
                collection.IndexingPolicy.IncludedPaths.Add(
                    new IncludedPath
                {
                    Path    = $"/\"{codeProperty}\"/?",
                    Indexes = new Collection <Index>
                    {
                        Index.Hash(DataType.String, -1)
                    }
                });

                var requestOptions = new RequestOptions
                {
                    OfferThroughput = _configuration.DefaultRUs
                };
                await _client.CreateDocumentCollectionAsync(databaseUri, collection, requestOptions);
            }
        }
示例#5
0
        public void Migrate(IEnumerable <string> documentcollection)
        {
            var database     = _configuration.GetSection("documentdb").GetSection("source").GetSection("database").Value;
            var db           = _documentClient.CreateDatabaseQuery().ToList().FirstOrDefault(x => x.Id == database);
            var colls        = _documentClient.CreateDocumentCollectionQuery(db.CollectionsLink).ToList();
            var migratecolls = colls.Where(z => documentcollection.Contains(z.Id, StringComparer.InvariantCultureIgnoreCase));

            Parse(migratecolls);
        }
        /// <summary>
        /// Returns a refernce to a collection with a DocumentDb database, or
        /// creates if it does not exist
        /// </summary>
        /// <param name="Client">DocumentDb client connection</param>
        /// <param name="db">Reference to the containing DocumentDb database</param>
        /// <param name="collectionId">The Id of the Collection to return a reference for</param>
        /// <param name="collectionSpec">Specifications for the Collection (used to create if it does not exist)</param>
        /// <returns></returns>
        public static async Task <DocumentCollection> GetOrCreateCollectionAsync(IDocumentClient Client,
                                                                                 Database db, string collectionId, DocumentCollectionSpec collectionSpec = null)
        {
            DocumentCollection collection = Client.CreateDocumentCollectionQuery(db.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();

            if (collection == null)
            {
                collection = await CreateNewCollection(Client, db, collectionId, collectionSpec);
            }
            return(collection);
        }
示例#7
0
        /// <summary>
        /// Gets the all document collections in the database.
        /// </summary>
        /// <param name="dbId">Database id.</param>
        /// <param name="feedOptions">Feed options</param>
        /// <returns>All document collections in the database.</returns>
        public async Task <IReadOnlyList <DocumentCollection> > GetAllCollectionsAsync(
            string dbId, FeedOptions feedOptions = null)
        {
            Code.ExpectsNotNullOrWhiteSpaceArgument(dbId, nameof(dbId), TaggingUtilities.ReserveTag(0x2381b1d7 /* tag_961hx */));

            IDocumentClient client = await GetDocumentClientAsync().ConfigureAwait(false);

            using (IDocumentQuery <DocumentCollection> query =
                       client.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(dbId), feedOptions).AsDocumentQuery())
            {
                return(await QueryDocumentsAsync(query).ConfigureAwait(false));
            }
        }
示例#8
0
        public DocumentCollection CreateDocumentCollectionQuery(string collectionId, FeedOptions options = null)
        {
            if (options == null)
                options = new FeedOptions
                {
                    MaxItemCount = 1
                };

            var databaseUri = UriFactory.CreateDatabaseUri(databaseId);

            return documentClient.CreateDocumentCollectionQuery(databaseUri, options)
                .Where(c => c.Id == collectionId).AsEnumerable().FirstOrDefault();
        }
        private async Task <DocumentCollection> GetOrCreateCollection()
        {
            var collectionName = typeof(T).Name;

            var collection = _client
                             .CreateDocumentCollectionQuery(_database.SelfLink)
                             .AsEnumerable()
                             .FirstOrDefault(c => c.Id == collectionName);

            return(collection ??
                   await _client.CreateDocumentCollectionAsync(
                       _database.SelfLink,
                       new DocumentCollection { Id = collectionName }));
        }
        public async Task <DocumentCollection> CreateOrGetCollection()
        {
            var collection =
                _documentClient.CreateDocumentCollectionQuery(
                    databaseLink: await _databaseProvider.GetDbSelfLink()
                    )
                .Where(c => c.Id == GetCollectionId())
                .AsEnumerable()
                .FirstOrDefault();

            return(collection ??
                   await _documentClient.CreateDocumentCollectionAsync(
                       await _databaseProvider.GetDbSelfLink(),
                       new DocumentCollection { Id = GetCollectionId() }));
        }
        private async Task <DocumentCollection> GetOrCreateCollectionAsync()
        {
            DocumentCollection collection = _client.CreateDocumentCollectionQuery((await _database).SelfLink).Where(c => c.Id == _collectionName).ToArray().FirstOrDefault();

            if (collection == null)
            {
                collection = new DocumentCollection {
                    Id = _collectionName
                };

                collection = await _client.CreateDocumentCollectionAsync((await _database).SelfLink, collection);
            }

            return(collection);
        }
示例#12
0
        private static void ListCollections(IDocumentClient client)
        {
            Console.WriteLine(">>> View Collections in mydb <<<");

            List <DocumentCollection> collections = client.CreateDocumentCollectionQuery(MyDbDatabaseUri).ToList();

            int count = 0;

            foreach (DocumentCollection collection in collections)
            {
                count++;
                Console.WriteLine();
                Console.WriteLine($" Collection #{count}");

                PrintCollection(collection);
            }

            Console.WriteLine($"Total collections in mydb database: {collections.Count}");
        }
示例#13
0
        public async Task <bool> EnsureCreatedAsync(Type entityType,
                                                    Database database,
                                                    int collectionThroughput,
                                                    IndexingPolicy indexingPolicy = null)
        {
            var collectionName = entityType.GetCollectionName();
            var collection     = _documentClient
                                 .CreateDocumentCollectionQuery(database.SelfLink)
                                 .ToArray()
                                 .FirstOrDefault(c => c.Id == collectionName);

            if (collection != null)
            {
                return(true);
            }

            collection = new DocumentCollection
            {
                Id = collectionName
            };
            var partitionKey = entityType.GetPartitionKeyForEntity();

            if (partitionKey != null)
            {
                collection.PartitionKey = partitionKey;
            }

            if (indexingPolicy != null)
            {
                collection.IndexingPolicy = indexingPolicy;
            }

            collection = await _documentClient.CreateDocumentCollectionAsync(database.SelfLink, collection, new RequestOptions
            {
                OfferThroughput = collectionThroughput
            });

            return(collection != null);
        }
        private static async Task DeleteCollection(IDocumentClient client)
        {
            Console.WriteLine();
            Console.WriteLine($"**** Delete Collection { CollectionId } in { DatabaseId } ****");

            var query = new SqlQuerySpec
            {
                QueryText  = "SELECT * FROM c WHERE c.id = @id",
                Parameters = new SqlParameterCollection
                {
                    new SqlParameter {
                        Name = "@id", Value = CollectionId
                    }
                }
            };

            DocumentCollection collection = client.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(DatabaseId), query).AsEnumerable().First();

            await client.DeleteDocumentCollectionAsync(collection.SelfLink);

            Console.WriteLine($"Deleted collection {collection.Id} from database {DatabaseId}");
        }
示例#15
0
        public static async Task <DocumentCollection> GetDocumentCollection(string collectionId, IDocumentClient client,
                                                                            Database database, CancellationToken token)
        {
            DocumentCollection documentCollection = null;
            var query = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).AsDocumentQuery();

            if (query.HasMoreResults)
            {
                var res = await query.ExecuteNextAsync <DocumentCollection>();

                if (res.Any())
                {
                    return(res.First());
                }
                else
                {
                    return(documentCollection);
                }
            }
            else
            {
                return(documentCollection);
            }
        }
示例#16
0
        public async Task ScaleDownAll()
        {
            var databases = _documentClient.CreateDatabaseQuery().AsEnumerable().ToList();

            foreach (var database in databases)
            {
                var offer = await _documentClient.GetOfferFromSelfLinkAsync(database.SelfLink);

                if (offer != null)
                {
                    await _documentClient.ScaleAsync(offer, _config.ScaleDownBatch, _config.MinThroughput, _config.MaxThroughput);
                }
                else
                {
                    var collections = _documentClient.CreateDocumentCollectionQuery(database.SelfLink).ToList();
                    foreach (var collection in collections)
                    {
                        offer = await _documentClient.GetOfferFromSelfLinkAsync(collection.SelfLink);

                        await _documentClient.ScaleAsync(offer, _config.ScaleDownBatch, _config.MinThroughput, _config.MaxThroughput);
                    }
                }
            }
        }
示例#17
0
        public async Task <DocumentCollection[]> GetCollections(FeedOptions feedOptions = null)
        {
            var collections = _client.CreateDocumentCollectionQuery(await SelfLinkAsync(), feedOptions);

            return(collections.ToArray());
        }