private ActionResultDto ChangeKarma(ITransactionScope transactionScope, ActionDto actionDto, int value)
        {
            var keyParam = GetParameter(actionDto, ActionGroup, "Key");
            var key = keyParam.Value;

            var karma = _karmaRepository.GetByKey(transactionScope, key);

            if (karma == null)
            {
                karma = _karmaRepository.Create();
                karma.KarmaKey = key;
                karma.KarmaValue = 0;
            }

            karma.KarmaValue = karma.KarmaValue + value;

            var newValue = karma.KarmaValue;

            if (newValue == 0)
                _karmaRepository.Delete(transactionScope, karma);
            else
                _karmaRepository.Save(transactionScope, karma);

            return new ActionResultDto() {Data = Convert.ToString(newValue)};
        }
Exemple #2
0
        public bool ChangePassword(ITransactionScope transactionScope, User user, string oldPassword, string newPassword)
        {
            if (user.Password == oldPassword)
            {
                _userRepository.ChangePassword(transactionScope, user, newPassword);
                return true;
            }

            return false;
        }
        protected override ActionResultDto ExecuteAction(ITransactionScope transactionScope, ActionDto actionDto)
        {
            var clientName = actionDto.Parameters.Where(p => p.Name == "Client").Single().Value;
            var client = ClientRepository.GetClientsByFilterCriteria(transactionScope, new ClientFilterCriteria() {Name = clientName}).SingleOrDefault();

            var restClient = new JarvisRestClient(Log);
            restClient.BaseUrl = client.Hostname;

            return restClient.Execute<ResultDto<ActionResultDto>>(new ActionExecuteRequest(){ActionDto = actionDto}, "POST").Result;
        }
Exemple #4
0
        public ActionResultDto Execute(ITransactionScope transactionScope, ActionDto actionDto)
        {
            _log.InfoFormat("Executing {0}.{1}", actionDto.ActionGroup, actionDto.Action);

            var serverAction = _actionRegistry.GetActionHandler(actionDto.ActionGroup);

            if (serverAction.CanExecute(transactionScope, actionDto))
                return serverAction.Execute(transactionScope, actionDto);

            _log.InfoFormat("ActionHandler {0} can not execute action {1}", serverAction.GetType().Name, actionDto.Action);

            return null;
        }
Exemple #5
0
        public ActionResultDto Execute(ITransactionScope transactionScope, ActionDto actionDto)
        {
            try
            {
                return ExecuteAction(transactionScope, actionDto);
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Error at executing server action {0}: {1}", this.GetType().Name, e);
            }

            return null;
        }
Exemple #6
0
        public bool CanExecute(ITransactionScope transactionScope, ActionDto actionDto)
        {
            try
            {
                return CanExecuteAction(transactionScope, actionDto);
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Error at checking executing at server action {0}: {1}", this.GetType().Name, e);
            }

            return false;
        }
        protected override ActionResultDto ExecuteAction(ITransactionScope transactionScope, ActionDto actionDto)
        {
            switch (actionDto.Action)
            {
                case "Increase":
                    return ChangeKarma(transactionScope, actionDto, 1);
                case "Decrease":
                    return ChangeKarma(transactionScope, actionDto, -1);
                case "GetKarma":
                    return GetKarma(transactionScope);
                case "Stats":
                    return GetStats(transactionScope);

            }

            throw new ArgumentOutOfRangeException();
        }
Exemple #8
0
        protected override ActionResultDto ExecuteAction(ITransactionScope transactionScope, ActionDto actionDto)
        {
            if (actionDto.Action == "Move" || actionDto.Action == "Copy")
            {
                var sourceClientParameter = GetParameter(actionDto, "File", "SourceClient");
                var targetClientParameter = GetParameter(actionDto, "File", "TargetClient");

                if (sourceClientParameter.Value == targetClientParameter.Value)
                {
                    return ExecuteFileAction(transactionScope, actionDto);
                }

                var sourcePathParameter = GetParameter(actionDto, "File", "SourcePath");
                var targetPathParameter = GetParameter(actionDto, "File", "TargetPath");

                var readDataAction = new ActionDto()
                                         {
                                             ActionGroup = "File",
                                             Action = "Read",
                                             Parameters = new List<ParameterDto>()
                                                              {
                                                                  new ParameterDto() { Category = "File", Name = "Path", Value = sourcePathParameter.Value }
                                                              }
                                         };

                var readDataResult = ExecuteFileAction(transactionScope, readDataAction);

                var writeDataAction = new ActionDto()
                                        {
                                            ActionGroup = "File",
                                            Action = "Write",
                                            Parameters = new List<ParameterDto>()
                                                                                      {
                                                                                          new ParameterDto() { Category = "File", Name = "Path", Value = targetPathParameter.Value },
                                                                                          new ParameterDto() {Category = "File", Name = "Data", Value = readDataResult.Data}
                                                                                      }
                                        };

                ExecuteFileAction(transactionScope, writeDataAction);

                return new ActionResultDto();
            }

            return ExecuteFileAction(transactionScope, actionDto);
        }
        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);
        }
Exemple #10
0
        internal ITransactionScope ReadScope()
        {
#if NLOG
            if (Log.IsTraceEnabled)
            {
                Log.Trace("Begin read transaction");
            }
#endif
            var result = Current;

            if (result == null)
            {
                result = new BulkReadScope();
            }

            result.AddRef();

            return(Current = result);
        }
Exemple #11
0
        static void WiffToSQLite()
        {
            string wiffPath   = @"C:\Work\primaqdev\testdata\Für Alex\20160212_MS_DHpsan006.wiff";
            string mzLitePath = Path.Combine(Path.GetDirectoryName(wiffPath), Path.GetFileNameWithoutExtension(wiffPath) + ".mzlite");
            string runID      = "sample=0";
            int    msLevel;

            if (File.Exists(mzLitePath))
            {
                File.Delete(mzLitePath);
            }

            using (IMzLiteDataReader reader = new WiffFileReader(wiffPath))
                using (ITransactionScope inTxn = reader.BeginTransaction())
                    using (MzLiteSQL writer = new MzLiteSQL(mzLitePath))
                        using (ITransactionScope outTxn = writer.BeginTransaction())
                        {
                            foreach (var ms in reader.ReadMassSpectra(runID))
                            {
                                if (ms.TryGetMsLevel(out msLevel) && msLevel != 1)
                                {
                                    continue;
                                }

                                var peaks = reader.ReadSpectrumPeaks(ms.ID);
                                //var clonedMS = MzLiteJson.JsonCloneModelItem("#1", ms);
                                //var max = peaks.Peaks.GroupBy(x => x.Intensity);

                                writer.Insert(runID, ms, peaks);
                                //break;
                            }

                            //foreach (var ms in writer.ReadMassSpectra(runID))
                            //{
                            //    var peaks = writer.ReadSpectrumPeaks(ms.ID);
                            //    var ms1 = writer.ReadMassSpectrum(ms.ID);
                            //    break;
                            //}

                            outTxn.Commit();
                        }
        }
Exemple #12
0
        public RunnedWorkflowDto GetWorkflowToExecute(ITransactionScope transactionScope)
        {
            var workflowToExecute = _workflowQueueRepository.GetNextQueuedWorkflowAndSetStarttime(transactionScope);

            if (workflowToExecute == null)
            {
                return null;
            }

            var runnedWorkflow = CreateRunnedWorkflow(transactionScope, workflowToExecute.DefinedWorkflow, workflowToExecute.Event);
            workflowToExecute.RunnedWorkflow = runnedWorkflow;

            _workflowQueueRepository.Save(transactionScope, workflowToExecute);

            transactionScope.Flush();

            _runnedWorkflowRepository.Refresh(transactionScope, runnedWorkflow);

            return TranslateToDto(runnedWorkflow);
        }
Exemple #13
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();
            }
        }
Exemple #14
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();
            }
        }
Exemple #15
0
        public void EditAccount(AccountInfo accountInfo)
        {
            using (this.unitOfWorkProvider.CreateUnitOfWork())
            {
                IAccount account = this.accountRepository.GetAccount(accountInfo.Id);

                if (account == null)
                {
                    throw new PalantirException("Account is not found");
                }

                using (ITransactionScope transaction = Factory.GetInstance <ITransactionScope>().Begin())
                {
                    account.Title             = accountInfo.Title;
                    account.MaxProjectsCount  = accountInfo.MaxProjectsCount;
                    account.CanDeleteProjects = accountInfo.CanDeleteProjects;

                    this.accountRepository.Save(account);
                    transaction.Commit();
                }
            }
        }
Exemple #16
0
        public void DeleteUser(int userId)
        {
            // TODO: Implement multi user logic
            using (this.unitOfWorkProvider.CreateUnitOfWork())
            {
                IProjectRepository projectRepository = this.projectRepositoryFactory();
                IList <Project>    projects          = projectRepository.GetByAccountId(userId);
                User user = this.userRepository.GetUserById(userId);

                using (ITransactionScope transaction = Factory.GetInstance <ITransactionScope>().Begin())
                {
                    foreach (var project in projects)
                    {
                        projectRepository.Delete(project);
                    }

                    this.userRepository.Delete(user);

                    transaction.Commit();
                }
            }
        }
Exemple #17
0
        static void TestRt()
        {
            string wiffPath = @"C:\Work\primaqdev\testdata\swathtest\20141201_BASF5_1SW01.wiff";
            string runID    = "sample=0";

            using (var reader = new WiffFileReader(wiffPath))
                using (ITransactionScope txn = reader.BeginTransaction())
                {
                    var rti       = reader.BuildRtIndex(runID);
                    var rtQuery   = new RangeQuery(56.8867263793945, 10.0);
                    var mzQueries = new RangeQuery[]
                    {
                        new RangeQuery(890.4764, 0.01),
                        new RangeQuery(677.3651, 0.01),
                        new RangeQuery(989.5448, 0.01),
                        new RangeQuery(776.4335, 0.01)
                    };

                    var profile = reader.RtProfiles(rti, rtQuery, mzQueries);
                    var profil  = reader.RtProfile(rti, rtQuery, new RangeQuery(776.4335, 0.01));
                }
        }
Exemple #18
0
        static void TestSwath()
        {
            string wiffPath       = @"C:\Work\primaqdev\testdata\swathtest\20141201_BASF5_1SW01.wiff";
            string searchListPath = @"C:\Work\primaqdev\testdata\swathtest\result_N14 - Ions.txt";
            string runID          = "sample=0";

            using (var reader = new WiffFileReader(wiffPath))
                using (ITransactionScope txn = reader.BeginTransaction())
                    using (var csv = CSVReader.GetTabReader(searchListPath))
                    {
                        var swath = SwathIndexer.Create(reader, runID);

                        var queuries = csv.ReadAll()
                                       .GroupBy(x => x.GetDouble("Precursor MZ"))
                                       .Select(x => CreateSwathQuery(x, 1.0, 0.05))
                                       .ToArray();

                        SwathQuerySorting.Sort(queuries);

                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        for (int i = 0; i < queuries.Length; i++)
                        {
                            if (i % 10 == 0)
                            {
                                Console.WriteLine(i);
                            }

                            var ms2 = swath.GetMS2(reader, queuries[i]);
                        }

                        stopwatch.Stop();
                        Console.WriteLine("Elapsed time: {0}", stopwatch.Elapsed.ToString());

                        Console.WriteLine("Press any key to exit.");
                        System.Console.ReadKey();
                    }
        }
Exemple #19
0
        private void DisposeSession(SessionDataContext ctx)
        {
            try
            {
                if (_scope != null)
                {
                    using (CodeMarker.MarkBlock("Session.ScopeDispose"))
                    {
                        _scope.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                var exception = ex;
                if (exception is AggregateException)
                {
                    exception = ((AggregateException)ex).InnerException;
                }
                Log(new DiagnosticMessage(MessageType.Error, exception.Message, "Session", SessionDataContext.InValidationProcess, null, exception));
            }
            _scope = null;

            try
            {
                // Libération des locks
                Store.LockManager.ReleaseLocks(ctx.Locks, ctx.Aborted);
            }
            catch (Exception ex)
            {
                throw new CriticalException(ExceptionMessages.CriticalErrorMaybeAwaitInSession, ex);
            }

            // Suppression de la session courante. Il n'est plus possible de faire référence à la session
            ctx.Current        = null;
            SessionDataContext = null;
            ResetSessionIndex(true);
        }
        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);
        }
Exemple #21
0
        public ClientDto RegisterClient(ITransactionScope transactionScope, ClientDto clientDto)
        {
            Client client = _clientRepository.GetClientsByFilterCriteria(transactionScope, new ClientFilterCriteria() {Name = clientDto.Name}).SingleOrDefault();
            ;
            if (client == null)
            {
                client = _clientRepository.Create();
            }

            client.Name = clientDto.Name;
            client.Hostname = clientDto.Hostname;
            client.Type = clientDto.Type;

            _clientRepository.Save(transactionScope, client);

            transactionScope.Flush();

            _clientRepository.Refresh(transactionScope, client);

            clientDto.Id = client.Id;

            return clientDto;
        }
Exemple #22
0
        public void eventRaised(ITransactionScope transactionScope, EventDto eventDto)
        {
            var client = _clientRepository.GetById(transactionScope, eventDto.ClientId);

            var raisedEvent = new Event()
                                  {
                                      EventGroupType = eventDto.EventGroupType,
                                      EventType = eventDto.EventType,
                                      TriggeredDate = eventDto.TriggeredDate,
                                      Data = eventDto.Data,
                                      Client = client
                                  };

            _eventRepository.Save(transactionScope, raisedEvent);

            var eventhandlerClients = _clientLogic.GetClientByFilterCriteria(transactionScope, new ClientFilterCriteria() { Type = ClientTypeEnum.Eventhandler, IsOnline = true });

            var eventhandlerClient = eventhandlerClients.FirstOrDefault();

            if (eventhandlerClient != null)
            {
                TriggerEventForEventhandlerClient(eventhandlerClient);
            }
        }
        public DeleteServiceTests()
        {
            _indexDataStore      = Substitute.For <IIndexDataStore>();
            _metadataStore       = Substitute.For <IMetadataStore>();
            _fileDataStore       = Substitute.For <IFileStore>();
            _deleteConfiguration = new DeletedInstanceCleanupConfiguration
            {
                DeleteDelay     = TimeSpan.FromDays(1),
                BatchSize       = 10,
                MaxRetries      = 5,
                PollingInterval = TimeSpan.FromSeconds(1),
                RetryBackOff    = TimeSpan.FromDays(4),
            };

            IOptions <DeletedInstanceCleanupConfiguration> deletedInstanceCleanupConfigurationOptions = Substitute.For <IOptions <DeletedInstanceCleanupConfiguration> >();

            deletedInstanceCleanupConfigurationOptions.Value.Returns(_deleteConfiguration);
            ITransactionHandler transactionHandler = Substitute.For <ITransactionHandler>();

            _transactionScope = Substitute.For <ITransactionScope>();
            transactionHandler.BeginTransaction().Returns(_transactionScope);

            _deleteService = new DeleteService(_indexDataStore, _metadataStore, _fileDataStore, deletedInstanceCleanupConfigurationOptions, transactionHandler, NullLogger <DeleteService> .Instance);
        }
Exemple #24
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)); });
        }
Exemple #25
0
        public void ITransactionScope_IsActiveScope()
        {
            ClientTransaction clientTransaction = ClientTransaction.CreateRootTransaction();

            try
            {
                ITransactionScope outerScope = clientTransaction.EnterDiscardingScope();
                Assert.That(outerScope.IsActiveScope, Is.True);

                using (ClientTransactionScope innerScope = clientTransaction.CreateSubTransaction().EnterDiscardingScope())
                {
                    Assert.That(outerScope.IsActiveScope, Is.False);
                    Assert.That(((ITransactionScope)innerScope).IsActiveScope, Is.True);
                }

                Assert.That(outerScope.IsActiveScope, Is.True);
                outerScope.Leave();
                Assert.That(outerScope.IsActiveScope, Is.False);
            }
            finally
            {
                ClientTransactionScope.ResetActiveScope(); // for TearDown
            }
        }
Exemple #26
0
        internal ITransactionScope WriteScope()
        {
#if NLOG
            if (Log.IsTraceEnabled)
            {
                Log.Trace("Begin write transaction");
            }
#endif
            var result = Current;

            if (result is BulkReadScope)
            {
                throw new InvalidOperationException("Nested write transaction inside read only one");
            }

            if (result == null)
            {
                result = new BulkWriteScope();
            }

            result.AddRef();

            return(Current = result);
        }
Exemple #27
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();
        }
 /// <summary>
 ///     Wrap the async Dapper call with default connection setup, disposal, and exception handling.
 /// </summary>
 /// <typeparam name="T">The DTO type to return.</typeparam>
 /// <param name="sql">The sql to execute.</param>
 /// <param name="parameters">The parameters to supply to the query, if any.</param>
 /// <param name="scope">The transaction scope.</param>
 /// <returns>The database result or null.</returns>
 protected Task <T> QueryFirstOrDefaultAsync <T>(string sql, object parameters, ITransactionScope scope) =>
 scope.Connection.QueryFirstOrDefaultAsync <T>(sql, parameters, scope.Transaction);
Exemple #29
0
 public void Create_ProducesTransactionScope()
 {
     _scope = _sut.CreateScope();
     Assert.That(_scope, Is.Not.Null);
     Assert.That(_scope, Is.InstanceOf <ITransactionScope>());
 }
Exemple #30
0
 protected abstract bool CanExecuteAction(ITransactionScope transactionScope, ActionDto actionDto);
 public static void SetTransactionScope(this IState state, ITransactionScope scope)
 {
     state.Replace("TransactionScope", scope);
 }
 protected override bool CanExecuteAction(ITransactionScope transactionScope, ActionDto actionDto)
 {
     return actionDto.ActionGroup == "Irc";
 }
Exemple #33
0
 public User AddUser(ITransactionScope transactionScope, string username, string password)
 {
     var user = _userRepository.Add(transactionScope, username, password);
     return user;
 }
Exemple #34
0
        private void SetIsOnlineState(ITransactionScope transactionScope, ClientDto clientDto, bool isOnline)
        {
            var client = _clientRepository.GetById(transactionScope, clientDto.Id);

            if (client == null)
            {
                throw new Exception("client not registered");
            }

            client.IsOnline = isOnline;
            clientDto.Hostname = clientDto.Hostname;
            _clientRepository.Save(transactionScope, client);
        }
Exemple #35
0
 public void SetCurrentTransactionScope(ITransactionScope transactionScope)
 {
     httpRequestService[CurrentTransactionScopeKey] = transactionScope;
 }
        private ActionResultDto GetKarma(ITransactionScope transactionScope)
        {
            var karmaEntities = _karmaRepository.GetAll(transactionScope);

            Decimal stats = 0;

            if (karmaEntities.Any())
            {
                stats = Decimal.Divide(karmaEntities.Sum(k => k.KarmaValue), karmaEntities.Count());

            }

            return new ActionResultDto() {Data = stats.ToString()};
        }
Exemple #37
0
 public List<Client> GetClientByFilterCriteria(ITransactionScope transactionScope, ClientFilterCriteria clientFilterCriteria)
 {
     return _clientRepository.GetClientsByFilterCriteria(transactionScope, clientFilterCriteria).ToList();
 }
Exemple #38
0
 public void Logoff(ITransactionScope transactionScope, ClientDto clientDto)
 {
     SetIsOnlineState(transactionScope, clientDto, false);
 }
        private ActionResultDto GetStats(ITransactionScope transactionScope)
        {
            var karmaEntities = _karmaRepository.GetAll(transactionScope);

            var result = String.Join(" ", karmaEntities.Select(k => k.KarmaKey + ": " + k.KarmaValue));

            return new ActionResultDto(){Data = result};
        }
 public void SetCurrentScope(ITransactionScope transactionScope)
 {
     WebContext.Current.Items[_HttpContextCurrentScope] = transactionScope;
 }
Exemple #41
0
 public static void SetTransactionScope(this IState <IPipeline> state, ITransactionScope scope)
 {
     state.Replace(StateKeys.TransactionScope, scope);
 }
Exemple #42
0
 public void SetCurrentTransactionScope(ITransactionScope transactionScope)
 {
     currentTransactionScope = transactionScope;
 }
Exemple #43
0
 public Scope(ITransactionScope scope, E element)
 {
     Transaction = scope;
     Element     = element;
 }
Exemple #44
0
 public void ResetCurrentTransactionScope()
 {
     currentTransactionScope = null;
 }
Exemple #45
0
 /// <summary>
 /// Deconstructs request.
 /// </summary>
 /// <param name="command">Value of <see cref="Command"/>.</param>
 /// <param name="context">Value of <see cref="Context"/>.</param>
 /// <param name="transactionScope">Value of <see cref="TransactionScope"/>.</param>
 public void Deconstruct(out TCommand command, out AggregateExecutionContext context, out ITransactionScope transactionScope)
 {
     command          = Command;
     context          = Context;
     transactionScope = TransactionScope;
 }
Exemple #46
0
        private void CreateRunnedNextWorkflowSteps(ITransactionScope transactionScope,
                                                   IList<DefinedNextWorkflowStep> nextWorkflowSteps, 
                                                   RunnedWorkflow runnedWorkflow,
                                                   List<RunnedWorkflowStep> runnedWorkflowSteps)
        {
            foreach (var definedNextWorkflowStep in nextWorkflowSteps)
            {
                var runnedNextWorkflowStep = _runnedNextWorkflowStepRepository.Create();
                runnedNextWorkflowStep.RunnedWorkflow = runnedWorkflow;
                runnedNextWorkflowStep.DefinedNextWorkflowStep = definedNextWorkflowStep;

                if (definedNextWorkflowStep.NextStep == null)
                {
                    runnedNextWorkflowStep.NextStep = null;
                }
                else
                {
                    runnedNextWorkflowStep.NextStep =
                        runnedWorkflowSteps.Where(rws => rws.DefinedWorkflowStep == definedNextWorkflowStep.NextStep).Single();
                }

                if (definedNextWorkflowStep.PreviousStep == null)
                {
                    runnedNextWorkflowStep.PreviousStep = null;
                }
                else
                {
                    runnedNextWorkflowStep.PreviousStep =
                        runnedWorkflowSteps.Where(rws => rws.DefinedWorkflowStep == definedNextWorkflowStep.PreviousStep).Single();
                }

                _runnedNextWorkflowStepRepository.Save(transactionScope, runnedNextWorkflowStep);
            }
        }
Exemple #47
0
 public List<Event> GetLastEvents(ITransactionScope transactionScope)
 {
     return _eventRepository.GetEvents(transactionScope, new EventFilterCriteria()).OrderByDescending(e => e.TriggeredDate).ToList();
 }
Exemple #48
0
        private RunnedTask CreateRunnedTask(ITransactionScope transactionScope, DefinedTask definedTask)
        {
            var runnedTask = _runnedTaskRepository.Create();
            runnedTask.DefinedTask = definedTask;
            runnedTask.RunCode = definedTask.RunCode;

            _runnedTaskRepository.Save(transactionScope, runnedTask);

            return runnedTask;
        }
Exemple #49
0
 public void CreateWithOptionAndAsyncFlow_ProducesTransactionScope()
 {
     _scope = _sut.CreateScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
     Assert.That(_scope, Is.Not.Null);
     Assert.That(_scope, Is.InstanceOf <ITransactionScope>());
 }
Exemple #50
0
        private RunnedWorkflow CreateRunnedWorkflow(ITransactionScope transactionScope, DefinedWorkflow definedWorkflow, Event eventInformation)
        {
            var runnedWorkflow = _runnedWorkflowRepository.Create();
            runnedWorkflow.DefinedWorkflow = definedWorkflow;
            _runnedWorkflowRepository.Save(transactionScope, runnedWorkflow);

            var runnedWorkflowSteps = CreateRunnedWorkflowSteps(transactionScope, definedWorkflow.WorkflowSteps, runnedWorkflow);
            CreateRunnedNextWorkflowSteps(transactionScope, definedWorkflow.NextWorkflowSteps, runnedWorkflow, runnedWorkflowSteps);

            CreateParameters(transactionScope, runnedWorkflow, eventInformation);

            return runnedWorkflow;
        }
Exemple #51
0
 protected abstract ActionResultDto ExecuteAction(ITransactionScope transactionScope, ActionDto actionDto);
Exemple #52
0
        private List<RunnedWorkflowStep> CreateRunnedWorkflowSteps(ITransactionScope transactionScope, IList<DefinedWorkflowStep> workflowSteps, RunnedWorkflow runnedWorkflow)
        {
            var runnedWorkflowSteps = new List<RunnedWorkflowStep>();

            foreach (var definedWorkflowStep in workflowSteps)
            {
                var runnedWorkflowStep = _runnedWorkflowStepRepository.Create();
                runnedWorkflowStep.RunnedWorkflow = runnedWorkflow;
                runnedWorkflowStep.DefinedWorkflowStep = definedWorkflowStep;
                runnedWorkflowStep.RunnedTask = CreateRunnedTask(transactionScope, definedWorkflowStep.DefinedTask);

                _runnedWorkflowStepRepository.Save(transactionScope, runnedWorkflowStep);

                runnedWorkflowSteps.Add(runnedWorkflowStep);
            }

            return runnedWorkflowSteps;
        }
 /// <summary>
 ///     Wrap the async Dapper call with default connection setup, disposal, and exception handling.
 /// </summary>
 /// <param name="sql">The command to execute.</param>
 /// <param name="parameters">The parameters to supply to the command, if any.</param>
 /// <param name="scope">The transaction scope.</param>
 /// <returns>The number of rows affected.</returns>
 protected Task <int> ExecuteStoredProcedureAsync(string sql, object parameters, ITransactionScope scope) =>
 scope.Connection.ExecuteAsync(sql, parameters, scope.Transaction, null, CommandType.StoredProcedure);
Exemple #54
0
 public User Login(ITransactionScope transactionScope, string username, string password)
 {
     return _userRepository.Login(transactionScope, username, password);
 }
 public MultiTransactionCommitter(TransactionScopeFactory transactionScopeFactory)
 {
     this.transactionScopeFactory = transactionScopeFactory;
     CurrentTransactionScope      = transactionScopeFactory.CreateReadWrite();
 }
Exemple #56
0
        private void CreateParameters(ITransactionScope transactionScope, RunnedWorkflow runnedWorkflow, Event eventInformation)
        {
            var reader = JsonParser.GetJsonSerializer().Deserialize<Dictionary<string, string>>(eventInformation.Data);

            _parameterRepository.Save(transactionScope, _parameterRepository.Create(runnedWorkflow, "EventParameter", "Client", eventInformation.Client.Name));
            _parameterRepository.Save(transactionScope, _parameterRepository.Create(runnedWorkflow, "EventParameter", "EventGroupType", eventInformation.EventGroupType));
            _parameterRepository.Save(transactionScope, _parameterRepository.Create(runnedWorkflow, "EventParameter", "EventType", eventInformation.EventType));

            foreach (var row in reader)
            {
                var parameter = _parameterRepository.Create(runnedWorkflow, "EventParameter", row.Key, row.Value);

                _parameterRepository.Save(transactionScope, parameter);
            }
        }
Exemple #57
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);
        }
Exemple #58
0
 public User GetUser(ITransactionScope transactionScope, string name)
 {
     return _userRepository.GetUser(transactionScope, name);
 }
Exemple #59
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);
        }
Exemple #60
0
 public void Logon(ITransactionScope transactionScope, ClientDto clientDto)
 {
     SetIsOnlineState(transactionScope, clientDto, true);
 }