private static async Task <bool> CheckList(IDocumentClient client, string link) { var CreateDatabase = Environment.GetEnvironmentVariable("CreateDatabase"); if (CreateDatabase != null && CreateDatabase == "true") { var databaseDefinition = new Database { Id = DatabaseId }; await client.CreateDatabaseIfNotExistsAsync(databaseDefinition); var collectionDefinition = new DocumentCollection { Id = CollectionId }; await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseId), collectionDefinition); } var response = client.CreateDocumentQuery <Item>(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), $"select * from c WHERE c.Url='{link}'").ToList(); if (response.Count > 0) { return(true); } await client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), new Item() { Url = link }); return(false); }
private async Task BuildCollection() { await _documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseId }); await _documentClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseId), new DocumentCollection { Id = collectionId }); }
public async Task InitialiseAsync() { await _documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = _options.Value.Database }) .ConfigureAwait(false); await CreateWorkerLeasesCollection(); await CreateLeaseRequestsCollection(); }
internal async Task <IDocumentClient> InitialiseAsync(IDocumentClient documentClient, CosmosDataStoreOptions cosmosDataStoreOptions) { await documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = cosmosDataStoreOptions.Database }); await CreateLockClaimsCollection(documentClient, cosmosDataStoreOptions); return(documentClient); }
private async Task <DocumentCollection> EnsureCollectionIsCreated(IDocumentClient documentClient) { await documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseId }); ResourceResponse <DocumentCollection> collectionResponse = await documentClient .CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseId), new DocumentCollection { Id = CollectionId }); return(collectionResponse.Resource); }
private async Task EnsureDatabaseAsync() { var database = new Database { Id = _configs.DatabaseId }; await _client.CreateDatabaseIfNotExistsAsync(database); }
public static async Task CreateCosmosDatabaseIfNotExists(this IDocumentClient documentClient, ILogger logger, string databaseId) { logger.Info($"Creating Cosmos Db if not exists with id {databaseId}"); var database = new Database { Id = databaseId }; await documentClient.CreateDatabaseIfNotExistsAsync(database); logger.Info($"Created Cosmos Db with id {databaseId}"); }
public async Task <Database> CreateDatabaseIfNotExistsAsync(IDocumentClient client) { Throw.IfNull(client, nameof(client)); var db = new Database { Id = _settings.DatabaseId }; return(await client.CreateDatabaseIfNotExistsAsync(db)); }
/// <summary> /// Gets or creates the database. /// </summary> /// <param name="database">Database to create or get.</param> /// <param name="requestOptions">Request options.</param> /// <returns>Database with specified database id.</returns> public async Task <ResourceResponse <Database> > GetOrCreateDatabaseAsync( Database database, RequestOptions requestOptions = null) { Code.ExpectsArgument(database, nameof(database), TaggingUtilities.ReserveTag(0x2381b1c8 /* tag_961hi */)); IDocumentClient client = await GetDocumentClientAsync().ConfigureAwait(false); return(await DocumentDbAdapter.ExecuteAndLogAsync(TaggingUtilities.ReserveTag(0x2381b1c9 /* tag_961hj */), () => client.CreateDatabaseIfNotExistsAsync(database, requestOptions)).ConfigureAwait(false)); }
public DocumentClientInitializerTests() { var documentClientTestProvider = Substitute.For <IDocumentClientTestProvider>(); _documentClientInitializer = new DocumentClientInitializer(documentClientTestProvider, NullLogger <DocumentClientInitializer> .Instance); _collectionInitializers = new List <ICollectionInitializer> { _collectionInitializer1, _collectionInitializer2 }; _documentClient.CreateDatabaseIfNotExistsAsync(Arg.Any <Database>(), Arg.Any <RequestOptions>()).Returns(Substitute.For <ResourceResponse <Database> >()); }
/// <summary> /// Ensures that the necessary database and collection exist with the proper indexing policy and stored procedures /// </summary> /// <param name="documentClient">The <see cref="DocumentClient"/> instance to use for initialization.</param> /// <param name="cosmosDataStoreConfiguration">The data store configuration.</param> /// <returns>A task</returns> public async Task InitializeDataStore(IDocumentClient documentClient, CosmosDataStoreConfiguration cosmosDataStoreConfiguration) { EnsureArg.IsNotNull(documentClient, nameof(documentClient)); EnsureArg.IsNotNull(cosmosDataStoreConfiguration, nameof(cosmosDataStoreConfiguration)); try { _logger.LogInformation("Initializing Cosmos DB collection {CollectionUri}", cosmosDataStoreConfiguration.AbsoluteCollectionUri); if (cosmosDataStoreConfiguration.AllowDatabaseCreation) { _logger.LogDebug("CreateDatabaseIfNotExists {DatabaseId})", cosmosDataStoreConfiguration.DatabaseId); await documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = cosmosDataStoreConfiguration.DatabaseId, }); } _logger.LogDebug("CreateDocumentCollectionIfNotExists {HostDescription}", cosmosDataStoreConfiguration.AbsoluteCollectionUri); DocumentCollection existingDocumentCollection = await documentClient.TryGetDocumentCollectionAsync(cosmosDataStoreConfiguration.RelativeCollectionUri); if (existingDocumentCollection == null) { var documentCollection = new DocumentCollection { Id = cosmosDataStoreConfiguration.CollectionId, PartitionKey = new PartitionKeyDefinition { Paths = { $"/{KnownResourceWrapperProperties.PartitionKey}", }, }, }; existingDocumentCollection = await documentClient.CreateDocumentCollectionIfNotExistsAsync( cosmosDataStoreConfiguration.RelativeDatabaseUri, cosmosDataStoreConfiguration.RelativeCollectionUri, documentCollection); } await _upgradeManager.SetupCollectionAsync(documentClient, existingDocumentCollection); _logger.LogInformation("Cosmos DB collection {CollectionUri} successfully initialized", cosmosDataStoreConfiguration.AbsoluteCollectionUri); } catch (Exception ex) { _logger.LogCritical(ex, "Cosmos DB collection {CollectionUri} initialization failed", cosmosDataStoreConfiguration.AbsoluteCollectionUri); throw; } }
public static void CreateCollection(IDocumentClient client, string databaseId, string collectionId, string partitionKeyName = "") { var result = client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseId }).GetAwaiter().GetResult(); if (result.StatusCode == System.Net.HttpStatusCode.Accepted || result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode == System.Net.HttpStatusCode.Created) { var collection = new DocumentCollection { Id = collectionId }; if (!string.IsNullOrEmpty(partitionKeyName)) { if (!partitionKeyName.StartsWith("/")) { partitionKeyName = "/" + partitionKeyName; } collection.PartitionKey = new PartitionKeyDefinition { Paths = new Collection <string> { partitionKeyName } }; } var collectionCreationResult = client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseId), collection, new RequestOptions { OfferThroughput = DEFAULT_RUS }).GetAwaiter().GetResult(); if (collectionCreationResult.StatusCode == System.Net.HttpStatusCode.Accepted || collectionCreationResult.StatusCode == System.Net.HttpStatusCode.OK || collectionCreationResult.StatusCode == System.Net.HttpStatusCode.Created) { Task.Delay(500).GetAwaiter().GetResult(); } else { throw new NotSupportedException($"Collection '{collection}' cannot be created. ({collectionCreationResult.StatusCode})"); } } else { throw new NotSupportedException($"Database '{databaseId}' cannot be created. Wrong Url or Key? ({result.StatusCode})"); } }
public CosmosDbTodoRepository(Uri accountEndpoint, string accountKey) { documentClient = new DocumentClient(accountEndpoint, accountKey); documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = dbName }).Wait(); var todoList = new DocumentCollection() { Id = collectionName }; todoList.PartitionKey.Paths.Add(todoListPartitionKey); documentClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(dbName), todoList).Wait(); }
public FhirDocumentClientInitializerTests() { var documentClientTestProvider = Substitute.For <IDocumentClientTestProvider>(); var fhirRequestContextAccessor = Substitute.For <IFhirRequestContextAccessor>(); _documentClientInitializer = new FhirDocumentClientInitializer(documentClientTestProvider, fhirRequestContextAccessor, NullLogger <FhirDocumentClientInitializer> .Instance); _collectionInitializers = new List <ICollectionInitializer> { _collectionInitializer1, _collectionInitializer2 }; _documentClient.CreateDatabaseIfNotExistsAsync(Arg.Any <Database>(), Arg.Any <RequestOptions>()).Returns(Substitute.For <ResourceResponse <Database> >()); _cosmosDataStoreConfiguration.RetryOptions.MaxNumberOfRetries = 10; _cosmosDataStoreConfiguration.RetryOptions.MaxWaitTimeInSeconds = 99; }
public async Task Run(ILogger logger) { var database = new Database { Id = DocumentSettings.DatabaseName }; var documentCollection = new DocumentCollection { Id = DocumentSettings.AccountProviderLegalEntitiesCollectionName, PartitionKey = new PartitionKeyDefinition { Paths = new Collection <string> { "/ukprn" } }, UniqueKeyPolicy = new UniqueKeyPolicy { UniqueKeys = new Collection <UniqueKey> { new UniqueKey { Paths = new Collection <string> { "/accountProviderLegalEntityId" } }, new UniqueKey { Paths = new Collection <string> { "/accountLegalEntityId" } } } } }; var requestOptions = new RequestOptions { OfferThroughput = 1000 }; //todo: logging from eas await _documentClient.CreateDatabaseIfNotExistsAsync(database); await _documentClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(database.Id), documentCollection, requestOptions); }
public async Task Run() { var database = new Database { Id = DocumentSettings.DatabaseName }; var documentCollection = new DocumentCollection { Id = DocumentSettings.AccountUsersCollectionName, PartitionKey = new PartitionKeyDefinition { Paths = new Collection <string> { "/accountId" } }, UniqueKeyPolicy = new UniqueKeyPolicy { UniqueKeys = new Collection <UniqueKey> { new UniqueKey { Paths = new Collection <string> { "/userRef" } } } } }; _logger.LogInformation("Creating ReadStore database and collection if they don't exist"); var createDatabaseResponse = await _documentClient.CreateDatabaseIfNotExistsAsync(database); _logger.LogInformation($"Database {(createDatabaseResponse.StatusCode == HttpStatusCode.Created ? "created" : "already existed")}"); var requestOptions = new RequestOptions { OfferThroughput = 1000 }; var createDocumentCollectionResponse = await _documentClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(database.Id), documentCollection, requestOptions); _logger.LogInformation($"Document collection {(createDocumentCollectionResponse.StatusCode == HttpStatusCode.Created ? "created" : "already existed")}"); }
public ProductsController(IDocumentClient client) { _cosmosClient = client; try { _cosmosClient.CreateDatabaseIfNotExistsAsync(new Database { Id = Constants.CosmosDBName }).Wait(); _cosmosClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Constants.CosmosDBName), new DocumentCollection { Id = CosmosCollectionName }).Wait(); _collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDBName, CosmosCollectionName); } catch (Exception ex) { Console.WriteLine($"Error building ProductsController: {ex.ToString()}"); throw; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, IDocumentClient client) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); // Init documentdb database Database shopifychallenge = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = Configuration["DbConfig:DataBaseName"] }); await client.CreateDocumentCollectionIfNotExistsAsync(shopifychallenge.SelfLink, new DocumentCollection { Id = Configuration["DbConfig:CollectionName"] }); }
public async Task <HGV> method(string id) { try { var PrimaryKey = Constants.PrimaryKey; var url = Constants.Uri; _client = new DocumentClient(new Uri(url), PrimaryKey); //Inserting to cosmos var record = new HGV { HGVName = "TestHGV", Country = "United States", }; var ans = await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseId }); var collectionDefinition = new DocumentCollection { Id = CollectionId }; _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseId), collectionDefinition).Wait(); var document = await _client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId) , record); HGV hgvrecord = _client.CreateDocumentQuery <HGV>( UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)) .Where(v => v.HGVName == "TestHGV") .AsEnumerable() .FirstOrDefault(); //Getting data from cosmos based on id HGV document1 = _client.ReadDocumentAsync <HGV>(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id)).Result; return(document1); } catch (Exception e) { throw e; } }
/// <inheritdoc /> public async Task InitializeDataStore(IDocumentClient documentClient, CosmosDataStoreConfiguration cosmosDataStoreConfiguration, IEnumerable <ICollectionInitializer> collectionInitializers) { EnsureArg.IsNotNull(documentClient, nameof(documentClient)); EnsureArg.IsNotNull(cosmosDataStoreConfiguration, nameof(cosmosDataStoreConfiguration)); EnsureArg.IsNotNull(collectionInitializers, nameof(collectionInitializers)); try { _logger.LogInformation("Initializing Cosmos DB Database {DatabaseId} and collections", cosmosDataStoreConfiguration.DatabaseId); if (cosmosDataStoreConfiguration.AllowDatabaseCreation) { _logger.LogDebug("CreateDatabaseIfNotExists {DatabaseId})", cosmosDataStoreConfiguration.DatabaseId); var options = new RequestOptions { OfferThroughput = cosmosDataStoreConfiguration.InitialDatabaseThroughput }; await documentClient.CreateDatabaseIfNotExistsAsync( new Database { Id = cosmosDataStoreConfiguration.DatabaseId, }, options); } foreach (var collectionInitializer in collectionInitializers) { await collectionInitializer.InitializeCollection(documentClient); } _logger.LogInformation("Cosmos DB Database {DatabaseId} and collections successfully initialized", cosmosDataStoreConfiguration.DatabaseId); } catch (Exception ex) { _logger.LogCritical(ex, "Cosmos DB Database {DatabaseId} and collections initialization failed", cosmosDataStoreConfiguration.DatabaseId); throw; } }
private async Task CreateDatabase(string database, RequestOptions requestOptions = null) { await _documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = database }, requestOptions); }
private static async Task CreateDatabaseIfNotExistsAsync(string databaseId) { await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseId }); }
internal static async Task CreateDatabaseAndCollectionIfNotExistAsync(IDocumentClient documentClient, string databaseName, string collectionName, string partitionKey, int throughput) { await documentClient.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseName }); await CreateDocumentCollectionIfNotExistsAsync(documentClient, databaseName, collectionName, partitionKey, throughput); }
/// <summary> /// Creates the database and collection if it does not exist. /// </summary> /// <param name="documentClient">The document client.</param> /// <param name="databaseId">The id of the database.</param> /// <param name="collectionId">The id of the collection.</param> public static void CreateCollectionIfDoesNotExist(this IDocumentClient documentClient, string databaseId, string collectionId) { documentClient.CreateDatabaseIfNotExistsAsync(databaseId).Wait(); documentClient.CreateCollectionIfNotExistsAsync(databaseId, collectionId).Wait(); }
public async Task CreateDatabaseIfNotExistsAsync() { // This method is not exists on IDocumentClient. only on DocumentClient. await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = _databaseId }); }