public async Task CloseAsync()
        {
            ChangeFeedProcessor processorSnapshot = this.changeFeedProcessor;

            if (processorSnapshot != null)
            {
                await processorSnapshot.StopAsync().ConfigureAwait(false);
            }

            CosmosClient clientSnapshot = this.destinationCollectionClient;

            if (clientSnapshot != null)
            {
                clientSnapshot.Dispose();
            }

            clientSnapshot = this.sourceCollectionClient;

            if (clientSnapshot != null)
            {
                clientSnapshot.Dispose();
            }

            clientSnapshot = this.destinationCollectionClient;

            if (clientSnapshot != null)
            {
                clientSnapshot.Dispose();
            }

            this.containerToStoreDocuments = null;
            this.changeFeedProcessor       = null;
        }
        public async Task TestDispose()
        {
            CosmosClient       cosmosClient = new CosmosClient(ConnectionString);
            Database           database     = cosmosClient.GetDatabase("asdf");
            Container          container    = cosmosClient.GetContainer("asdf", "asdf");
            TransactionalBatch batch        = container.CreateTransactionalBatch(new PartitionKey("asdf"));

            batch.ReadItem("Test");

            FeedIterator <dynamic> feedIterator1 = container.GetItemQueryIterator <dynamic>();
            FeedIterator <dynamic> feedIterator2 = container.GetItemQueryIterator <dynamic>(queryText: "select * from T");
            FeedIterator <dynamic> feedIterator3 = database.GetContainerQueryIterator <dynamic>(queryText: "select * from T");

            string userAgent = cosmosClient.ClientContext.UserAgent;

            // Dispose should be idempotent
            cosmosClient.Dispose();
            cosmosClient.Dispose();

            List <Func <Task> > validateAsync = new List <Func <Task> >()
            {
                () => cosmosClient.ReadAccountAsync(),
                () => cosmosClient.CreateDatabaseAsync("asdf"),
                () => database.CreateContainerAsync("asdf", "/pkpathasdf", 200),
                () => container.ReadItemAsync <dynamic>("asdf", new PartitionKey("test")),
                () => container.Scripts.ReadStoredProcedureAsync("asdf"),
                () => container.Scripts.ReadTriggerAsync("asdf"),
                () => container.Scripts.ReadUserDefinedFunctionAsync("asdf"),
                () => batch.ExecuteAsync(),
                () => feedIterator1.ReadNextAsync(),
                () => feedIterator2.ReadNextAsync(),
                () => feedIterator3.ReadNextAsync(),
            };

            foreach (Func <Task> asyncFunc in validateAsync)
            {
                try
                {
                    await asyncFunc();

                    Assert.Fail("Should throw ObjectDisposedException");
                }
                catch (CosmosObjectDisposedException e)
                {
                    string expectedMessage = $"Cannot access a disposed 'CosmosClient'. Follow best practices and use the CosmosClient as a singleton." +
                                             $" CosmosClient was disposed at: {cosmosClient.DisposedDateTimeUtc.Value.ToString("o", CultureInfo.InvariantCulture)}; CosmosClient Endpoint: https://localtestcosmos.documents.azure.com/; Created at: {cosmosClient.ClientConfigurationTraceDatum.ClientCreatedDateTimeUtc.ToString("o", CultureInfo.InvariantCulture)}; UserAgent: {userAgent};";
                    Assert.IsTrue(e.Message.Contains(expectedMessage));
                    string diagnostics = e.Diagnostics.ToString();
                    Assert.IsNotNull(diagnostics);
                    Assert.IsFalse(diagnostics.Contains("NoOp"));
                    Assert.IsTrue(diagnostics.Contains("Client Configuration"));
                    string exceptionString = e.ToString();
                    Assert.IsTrue(exceptionString.Contains(diagnostics));
                    Assert.IsTrue(exceptionString.Contains(e.Message));
                    Assert.IsTrue(exceptionString.Contains(e.StackTrace));
                }
            }
        }
        public void TestDispose()
        {
            CosmosClient cosmosClient = new CosmosClient(ConnectionString);

            // Dispose should be idempotent
            cosmosClient.Dispose();
            cosmosClient.Dispose();
            cosmosClient.GetContainer("asdf", "asdf");
        }
Ejemplo n.º 4
0
        public void SingleClientTest()
        {
            CosmosClient cosmosClient = new CosmosClient(ConnectionString);

            Assert.AreEqual(1, CosmosClient.NumberOfActiveClients);
            cosmosClient.Dispose();
        }
Ejemplo n.º 5
0
 public void Dispose()
 {
     if (client != null)
     {
         client.Dispose();
     }
 }
Ejemplo n.º 6
0
        public void Dispose()
        {
            var tasks = _dbs.Select(db => db.DeleteAsync()).ToArray();

            Task.WaitAll(tasks);
            _client.Dispose();
        }
Ejemplo n.º 7
0
        private async Task DeleteDatabaseAndCleanupAsync()
        {
            DatabaseResponse databaseResourceResponse = await database.DeleteAsync();

            Console.WriteLine($"Deleted Database: {databaseId}");
            cosmosClient.Dispose();
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _cosmosClient?.Dispose();
     }
 }
Ejemplo n.º 9
0
        private async Task DeleteDatabaseAndCleanupAsync()
        {
            DatabaseResponse databaseResourceResponse = await _database.DeleteAsync();

            Debug.WriteLine("Suppression Database: {0}\n", _database.Id);
            _cosmosClient.Dispose();
        }
Ejemplo n.º 10
0
 public void Dispose()
 {
     if (cosmosClient != null)
     {
         cosmosClient.Dispose();
     }
 }
        public async Task CreateAndInitializeWithCosmosClientBuilderTest()
        {
            int httpCallsMade = 0;
            HttpClientHandlerHelper httpClientHandlerHelper = new HttpClientHandlerHelper
            {
                RequestCallBack = (request, cancellationToken) =>
                {
                    httpCallsMade++;
                    return(null);
                }
            };

            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            List <(string, string)> containers = new List <(string, string)>
            {
                ("ClientCreateAndInitializeDatabase", "ClientCreateAndInitializeContainer")
            };

            CosmosClientBuilder builder      = new CosmosClientBuilder(endpoint, authKey).WithHttpClientFactory(() => new HttpClient(httpClientHandlerHelper));
            CosmosClient        cosmosClient = await builder.BuildAndInitializeAsync(containers);

            Assert.IsNotNull(cosmosClient);
            int httpCallsMadeAfterCreation = httpCallsMade;

            ContainerInternal           container    = (ContainerInternal)cosmosClient.GetContainer("ClientCreateAndInitializeDatabase", "ClientCreateAndInitializeContainer");
            ItemResponse <ToDoActivity> readResponse = await container.ReadItemAsync <ToDoActivity>("1", new Cosmos.PartitionKey("Status1"));

            Assert.AreEqual(httpCallsMade, httpCallsMadeAfterCreation);
            cosmosClient.Dispose();
        }
Ejemplo n.º 12
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                CosmosClient cosmosDbClient;

                if (!_connections.TryGetValue(_connectionString, out cosmosDbClient))
                {
                    cosmosDbClient = new CosmosClient(_connectionString);

                    if (!_connections.TryAdd(_connectionString, cosmosDbClient))
                    {
                        cosmosDbClient.Dispose();
                        cosmosDbClient = _connections[_connectionString];
                    }
                }
                await cosmosDbClient.ReadAccountAsync();

                return(HealthCheckResult.Healthy());
            }
            catch (Exception ex)
            {
                return(new HealthCheckResult(context.Registration.FailureStatus, exception: ex));
            }
        }
Ejemplo n.º 13
0
 protected override void DisposeObject(bool disposing)
 {
     if (disposing)
     {
         cosmosClient.Dispose();
     }
 }
Ejemplo n.º 14
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Push2Cosmos processed a request.");

            string DatabaseName            = Environment.GetEnvironmentVariable("COSMOS_DB_NAME");
            string CollectionName          = Environment.GetEnvironmentVariable("COSMOS_COLLECTION");
            string ConnectionStringSetting = Environment.GetEnvironmentVariable("COSMOS_CS");

            CosmosClient cosmosClient    = new CosmosClient(ConnectionStringSetting);
            Container    cosmosContainer = cosmosClient.GetContainer(DatabaseName, CollectionName);

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            log.LogInformation($"Push2Cosmos : got string data: {requestBody}");
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            log.LogInformation("Push2Cosmos : got dynamic data");
            string scount = data?.messageCount;
            int    count  = (!string.IsNullOrEmpty(scount))? int.Parse(scount):1;

            log.LogInformation($"Push2Cosmos will push {count} messages");
            for (int i = 0; i < count; i++)
            {
                string pkey = Guid.NewGuid().ToString();
                data.id = pkey;
                log.LogInformation($"Push2Cosmos pushed one message with pkey:{pkey}");
                ItemResponse <object> alertResponse = await cosmosContainer.CreateItemAsync <object>(data, new PartitionKey(pkey));
            }

            cosmosClient.Dispose();
            return(new OkObjectResult($" {count} message(s) pushed"));
        }
Ejemplo n.º 15
0
        private async Task DeleteDatabaseAsync()
        {
            await _database.DeleteAsync();

            _cosmosClient.Dispose();

            Console.WriteLine($"\nDatabase {DATABASEID} deleted");
        }
Ejemplo n.º 16
0
 public void Dispose()
 {
     if (!isDisposed)
     {
         client.Dispose();
         isDisposed = true;
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _client.Dispose();
         _container = null;
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (_cosmosClient != null)
     {
         _cosmosClient.Dispose();
         _cosmosClient = null;
     }
 }
Ejemplo n.º 19
0
        public void MultiClientTest()
        {
            CosmosClient cosmosClient1 = new CosmosClient(ConnectionString); // Initializing 1st time
            CosmosClient cosmosClient2 = new CosmosClient(ConnectionString); // Initializing 2nd time

            Assert.AreEqual(2, CosmosClient.NumberOfActiveClients);
            cosmosClient1.Dispose();
            cosmosClient2.Dispose();
        }
Ejemplo n.º 20
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _initializationOperation.Dispose();
         _client.Dispose();
         _container = null;
     }
 }
        public async Task DisposeAsync()
        {
            if (_container != null)
            {
                await _container.DeleteContainerAsync();
            }

            _cosmosClient.Dispose();
        }
Ejemplo n.º 22
0
        private static async Task CleanupAsync()
        {
            if (Program.client != null)
            {
                await Program.client.GetDatabase(encryptedDatabaseId).DeleteStreamAsync();

                client.Dispose();
            }
        }
Ejemplo n.º 23
0
        public void MultiClientWithDisposeTest()
        {
            CosmosClient cosmosClient1 = new CosmosClient(ConnectionString); // Initializing 1st time
            CosmosClient cosmosClient2 = new CosmosClient(ConnectionString); // Initializing 2nd time
            CosmosClient cosmosClient3 = new CosmosClient(ConnectionString); // Initializing 3rd time

            cosmosClient2.Dispose();                                         // Destroying 1 instance
            Assert.AreEqual(2, CosmosClient.NumberOfActiveClients);
            cosmosClient1.Dispose();
            cosmosClient3.Dispose();
        }
        public async Task AuthIncorrectTest()
        {
            List <(string databaseId, string containerId)> containers = new List <(string databaseId, string containerId)>
            {
                ("ClientCreateAndInitializeDatabase", "ClientCreateAndInitializeContainer")
            };
            string       authKey      = TestCommon.GetAccountInfo().authKey;
            CosmosClient cosmosClient = await CosmosClient.CreateAndInitializeAsync("https://127.0.0.1:0000/", authKey, containers);

            cosmosClient.Dispose();
        }
        /// <summary>
        /// Delete the database and dispose of the Cosmos Client instance
        /// </summary>
        private async Task DeleteDatabaseAndCleanupAsync()
        {
            DatabaseResponse databaseResourceResponse = await database.DeleteAsync();

            // Also valid: await this.cosmosClient.Databases["FamilyDatabase"].DeleteAsync();

            Console.WriteLine("Deleted Database: {0}\n", databaseId);

            //Dispose of CosmosClient
            cosmosClient.Dispose();
        }
Ejemplo n.º 26
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             _client.Dispose();
         }
         disposedValue = true;
     }
 }
        public void Dispose()
        {
            if (!_disposed)
            {
                _cosmosClient.Dispose();

                GC.SuppressFinalize(this);

                _disposed = true;
            }
        }
    static void Main(string[] args)
    {
        cosmosClient = new CosmosClient(EndpointUrl, PrimaryKey);
        database     = cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId).Result;
        container    = database.CreateContainerIfNotExistsAsync(containerId, "/key").Result;
        string json = "{\"id\":\"bbb\",\"key\":\"bbb\"}";
        var    obj  = JsonConvert.DeserializeObject(json);

        container.CreateItemAsync <Object>(obj).Wait();
        cosmosClient.Dispose();
        Console.ReadLine();
    }
Ejemplo n.º 29
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _cosmosClient.Dispose();
                }

                _disposed = true;
            }
        }
        private void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    cosmosClient.Dispose();
                }

                disposedValue = true;
            }
        }