public CosmosContainer Convert(CosmosAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } ICosmosService service = configProvider.GetService( configProvider.ResolveConnectionString(attribute.ConnectionStringSetting), attribute.ApplicationName, attribute.ApplicationRegion); if (attribute.CreateIfNotExists) { var context = new CosmosContext { ResolvedAttribute = attribute, Service = service }; CosmosUtility.CreateDatabaseAndContainerNameIfNotExistAsync(context).Wait(); } return(service.GetContainer(attribute.DatabaseName, attribute.ContainerName)); }
internal ICosmosService GetService(string connectionString, string applicationName = "", string applicationRegion = "") { string cacheKey = BuildCacheKey(connectionString, applicationName, applicationRegion); CosmosClientOptions clientOptions = CosmosUtility.BuildClientOptions(options.ConnectionMode, applicationName, applicationRegion); return(ClientCache.GetOrAdd(cacheKey, (c) => cosmosServiceFactory.CreateService(connectionString, clientOptions))); }
public async Task AddAsync(T item, CancellationToken cancellationToken = default) { bool create = false; try { await UpsertDocument(cosmosContext, item); } catch (Exception ex) { if (CosmosUtility.TryGetCosmosException(ex, out CosmosException ce) && (HttpStatusCode)ce.Status == HttpStatusCode.NotFound) { if (cosmosContext.ResolvedAttribute.CreateIfNotExists) { create = true; } else { // Throw a custom error so that it's easier to decipher. string message = $"The container '{cosmosContext.ResolvedAttribute.ContainerName}' (in database '{cosmosContext.ResolvedAttribute.DatabaseName}') does not exist. To automatically create the collection, set '{nameof(CosmosAttribute.CreateIfNotExists)}' to 'true'."; throw new InvalidOperationException(message, ex); } } else { throw; } } if (create) { await CosmosUtility.CreateDatabaseAndContainerNameIfNotExistAsync(cosmosContext); await UpsertDocument(cosmosContext, item); } }