public async Task <bool> TryDeleteDirectoryAsync(string path)
        {
            path = path.TrimEnd('/');
            var filter = Builders <MongoDBFileStoreEntry> .Filter.Where(e => e.Path.StartsWith(path));

            var fileEntityList = await _mongoRepository.GetAsync(filter);

            try
            {
                foreach (var fileEntity in fileEntityList)
                {
                    if (!fileEntity.IsDirectory)
                    {
                        await _mongoRepository.DeleteFileAsync(fileEntity.FileStoreId);
                    }
                }
                await _mongoRepository.DeleteAsync(filter);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError(e.StackTrace);
                return(false);
            }
        }
        public void Deve_Registrar_Logs_No_Repositorio_MongoDB()
        {
            //Given
            var dataBaseName = "mongo-auto-create";
            var entity       = new AggregateRoot();

            var mongoSettings = new MongoSettings
            {
                DatabaseName     = dataBaseName,
                ConnectionString = "mongodb://127.0.0.1:27017"
            };

            var setMock          = new Mock <IMongoCollection <AggregateRoot> >();
            var mongoContextMock = new Mock <MongoContext>(mongoSettings);

            var logger            = new XunitLogger <MongoRepository <AggregateRoot, Guid> >();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(setup => setup.CreateLogger(It.IsAny <string>())).Returns(logger);

            var repositoryMock = new MongoRepository <AggregateRoot, Guid>(mongoContextMock.Object, loggerFactoryMock.Object);

            //When
            repositoryMock.GetByIdAsync(entity.Id).ConfigureAwait(false);
            repositoryMock.GetAllAsync();
            repositoryMock.InsertAsync(entity);
            repositoryMock.UpdateAsync(entity);
            repositoryMock.DeleteAsync(entity);
            repositoryMock.DeleteAsync(entity.Id).ConfigureAwait(false);
            repositoryMock.SaveChangesAsync();

            //Then
            var msgContructor          = "Inicializando MongoRepository<AggregateRoot, Guid>";
            var msgGetById             = $"Método: GetByIdAsync( {{id:{ entity.Id }}} ) Retorno: type AggregateRoot";
            var msgGetAllAsync         = "Método: GetAllAsync() Retorno: IAsyncEnumerable<AggregateRoot>";
            var msgInsertAsync         = $"Método: InsertAsync( {{entity:{ entity.ToJson()}}} )";
            var msgUpdateAsync         = $"Método: UpdateAsync( {{entity:{ entity.ToJson()}}} )";
            var msgDeleteAsync         = $"Método: DeleteAsync( {{entity:{ entity.ToJson()}}} )";
            var msgDeleteNotFoundAsync = $"Método: DeleteAsync( {{id:{ entity.Id }}} ) Registro não encontrado";
            var msgSaveChanges         = "Método: SaveChangesAsync()";

            logger.Logs.Should().HaveCount(9);
            logger.Logs.Any(a => a.Equals(msgGetById)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgContructor)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetAllAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgInsertAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgUpdateAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgDeleteAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgDeleteNotFoundAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgSaveChanges)).Should().BeTrue();

            mongoContextMock.Object.MongoClient.DropDatabase(dataBaseName);
            mongoContextMock.Object.Dispose();
        }
Example #3
0
        public async void CanDeleteDocumentByExpressionAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers);

            await customerRepository.DeleteAsync(x => x.Id == this.TestCustomers[0].Id);

            var document = await customerRepository.GetByIdAsync(this.TestCustomers[0].Id);

            document.ShouldBeNull();

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
Example #4
0
        public async void CanDeleteDocumentByIdAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            customerRepository.Add(this.TestCustomers);
            customerRepository.Count().ShouldBe(this.TestCustomers.Count);

            await customerRepository.DeleteAsync(this.TestCustomers[0].Id);

            var document = await customerRepository.GetByIdAsync(this.TestCustomers[0].Id);

            document.ShouldBeNull();

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
        public async Task <IActionResult> Delete(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return(BadRequest("Customer ID is required to delete customer record"));
            }

            try
            {
                var cust = await _custrepo.GetByEntityIdAsync(id);

                if (cust == null)
                {
                    return(NotFound());
                }

                await _custrepo.DeleteAsync(id);

                return(Ok());
            }
            catch (Exception ex) {
                _logger.LogError(LoggingEvents.Error, ex, $"ERROR: Unable to delete customer: {id}");
            }

            return(BadRequest($"ERROR: Unable to delete customer: {id}"));
        }
Example #6
0
        public async Task DeleteAsync_Success()
        {
            var entity = new MongoTestEntity()
            {
                Bool   = false,
                Number = 1,
                String = "String"
            };

            entity = Repository.Create(entity);

            await Repository.DeleteAsync(entity);

            entity = Repository.Read(entity.Id);

            Assert.IsNull(entity);
        }
Example #7
0
        public async void CanAddDocumentAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers[0]);

            this.TestCustomers[0].Id.ShouldNotBeNullOrWhiteSpace();

            await customerRepository.DeleteAsync(this.TestCustomers[0]);
        }
 public async Task DeleteAsync(TrackingUrlEntity entity)
 {
     try
     {
         await _collection.DeleteAsync(entity.Id);
     }
     catch (Exception e)
     {
         throw new ApplicationException(string.Format("Mongo driver failure: {0}", e));
     }
 }
Example #9
0
        public async void CanCountDocumentsAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers);

            var count = await customerRepository.CountAsync();

            count.ShouldBe(this.TestCustomers.Count);

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
Example #10
0
        public async void CanCheckIfDocumentExistsAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers);

            var exists = await customerRepository.ExistsAsync(x => x.Id == this.TestCustomers[0].Id);

            exists.ShouldBeTrue();

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
        public async Task Delete_Object_Success()
        {
            MongoRepository repo = new MongoRepository(_mongoFixture.MongoClient, _mongoFixture.Logger, new Dictionary <string, HashSet <string> >());
            string          json = "{ \"Name\" : \"Maria\" }";

            var insertResult = await repo.InsertAsync("bookstore", "users", "3", json);

            var getResult = await repo.GetAsync("bookstore", "users", "3");

            var deleteResult = await repo.DeleteAsync("bookstore", "users", "3");

            var getResultAfterDelete = await repo.GetAsync("bookstore", "users", "3");

            Assert.Null(getResultAfterDelete);
            Assert.True(deleteResult);
        }
Example #12
0
        public async void CanUpdateDocumentAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers);

            this.TestCustomers[0].LastName = "Updated LastName";
            await customerRepository.UpdateAsync(this.TestCustomers[0]);

            var document = await customerRepository.GetByIdAsync(this.TestCustomers[0].Id);

            document.ShouldNotBeNull();
            document.Id.ShouldBe(this.TestCustomers[0].Id);
            document.LastName.ShouldBe("Updated LastName");

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
        public async Task DeleteAsyncByPredicateShouldSucceed()
        {
            var itemsDoc = new List <MockDocument> {
                _mockDocument98, _mockDocument99
            };

            foreach (var item in itemsDoc)
            {
                item.IsActive = false;
            }

            await _mockDocumentRepo.CreateAsync(itemsDoc);

            var searchDocResults = await _mockDocumentRepo.FindAsync();

            var count = searchDocResults.Count;

            var searchObjResults = await _mockObjectRepo.FindAsync();

            count += searchObjResults.Count;

            var deleteCount = await _mockDocumentRepo.DeleteAsync(x => !x.IsActive);

            searchDocResults = await _mockDocumentRepo.FindAsync();

            deleteCount += await _mockObjectRepo.DeleteAsync(x => true);

            searchObjResults = await _mockObjectRepo.FindAsync();

            Assert.Equal(3, count);
            Assert.Equal(3, deleteCount);

            Assert.NotNull(searchDocResults);
            Assert.NotNull(searchObjResults);
            Assert.Collection(searchDocResults);
            Assert.Collection(searchObjResults);
            Assert.Empty(searchDocResults);
            Assert.Empty(searchObjResults);
        }
        public async Task CustomerMasterRepositoryTest001_CreateFindDeleteAsync_ExpectNoExceptions()
        {
            // Test cases for async API

            await repo.DeleteAllAsync();

            Assert.Equal(0, repo.Count());

            // Add an entity
            Customer entity = new Customer("CustomerMasterRepositoryTest001_cname", "1-800-start");
            await repo.AddAsync(entity);

            this.testLogger.LogDebug($"New entity: {entity.ToJson()}");

            // Count should increase by 1
            Assert.Equal(1, await repo.CountAsync());

            // Test get by id
            var fetch = await repo.GetByEntityIdAsync(entity.entityid);

            Assert.NotNull(fetch);
            // Assert.Equal(fetch,entity);

            // Test search API
            var searchresult = await repo.GetAsync(e => e.phone == "1-800-start");

            Assert.Equal(1, searchresult.Count);

            // Test Update API
            entity.phone = "1-800-updated";
            await repo.UpdateAsync(entity);

            Assert.Equal(1, (await repo.GetAsync(e => e.phone == "1-800-updated")).Count);

            await repo.DeleteAsync(entity.entityid);

            await Assert.ThrowsAsync <Exception>(async() => fetch = await repo.GetByEntityIdAsync(entity.entityid));
        }
Example #15
0
        public async void CanUpdateMultipleDocumentsAsync()
        {
            var customerRepository = new MongoRepository <Customer>();

            await customerRepository.AddAsync(this.TestCustomers);

            this.TestCustomers[0].LastName = "Updated LastName 1";
            this.TestCustomers[1].LastName = "Updated LastName 2";
            await customerRepository.UpdateAsync(this.TestCustomers);

            var document1 = await customerRepository.GetByIdAsync(this.TestCustomers[0].Id);

            document1.ShouldNotBeNull();
            document1.Id.ShouldBe(this.TestCustomers[0].Id);
            document1.LastName.ShouldBe("Updated LastName 1");

            var document2 = await customerRepository.GetByIdAsync(this.TestCustomers[1].Id);

            document2.ShouldNotBeNull();
            document2.Id.ShouldBe(this.TestCustomers[1].Id);
            document2.LastName.ShouldBe("Updated LastName 2");

            await customerRepository.DeleteAsync(this.TestCustomers);
        }
 public async Task <Task> ExecuteAsync(Translation translation)
 {
     SetPredicate(translation);
     Log.Debug($"Deleting translation async: {translation.ToString()}");
     return(_mongoRepository.DeleteAsync(_predicate));
 }
        public async Task CreateAsyncByItemsShouldSucceed()
        {
            var deleteCount = await _mockDocumentRepo.DeleteAsync(x => true);

            var items = new List <MockDocument> {
                _mockDocument98, _mockDocument99
            };
            await _mockDocumentRepo.CreateAsync(items);

            var results = await _mockDocumentRepo.FindAsync();

            Assert.Equal(1, deleteCount);
            Assert.NotEmpty(results);
            Assert.Equal(2, results.Count);
        }
        public void StartServer(CancellationToken cancellationToken)
        {
            this._logger.LogDebug(LoggingEvents.Debug, "Started Data Replication Server");
            Console.WriteLine(" *** Started App Data Replication Server ***");


            // This is the event handler for emailNotification queue. Make sure this does not throw exception
            // Kafka message handling block would not be responsible to handle any exceptions
            Func <KMessage <AppEventArgs <Customer> >, Task> appEventHandler = async(message) =>
            {
                this._logger.LogTrace(LoggingEvents.Trace, $"Response: Partition:{message.Partition}, Offset:{message.Offset} :: {message.Message}");

                AppEventArgs <Customer> evt = message.Message;

                try {
                    Customer customer = evt.afterChange;

                    switch (evt.appEventType)
                    {
                    case AppEventType.Insert:
                        _logger.LogTrace(LoggingEvents.Trace, String.Format("Adding new Customer:{0}", customer.name));
                        await _custrepo.AddAsync(customer);

                        await this._searchrepo.AddAsync(customer);

                        break;

                    case AppEventType.Delete:
                        var cust = await _custrepo.GetByEntityIdAsync(customer.entityid);

                        if (cust == null)
                        {
                            _logger.LogTrace(LoggingEvents.Trace, $"Trying to delete Customer {customer.name} with EmtityID: {customer.entityid} that does not exist");
                        }
                        else
                        {
                            await _custrepo.DeleteAsync(customer.entityid);
                        }

                        if (this._searchrepo.Exists(customer.id))
                        {
                            await this._searchrepo.DeleteAsync(customer.id);
                        }

                        break;

                    case AppEventType.Update:
                        _logger.LogTrace(LoggingEvents.Trace, $"Processing request to update customer:{customer.entityid}");
                        await _custrepo.UpdateAsync(customer);

                        await _searchrepo.UpdateAsync(customer);

                        break;

                    default:
                        _logger.LogTrace(LoggingEvents.Trace, $"No action required for event:{evt.id} of type:{evt.appEventType}");
                        break;
                    }

                    this._logger.LogDebug(LoggingEvents.Trace, $"Processed Customer CRUD event {evt.id}");
                }
                catch (Exception ex) {
                    var msg = $"Event:{evt.id} - Error:{ex.Message}";

                    this._logger.LogError(LoggingEvents.Error, ex, msg);

                    // We will send out a notification for every update
                    var notifyEvt = new EmailEventArgs {
                        subject  = "Data Replication Error",
                        textMsg  = $"Error replicating customer information. {msg}",
                        htmlMsg  = $"<p> Error replicating customer information.  </p><p> <b>Message Details: </b> {msg}  <p>",
                        notifyTo = new List <string>()
                        {
                            "*****@*****.**"
                        },
                        notifyCC  = new List <string>(),
                        notifyBCC = new List <string>()
                    };

                    await this._notificationProducer.ProduceAsync(this._notificationMsgQueueTopic, notifyEvt);
                }
            };

            this._appEventMsgConsumer.Consume(cancellationToken, appEventHandler, null, null);

            this._appEventMsgConsumer.Dispose();
            Console.WriteLine(" *** Stopped App Data Replication Server ***");

            this._logger.LogDebug(LoggingEvents.Debug, "Stopped App Data Replication Server");
        }