Ejemplo n.º 1
0
        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)};
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 3
0
        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;
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 7
0
        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();
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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();
                        }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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();
            }
        }
Ejemplo n.º 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();
            }
        }
Ejemplo n.º 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();
                }
            }
        }
Ejemplo n.º 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();
                }
            }
        }
Ejemplo n.º 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));
                }
        }
Ejemplo n.º 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();
                    }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 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)); });
        }
Ejemplo n.º 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
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 28
0
 /// <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);
Ejemplo n.º 29
0
 public void Create_ProducesTransactionScope()
 {
     _scope = _sut.CreateScope();
     Assert.That(_scope, Is.Not.Null);
     Assert.That(_scope, Is.InstanceOf <ITransactionScope>());
 }
Ejemplo n.º 30
0
 protected abstract bool CanExecuteAction(ITransactionScope transactionScope, ActionDto actionDto);
 public static void SetTransactionScope(this IState state, ITransactionScope scope)
 {
     state.Replace("TransactionScope", scope);
 }
Ejemplo n.º 32
0
 protected override bool CanExecuteAction(ITransactionScope transactionScope, ActionDto actionDto)
 {
     return actionDto.ActionGroup == "Irc";
 }
Ejemplo n.º 33
0
 public User AddUser(ITransactionScope transactionScope, string username, string password)
 {
     var user = _userRepository.Add(transactionScope, username, password);
     return user;
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 35
0
 public void SetCurrentTransactionScope(ITransactionScope transactionScope)
 {
     httpRequestService[CurrentTransactionScopeKey] = transactionScope;
 }
Ejemplo n.º 36
0
        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()};
        }
Ejemplo n.º 37
0
 public List<Client> GetClientByFilterCriteria(ITransactionScope transactionScope, ClientFilterCriteria clientFilterCriteria)
 {
     return _clientRepository.GetClientsByFilterCriteria(transactionScope, clientFilterCriteria).ToList();
 }
Ejemplo n.º 38
0
 public void Logoff(ITransactionScope transactionScope, ClientDto clientDto)
 {
     SetIsOnlineState(transactionScope, clientDto, false);
 }
Ejemplo n.º 39
0
        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};
        }
Ejemplo n.º 40
0
 public void SetCurrentScope(ITransactionScope transactionScope)
 {
     WebContext.Current.Items[_HttpContextCurrentScope] = transactionScope;
 }
Ejemplo n.º 41
0
 public static void SetTransactionScope(this IState <IPipeline> state, ITransactionScope scope)
 {
     state.Replace(StateKeys.TransactionScope, scope);
 }
Ejemplo n.º 42
0
 public void SetCurrentTransactionScope(ITransactionScope transactionScope)
 {
     currentTransactionScope = transactionScope;
 }
Ejemplo n.º 43
0
 public Scope(ITransactionScope scope, E element)
 {
     Transaction = scope;
     Element     = element;
 }
Ejemplo n.º 44
0
 public void ResetCurrentTransactionScope()
 {
     currentTransactionScope = null;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 47
0
 public List<Event> GetLastEvents(ITransactionScope transactionScope)
 {
     return _eventRepository.GetEvents(transactionScope, new EventFilterCriteria()).OrderByDescending(e => e.TriggeredDate).ToList();
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 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>());
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 51
0
 protected abstract ActionResultDto ExecuteAction(ITransactionScope transactionScope, ActionDto actionDto);
Ejemplo n.º 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;
        }
Ejemplo n.º 53
0
 /// <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);
Ejemplo n.º 54
0
 public User Login(ITransactionScope transactionScope, string username, string password)
 {
     return _userRepository.Login(transactionScope, username, password);
 }
Ejemplo n.º 55
0
 public MultiTransactionCommitter(TransactionScopeFactory transactionScopeFactory)
 {
     this.transactionScopeFactory = transactionScopeFactory;
     CurrentTransactionScope      = transactionScopeFactory.CreateReadWrite();
 }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 58
0
 public User GetUser(ITransactionScope transactionScope, string name)
 {
     return _userRepository.GetUser(transactionScope, name);
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 60
0
 public void Logon(ITransactionScope transactionScope, ClientDto clientDto)
 {
     SetIsOnlineState(transactionScope, clientDto, true);
 }