Esempio n. 1
0
        public async Task GivenACompletedTransaction_WhenStartingASecondTransactionCommitted_ThenTheResourceShouldBeCreated()
        {
            string createdId1;
            string createdId2;

            using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
            {
                SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));

                createdId1 = saveResult.Resource.Id;

                Assert.NotEqual(string.Empty, createdId1);

                transactionScope.Complete();
            }

            using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
            {
                SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));

                createdId2 = saveResult.Resource.Id;

                Assert.NotEqual(string.Empty, createdId2);

                transactionScope.Complete();
            }

            ResourceElement getResult1 = await Mediator.GetResourceAsync(new ResourceKey <Observation>(createdId1));

            Assert.Equal(createdId1, getResult1.Id);

            ResourceElement getResult2 = await Mediator.GetResourceAsync(new ResourceKey <Observation>(createdId2));

            Assert.Equal(createdId2, getResult2.Id);
        }
Esempio n. 2
0
        public DeleteContainerResult Execute(DeleteContainerParameters parameters)
        {
            using (ITransactionScope scope = DatabaseContext.CreateTransactionScope())
            {
                ContainerDao.DeleteContainer(parameters.ContainerName);
                scope.Complete();
            }

            return(new DeleteContainerResult());
        }
Esempio n. 3
0
        public void TransactionScope()
        {
            DagentDatabase db = new DagentDatabase("connectionStringName");

            using (ITransactionScope scope = db.TransactionScope())
            {
                Customer customer = new Customer {
                    CustomerId = 1, Name = "Ziba-nyan"
                };

                db.Command <Customer>("Customer", "CustomerId").Insert(customer);

                scope.Complete();

                customer.Name = "Buchi-nyan";

                db.Command <Customer>("Customer", "CustomerId").Update(customer);

                scope.Complete();
            }
        }
Esempio n. 4
0
        public FindContainerResult Execute(FindContainerParameters parameters)
        {
            using (ITransactionScope scope = DatabaseContext.CreateTransactionScope())
            {
                var result     = new FindContainerResult();
                var containers = ContainerDao.FindContainer(parameters.ContainerName);

                if ((containers != null) && (containers.Count > 0))
                {
                    result.AddRange(containers);
                }

                scope.Complete();

                return(result);
            }
        }
Esempio n. 5
0
        private Tuple <ExecutionResult, ISessionInformation> CompleteTopLevelTransaction(IEnumerable <IEventNotifier> notifiers, SessionDataContext ctx, SessionLocalInfo currentInfo)
        {
            // Sauvegarde des références vers les objets qui sont utilisés aprés que les données de la session auront été supprimées
            ExecutionResult     messages    = null;
            ISessionInformation sessionInfo = null;

            // Il ne peut pas y avoir d'erreur dans cette partie de code
            try
            {
                ctx.Disposing = true;

                // Si la session était en lecture seule, on simplifie les traitements
                // Pas de validation
                if (!ctx.ReadOnly)
                {
                    messages = ExecuteConstraints(ctx, currentInfo);
                }

                // Contexte en lecture seule de la session mais tjs dans le scope
                // Envoi des events même en read-only pour s'assurer que le OnSessionCompleted soit bien notifié
                if (!ctx.CancellationToken.IsCancellationRequested)
                {
                    using (CodeMarker.MarkBlock("Session.OnSessionCompleted"))
                    {
                        sessionInfo = OnSessionCompleted(currentInfo, notifiers, messages);
                    }
                }

                // Si tout va bien, on commite
                if (!IsAborted && _scope != null && (messages == null || !messages.HasErrors))
                {
                    _scope.Complete();
                }
            }
            catch (Exception ex)
            {
                Log(new DiagnosticMessage(MessageType.Error, ex.Message, ExceptionMessages.Diagnostic_ApplicationError, SessionDataContext.InValidationProcess, null, ex));
            }
            finally
            {
                DisposeSession(ctx);
            }

            return(Tuple.Create(messages ?? ExecutionResult.Empty, sessionInfo));
        }
Esempio n. 6
0
        public FindBlobResult Execute(FindBlobParameters parameters)
        {
            using (ITransactionScope scope = DatabaseContext.CreateTransactionScope())
            {
                var result = new FindBlobResult();

                var blobs = BlobDao.FindContainerBlob(parameters.ContainerName, parameters.BlobName);

                if ((blobs != null) && (blobs.Count > 0))
                {
                    result.AddRange(blobs);
                }

                scope.Complete();

                return(result);
            }
        }
Esempio n. 7
0
        public async Task GivenATransactionHandler_WhenATransactionIsCommitted_ThenTheResourceShouldBeCreated()
        {
            string createdId = string.Empty;

            using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
            {
                SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));

                createdId = saveResult.Resource.Id;

                Assert.NotEqual(string.Empty, createdId);

                transactionScope.Complete();
            }

            ResourceElement getResult = await Mediator.GetResourceAsync(new ResourceKey <Observation>(createdId));

            Assert.Equal(createdId, getResult.Id);
        }
Esempio n. 8
0
        //[TestMethod]
        public void RefreshTestData()
        {
            DagentDatabase database = new DagentDatabase("SQLite");

            using (ITransactionScope scope = database.TransactionScope())
            {
                database.ExequteNonQuery("delete from customers", null);
                database.ExequteNonQuery("delete from customerPurchases", null);
                database.ExequteNonQuery("delete from business", null);

                int customerNo          = 10000;
                int customerPurchasesNo = 10;
                int businessNo          = 10;

                int businessId = 1;
                for (int i = 1; i <= customerNo; i++)
                {
                    database.ExequteNonQuery(string.Format("insert into customers values ({0}, '{1}', '{2}')", i.ToString(), "name_" + i.ToString(), businessId));

                    if (businessId == 10)
                    {
                        businessId = 0;
                    }
                    businessId++;


                    for (int j = 1; j <= customerPurchasesNo; j++)
                    {
                        database.ExequteNonQuery(string.Format("insert into customerPurchases values ({0}, {1}, '{2}')", i.ToString(), j.ToString(), "content_" + j.ToString()));
                    }
                }

                for (int i = 1; i <= businessNo; i++)
                {
                    database.ExequteNonQuery(string.Format("insert into business values ({0}, '{1}')", i.ToString(), "business_" + i.ToString()));
                }

                scope.Complete();
            }
        }
        public CreateOrUpdateContainerResult Execute(CreateOrUpdateContainerParameters parameters)
        {
            CreateOrUpdateContainerResult result = new CreateOrUpdateContainerResult();

            if ((parameters.Container == null) || (string.IsNullOrEmpty(parameters.Container.Name)))
            {
                return(result);
            }

            using (ITransactionScope scope = DatabaseContext.CreateTransactionScope())
            {
                var containers = ContainerDao.FindContainer(parameters.Container.Name);

                if ((containers != null) && (containers.Count == 1))
                {
                    var dbContainer = containers[0];

                    if (dbContainer.Name == parameters.Container.Name)
                    {
                        dbContainer.MetaData.Clear();

                        foreach (ContainerMetaData meta in parameters.Container.MetaData)
                        {
                            dbContainer.MetaData.Add(meta);
                        }

                        parameters.Container = dbContainer;
                    }
                }

                parameters.Container.LastModified = DateTime.Now.ToUniversalTime();
                ContainerDao.SaveOrUpdate(parameters.Container);

                scope.Complete();
            }

            return(result);
        }
Esempio n. 10
0
        public async Task GivenATransactionHandler_WhenATransactionFailsFailedRequest_ThenNothingShouldCommit()
        {
            string createdId        = string.Empty;
            string randomNotFoundId = Guid.NewGuid().ToString();

            await Assert.ThrowsAsync <ResourceNotFoundException>(
                async() =>
            {
                using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
                {
                    SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
                    createdId = saveResult.Resource.Id;

                    Assert.NotEqual(string.Empty, createdId);

                    await Mediator.GetResourceAsync(new ResourceKey <Observation>(randomNotFoundId));

                    transactionScope.Complete();
                }
            });

            await Assert.ThrowsAsync <ResourceNotFoundException>(
                async() => { await Mediator.GetResourceAsync(new ResourceKey <Observation>(createdId)); });
        }
Esempio n. 11
0
        public async Task <(bool success, int retrievedInstanceCount)> CleanupDeletedInstancesAsync(CancellationToken cancellationToken)
        {
            bool success = true;
            int  retrievedInstanceCount = 0;

            using (ITransactionScope transactionScope = _transactionHandler.BeginTransaction())
            {
                try
                {
                    var deletedInstanceIdentifiers = (await _indexDataStore
                                                      .RetrieveDeletedInstancesAsync(
                                                          _deletedInstanceCleanupConfiguration.BatchSize,
                                                          _deletedInstanceCleanupConfiguration.MaxRetries,
                                                          cancellationToken))
                                                     .ToList();

                    retrievedInstanceCount = deletedInstanceIdentifiers.Count;

                    foreach (VersionedInstanceIdentifier deletedInstanceIdentifier in deletedInstanceIdentifiers)
                    {
                        try
                        {
                            Task[] tasks = new[]
                            {
                                _fileStore.DeleteFileIfExistsAsync(deletedInstanceIdentifier, cancellationToken),
                                _metadataStore.DeleteInstanceMetadataIfExistsAsync(deletedInstanceIdentifier, cancellationToken),
                            };

                            await Task.WhenAll(tasks);

                            await _indexDataStore.DeleteDeletedInstanceAsync(deletedInstanceIdentifier, cancellationToken);
                        }
                        catch (Exception cleanupException)
                        {
                            try
                            {
                                int newRetryCount = await _indexDataStore.IncrementDeletedInstanceRetryAsync(deletedInstanceIdentifier, GenerateCleanupAfter(_deletedInstanceCleanupConfiguration.RetryBackOff), cancellationToken);

                                if (newRetryCount > _deletedInstanceCleanupConfiguration.MaxRetries)
                                {
                                    _logger.LogCritical(cleanupException, "Failed to cleanup instance {deletedInstanceIdentifier}. Retry count is now {newRetryCount} and retry will not be re-attempted.", deletedInstanceIdentifier, newRetryCount);
                                }
                                else
                                {
                                    _logger.LogError(cleanupException, "Failed to cleanup instance {deletedInstanceIdentifier}. Retry count is now {newRetryCount}.", deletedInstanceIdentifier, newRetryCount);
                                }
                            }
                            catch (Exception incrementException)
                            {
                                _logger.LogCritical(incrementException, "Failed to increment cleanup retry for instance {deletedInstanceIdentifier}.", deletedInstanceIdentifier);
                                success = false;
                            }
                        }
                    }

                    transactionScope.Complete();
                }
                catch (Exception retrieveException)
                {
                    _logger.LogCritical(retrieveException, "Failed to retrieve instances to cleanup.");
                    success = false;
                }
            }

            return(success, retrievedInstanceCount);
        }
Esempio n. 12
0
        public void InsertManyData()
        {
            IDagentDatabase database = new DagentDatabase("SQLite");

            using (ITransactionScope scope = database.TransactionScope())
            {
                database.ExequteNonQuery("delete from customers", null);
                database.ExequteNonQuery("delete from customerPurchases", null);
                database.ExequteNonQuery("delete from business", null);

                int customerNo          = 10000;
                int customerPurchasesNo = 10;
                int businessNo          = 10;

                //var customerCommand = database.Command<Customer>("customers", "customerId");
                //var customerPurchaseCommand = database.Command<CustomerPurchase>("customerPurchases", "customerId", "no");
                //var businessCommand = database.Command<Business>("business", "businessId");

                int businessId = 1;
                for (int i = 1; i <= customerNo; i++)
                {
                    Customer customer = new Customer
                    {
                        customerId = i,
                        name       = "name_" + i.ToString(),
                        businessId = businessId
                    };
                    database.Command <Customer>("customers", "customerId").Insert(customer);

                    if (businessId == 10)
                    {
                        businessId = 0;
                    }
                    businessId++;


                    for (int j = 1; j <= customerPurchasesNo; j++)
                    {
                        CustomerPurchase customerPurchase = new CustomerPurchase
                        {
                            customerId = i,
                            no         = j,
                            content    = "content_" + j.ToString()
                        };
                        database.Command <CustomerPurchase>("customerPurchases", "customerId", "no").Insert(customerPurchase);
                    }
                }

                for (int i = 1; i <= businessNo; i++)
                {
                    Business business = new Business
                    {
                        BusinessId   = i,
                        BusinessName = "business_" + i.ToString()
                    };
                    database.Command <Business>("business", "businessId")
                    .Ignore(x => x.BusinessId, x => x.BusinessName)
                    .Map((row, model) =>
                    {
                        row["businessId"]   = model.BusinessId;
                        row["businessName"] = model.BusinessName;
                    })
                    .Insert(business);
                }

                scope.Complete();
            }

            FetchForOneToOne();
        }
Esempio n. 13
0
        public CreateOrUpdateBlobResult Execute(CreateOrUpdateBlobParameters parameters)
        {
            CreateOrUpdateBlobResult result = new CreateOrUpdateBlobResult();

            if ((parameters.Blobs == null) || (parameters.Blobs.Count == 0))
            {
                return(result);
            }

            using (ITransactionScope scope = DatabaseContext.CreateTransactionScope())
            {
                Blob      saveBlob;
                Container container;
                bool      addedToList = false;

                var dbContainerList = ContainerDao.FindContainer(parameters.ContainerName);

                if ((dbContainerList == null) || (dbContainerList.Count == 0))
                {
                    container = new Container
                    {
                        LastModified = DateTime.Now.ToUniversalTime(),
                        Name         = parameters.ContainerName
                    };

                    container = ContainerDao.SaveOrUpdate(container);
                }
                else
                {
                    container = dbContainerList.First();
                }

                foreach (Blob parameterBlob in parameters.Blobs)
                {
                    // Check if blob already exists
                    var dbBlobList = BlobDao.FindContainerBlob(parameters.ContainerName, parameterBlob.Name);

                    if ((dbBlobList != null) && (dbBlobList.Count > 0))
                    {
                        // Update
                        saveBlob = dbBlobList.First();

                        saveBlob.Data = parameterBlob.Data;

                        if (parameterBlob.MetaData != null)
                        {
                            saveBlob.MetaData.Clear();

                            foreach (BlobMetaData meta in parameterBlob.MetaData)
                            {
                                saveBlob.MetaData.Add(meta);
                            }
                        }
                    }
                    else
                    {
                        // Create
                        saveBlob = parameterBlob;

                        if (container.Blobs == null)
                        {
                            container.Blobs = new List <Blob>();
                        }

                        container.Blobs.Add(saveBlob);
                        addedToList = true;
                    }

                    saveBlob.LastModified = DateTime.Now.ToUniversalTime();
                    saveBlob.Container    = container;
                    saveBlob = BlobDao.SaveOrUpdate(saveBlob);
                }

                if (addedToList)
                {
                    container.LastModified = DateTime.Now.ToUniversalTime();
                    ContainerDao.SaveOrUpdate(container);
                }

                scope.Complete();
            }


            return(result);
        }