public RoutineManager(ITransaction transaction)
        {
            if (transaction == null)
                throw new ArgumentNullException("transaction");

            this.transaction = transaction;
        }
 protected void ClearSession() {
     Trace.WriteLine("Flush and clear session");
     _transaction.Commit();
     _session.Clear();
     _transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted);
     Trace.WriteLine("Flushed and cleared session");
 }
Beispiel #3
0
 public void SetUp()
 {
     BeforeSetUp();
     Session = SessionFactory.OpenSession();
     Transaction = Session.BeginTransaction();
     AfterSetUp();
 }
Beispiel #4
0
        public IEnumerable<Dictionary<string, object>> RawRead(string tableName, Dictionary<string, object> id, ITransaction transaction = null)
        {
            if (!DataStore.ContainsKey(tableName))
                return new List<Dictionary<string, object>>();

            return DataStore[tableName].FindByFieldValues(id);
        }
Beispiel #5
0
        public IEnumerable<Dictionary<string, object>> RawReadAll(string tableName, ITransaction transaction = null)
        {
            if (!DataStore.ContainsKey(tableName))
                return new List<Dictionary<string, object>>();

            return DataStore[tableName];
        }
 /// <summary>
 /// ���캯��
 /// </summary>
 public UnitOfWorkSynchronization(ITransaction transaction, UnitOfWorkDelegate unitOfWorkDelegate)
 {
     _transaction = transaction;
     _unitOfWorkDelegate = unitOfWorkDelegate;
     _asyncMessageBus = DependencyResolver.Resolve<IAsyncMessageBus>();
     _logger = DependencyResolver.Resolve<ILoggerFactory>().Create("EventSourcing.UnitOfWorkSynchronization");
 }
Beispiel #7
0
        public Dictionary<string, object> Insert(string tableName, Dictionary<string, object> row, ITransaction transaction = null)
        {
            if (!DataStore.ContainsKey(tableName))
                DataStore.Add(tableName, new FakeDBTable());

            var table = DataStore[tableName];

            var dictToUse = row.Copy();
            //var id = DataStore[tableName].Count + 1;
            var primaryKeys = Analyzer.GetPrimaryKeys(tableName);
            var autoKey = Analyzer.GetAutoNumberKey(tableName);

            if (autoKey != null)
            {
                if (!dictToUse.ContainsKey(autoKey))
                    dictToUse.Add(autoKey, table.NextAutoKey++);
                else
                    dictToUse[autoKey] = table.NextAutoKey++;
            }

            var invalid = primaryKeys.Where(key => dictToUse[key] == null);
            if (invalid.Any())
                throw new KeyNotSetException(tableName, invalid);

            table.Add(dictToUse);
            return dictToUse.WhereKeys(key => primaryKeys.Contains(key));
        }
 public void Start()
 {
     _session = _sessionSource.CreateSession();
     _session.FlushMode = FlushMode.Commit;
     _transaction = _session.BeginTransaction();
     _isInitialized = true;
 }
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _sessionFactory = sessionFactory;
     CurrentSession = _sessionFactory.OpenSession();
     //CurrentSession.EnableFilter("translationFilter").SetParameter("locale", Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName);
     _transaction = CurrentSession.BeginTransaction();
 }
Beispiel #10
0
        public SchemaManager(ITransaction transaction)
        {
            if (transaction == null)
                throw new ArgumentNullException("transaction");

            Transaction = transaction;
        }
        public void Intercept(IInvocation invocation)
        {
            var sessionFactories = NHibernateSessionManager.SessionFactories;
            var method = invocation.Method;
            var isTransactionScoped = method.IsDecoratedBy(typeof(TransactionAttribute));

            if (isTransactionScoped) {
                foreach (var sessionFactory in sessionFactories)
                {
                    var session = sessionFactory.GetSession();

                    _transaction = sessionFactory.GetSession().Transaction.IsActive
                                ? _session.Transaction
                                : _session.BeginTransaction();
                }
                _transaction = _session.Transaction;

                try {
                    invocation.Proceed();

                    _transaction.Commit();
                } catch (Exception) {
                    _transaction.Rollback();

                    throw;
                } finally {
                    _transaction.Dispose();
                }
            }
        }
Beispiel #12
0
        public void DetachFrom(ITransaction transaction)
        {
            transaction.UnregisterOnCommit(OnCommit);

            if (transaction is ICallbackHandler)
                ((ICallbackHandler)transaction).OnCallbackDetached(this);
        }
Beispiel #13
0
        public void AttachTo(ITransaction transaction)
        {
            transaction.RegisterOnCommit(OnCommit);

            if (transaction is ICallbackHandler)
                ((ICallbackHandler)transaction).OnCallbackAttached(this);
        }
        public void RequireNew(IsolationLevel level) {
            EnsureSession();

            if (_enableTransaction)
            {
                if (_cancelled)
                {
                    if (_transaction != null)
                    {
                        _transaction.Rollback();
                        _transaction.Dispose();
                        _transaction = null;
                    }

                    _cancelled = false;
                }
                else
                {
                    if (_transaction != null)
                    {
                        _transaction.Commit();
                    }
                }

                Logger.Debug("Creating new transaction with isolation level {0}", level);
                _transaction = _session.BeginTransaction(level);
            }
        }
 public ISession BeginOperation()
 {
     try
     {
         session = PersistenceManager.Istance.GetSession();
         if (session.Transaction.IsActive)
         {
             isInternalTransaction = false;
             tx = session.Transaction;
             logger.Debug(GetCallerClassDotMethod() + " si è agganciato alla transazione " + tx.GetHashCode());
         }
         else
         {
             isInternalTransaction = true;
             tx = session.Transaction;
             tx.Begin();
             logger.Debug("Transazione " + tx.GetHashCode() + " creata da " + GetCallerClassDotMethod());
         }
         logger.Debug("La sessione è " + session.GetHashCode());
         return session;
     }
     catch (Exception ex)
     {
         string msg = "Errore nell'apertura dell'operazione";
         logger.ErrorException(msg, ex);
         throw new Exception(msg, ex);
     }
 }
    // User profiles

    public static IDbCommand SelectUserProfilesCommand(ITransaction transaction, Guid? profileId, string name,
        out int profileIdIndex, out int nameIndex)
    {
      ISQLDatabase database = transaction.Database;
      IDbCommand result = transaction.CreateCommand();
      result.CommandText = "SELECT PROFILE_ID, NAME FROM USER_PROFILES";

      IList<string> filters = new List<string>(2);
      if (profileId.HasValue)
        filters.Add("PROFILE_ID=@PROFILE_ID");
      if (!string.IsNullOrEmpty(name))
        filters.Add("NAME=@NAME");

      if (filters.Count > 0)
        result.CommandText += " WHERE " + StringUtils.Join(" AND ", filters);

      if (profileId.HasValue)
        database.AddParameter(result, "PROFILE_ID", profileId, typeof(Guid));
      if (!string.IsNullOrEmpty(name))
        database.AddParameter(result, "NAME", name, typeof(string));

      profileIdIndex = 0;
      nameIndex = 1;
      return result;
    }
        public UnitOfWork(ISession session)
        {
            Guard.AgainstNull(() => session);

            this.session = session;
            this.transaction = session.BeginTransaction(IsolationLevel.ReadCommitted);
        }
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _sessionFactory = sessionFactory;
     Session = _sessionFactory.OpenSession();
     Session.FlushMode = FlushMode.Auto;
     _transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
 }
Beispiel #19
0
        private void SubmitCheck( IDataProvider provider )
        {
            int accountId = int.Parse( ddlAccount.SelectedValue );

            IAccount account = provider.GetAccount( accountId );
            if( account == null )
                throw new ApplicationException( "Account " + accountId + " not found in data storage." );

            IAccount expenseAccount = provider.GetAccount( 2 );
            if( expenseAccount == null )
                throw new ApplicationException( "Expense account not found in data storage." );

            this.trans = provider.NewTransaction();
            trans.Amount = Convert.ToDecimal( txtAmount.Text );
            trans.TransactionDate = DateTime.Parse( txtDate.Text );
            trans.Payee = txtPayee.Text;
            if( txtMemo.Text.Length > 0 ) trans.Memo = txtMemo.Text;
            trans.IsEstimated = chkEstimated.Checked;

            ILineItem credit = trans.NewLineItem();
            credit.SetAccount( account );
            credit.Amount = trans.Amount;
            credit.Category = null;
            credit.Memo = trans.Memo;
            if( txtNumber.Text.Length > 0 ) credit.Number = txtNumber.Text;
            credit.TransactionType = TransactionType.Credit;
            credit.IsTaxRelated = this.chkDeductible.Checked;

            ILineItem debit = trans.NewLineItem();
            debit.SetAccount( expenseAccount );
            debit.Amount = credit.Amount;
            debit.Category = txtCategory.Text;
            debit.TransactionType = TransactionType.Debit;
            debit.IsTaxRelated = this.chkDeductible.Checked;
        }
 protected void SessionInitializeTransaction()
 {
     if (session == null) {
         session = NHibernateHelper.OpenSession ();
         tx = session.BeginTransaction ();
     }
 }
Beispiel #21
0
        public TransactionElection(ITransaction transaction)
        {
            if (transaction == null)
            throw new ArgumentNullException("transaction");

             _transaction = transaction;
        }
        public void Dispose()
        {
            if (disposed)
                return;

            if (session == null)
                return;

            try
            {
                if (preventCommit)
                    transaction.Rollback();
                else
                    transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                transaction.Dispose();
            }

            session.Dispose();
            session = null;
            transaction = null;
            disposed = true;
        }
 public void Commit()
 {
     if (_transaction == null) return;
     _transaction.Commit();
     _transaction.Dispose();
     _transaction = null;
 }
Beispiel #24
0
 //查找用户的基本套餐
 public Int32 getId(Int64 num)
 {
     trans = session.BeginTransaction();
     try
     {
         IEnumerable<Rule> rule = session.CreateQuery("from Rule as c where c.Mobilenumber='" + num + "'").List<Rule>();
         Int32 id = 0;
         foreach (Rule r in rule)
         {
             if (r.Chargeid == 1)
             {
                 id = 1;
                 break;
             }
             else if (r.Chargeid == 2)
             {
                 id = 2;
                 break;
             }
             else if (r.Chargeid == 3)
             {
                 id = 3;
                 break;
             }
             else continue;
         }
         return id;
     }
     catch (Exception)
     {
         throw new Exception();
     }
 }
Beispiel #25
0
		protected override void OnSetUp()
		{
			session = OpenSession();
			tran = session.BeginTransaction();

			// save some data
			Document doc = new Document(1, "test doc");
			Image img = new Image(1, doc, "c:\a.jpg");
			Paragraph para = new Paragraph(2, doc, "Arial");
			Page p1 = new Page(1, doc);
			p1.IsActive = true;
			Page p2 = new Page(2, doc);
			p2.IsActive = false;
			Review r = new Review(10, doc, "this is a good document"); // this id is 10 on purpose (to be != docId)

			session.Save(doc);
			session.Save(img);
			session.Save(para);
			session.Save(p1);
			session.Save(p2);
			session.Save(r);

			session.Flush();
			session.Clear();
		}
 public void BeginTransaction()
 {
     if (_transaction == null)
     {
         _transaction = Session.BeginTransaction();
     }
 }
 private void OnNewTransaction(ITransaction transaction, TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction)
 {
     if (!transaction.DistributedTransaction)
     {
         transaction.Enlist(new RhinoTransactionResourceAdapter(transactionMode));
     }
 }
Beispiel #28
0
 public UnitOfWork(IProvider dataProvider)
 {
     provider = dataProvider as Provider;
     if (provider == null)
         throw new Exception("Invalid Data Provider");
     transaction = provider.Session.BeginTransaction();
 }
Beispiel #29
0
 public void SetUp()
 {
     // new session on every test
     Session = FixtureSetup.Container.Resolve<ISessionFactory>().OpenSession();
     FixtureSetup.Container.Register(x => this.Session);
     _transaction = Session.BeginTransaction();
 }
 public void Setup()
 {
     session = WindsorPersistenceFixture.Container.Resolve<ISession>();
     repository = new SecurityRepository();
     repository.Session = session;
     tx = session.BeginTransaction();
 }
Beispiel #31
0
        public void MergeDeepTree()
        {
            ClearCounts();

            var root = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "root"
            };
            var child = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "child"
            };
            var grandchild = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "grandchild"
            };

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    root.AddChild(child);
                    child.AddChild(grandchild);
                    s.Merge(root);
                    tx.Commit();
                }

            AssertInsertCount(3);
            AssertUpdateCount(0);
            ClearCounts();

            grandchild.Description = "the grand child";
            var grandchild2 = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "grandchild2"
            };

            child.AddChild(grandchild2);

            using (var s = OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    s.Merge(root);
                    tx.Commit();
                }

            AssertInsertCount(1);
            AssertUpdateCount(1);
            ClearCounts();

            var child2 = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "child2"
            };
            var grandchild3 = new Node
            {
                Created = RoundForDialect(DateTime.Now),
                Name    = "grandchild3"
            };

            child2.AddChild(grandchild3);
            root.AddChild(child2);

            using (var s = OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    s.Merge(root);
                    tx.Commit();
                }

            AssertInsertCount(2);
            AssertUpdateCount(0);
            ClearCounts();

            using (var s = OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    s.Delete(grandchild);
                    s.Delete(grandchild2);
                    s.Delete(grandchild3);
                    s.Delete(child);
                    s.Delete(child2);
                    s.Delete(root);
                    tx.Commit();
                }
        }
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            const string queueVendorName = "Msmq";
            var          queue           = instrumentedMethodCall.MethodCall.InvocationTarget as MessageQueue;

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

            var segment = transaction.StartMessageBrokerSegment(instrumentedMethodCall.MethodCall, MessageBrokerDestinationType.Queue, MessageBrokerAction.Purge, queueVendorName, queue.QueueName);

            return(Delegates.GetDelegateFor(segment));
        }
Beispiel #33
0
 /// <summary>
 /// Removes the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public async Task <bool> RemoveAsync(ITransaction tran, TKey key)
 {
     return(await tran.HashDeleteAsync(RedisKey, KeySerializer.Serialize(key)));
 }
Beispiel #34
0
        /// <summary>
        /// Remove an existing <see cref="IReliableIndexedDictionary{TKey, TValue}"/> with the given name, along with its indexes.
        /// The state is permanently removed from storage and all replicas when this transaction commits.
        /// </summary>
        /// <remarks>
        /// The index definitions indicate the indexes that should be created, or which should exist with this reliable collection.  The index definitions should be
        /// consistent when creating/reading/removing reliable collections, and should not be changed after creation.  Doing so can cause the index to become out of sync
        /// with the primary reliable collection, which will cause runtime exceptions.
        /// </remarks>
        public static async Task RemoveIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, string name, TimeSpan timeout, params IIndexDefinition <TKey, TValue>[] indexes)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            var result = await stateManager.TryGetAsync <IReliableDictionary2 <TKey, TValue> >(name).ConfigureAwait(false);

            if (result.HasValue)
            {
                await stateManager.RemoveIndexedAsync(tx, result.Value.Name, timeout, indexes).ConfigureAwait(false);
            }
        }
 public void StoreIncompleted(ITransaction transaction)
 {
     DeleteTransaction(transaction);
     SavedTransactions.Add(transaction);
 }
Beispiel #36
0
        public async Task TestMergeComponentAsync()
        {
            Employee emp = null;
            IEnumerator <Employee> enumerator = null;

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp             = new Employee();
                    emp.HireDate    = new DateTime(1999, 12, 31);
                    emp.Person      = new Person();
                    emp.Person.Name = "steve";
                    emp.Person.Dob  = new DateTime(1999, 12, 31);
                    await(s.PersistAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.OptionalComponent, Is.Null);

            emp.OptionalComponent        = new OptionalComponent();
            emp.OptionalComponent.Value1 = "emp-value1";
            emp.OptionalComponent.Value2 = "emp-value2";

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.MergeAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.OptionalComponent.Value1, Is.EqualTo("emp-value1"));
            Assert.That(emp.OptionalComponent.Value2, Is.EqualTo("emp-value2"));

            emp.OptionalComponent.Value1 = null;
            emp.OptionalComponent.Value2 = null;

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.MergeAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(NHibernateUtil.InitializeAsync(emp.DirectReports));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.OptionalComponent, Is.Null);

            Employee emp1 = new Employee();

            emp1.HireDate    = new DateTime(1999, 12, 31);
            emp1.Person      = new Person();
            emp1.Person.Name = "bozo";
            emp1.Person.Dob  = new DateTime(1999, 12, 31);
            emp.DirectReports.Add(emp1);

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.MergeAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(NHibernateUtil.InitializeAsync(emp.DirectReports));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.DirectReports.Count, Is.EqualTo(1));

            enumerator = emp.DirectReports.GetEnumerator();
            enumerator.MoveNext();
            emp1 = (Employee)enumerator.Current;
            Assert.That(emp1.OptionalComponent, Is.Null);

            emp1.OptionalComponent        = new OptionalComponent();
            emp1.OptionalComponent.Value1 = "emp1-value1";
            emp1.OptionalComponent.Value2 = "emp1-value2";

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.MergeAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(NHibernateUtil.InitializeAsync(emp.DirectReports));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.DirectReports.Count, Is.EqualTo(1));

            enumerator = emp.DirectReports.GetEnumerator();
            enumerator.MoveNext();
            emp1 = (Employee)enumerator.Current;
            Assert.That(emp1.OptionalComponent.Value1, Is.EqualTo("emp1-value1"));
            Assert.That(emp1.OptionalComponent.Value2, Is.EqualTo("emp1-value2"));

            emp1.OptionalComponent.Value1 = null;
            emp1.OptionalComponent.Value2 = null;

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.MergeAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    emp = (Employee)await(s.GetAsync(typeof(Employee), emp.Id));
                    await(NHibernateUtil.InitializeAsync(emp.DirectReports));
                    await(t.CommitAsync());
                    s.Close();
                }

            Assert.That(emp.DirectReports.Count, Is.EqualTo(1));

            enumerator = emp.DirectReports.GetEnumerator();
            enumerator.MoveNext();
            emp1 = (Employee)enumerator.Current;
            Assert.That(emp1.OptionalComponent, Is.Null);

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    await(s.DeleteAsync(emp));
                    await(t.CommitAsync());
                    s.Close();
                }
        }
Beispiel #37
0
        /// <summary>
        /// Re-creates all AnimeGroups based on the existing AnimeSeries.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
        public void RecreateAllGroups(ISessionWrapper session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            bool cmdProcGeneralPaused = ShokoService.CmdProcessorGeneral.Paused;
            bool cmdProcHasherPaused  = ShokoService.CmdProcessorHasher.Paused;
            bool cmdProcImagesPaused  = ShokoService.CmdProcessorImages.Paused;

            try
            {
                // Pause queues
                ShokoService.CmdProcessorGeneral.Paused = true;
                ShokoService.CmdProcessorHasher.Paused  = true;
                ShokoService.CmdProcessorImages.Paused  = true;

                _log.Info("Beginning re-creation of all groups");

                IReadOnlyList <SVR_AnimeSeries>      animeSeries   = RepoFactory.AnimeSeries.GetAll();
                IReadOnlyCollection <SVR_AnimeGroup> createdGroups = null;
                SVR_AnimeGroup tempGroup = null;

                using (ITransaction trans = session.BeginTransaction())
                {
                    tempGroup = CreateTempAnimeGroup(session);
                    ClearGroupsAndDependencies(session, tempGroup.AnimeGroupID);
                    trans.Commit();
                }

                if (_autoGroupSeries)
                {
                    createdGroups = AutoCreateGroupsWithRelatedSeries(session, animeSeries)
                                    .AsReadOnlyCollection();
                }
                else // Standard group re-create
                {
                    createdGroups = CreateGroupPerSeries(session, animeSeries)
                                    .AsReadOnlyCollection();
                }

                using (ITransaction trans = session.BeginTransaction())
                {
                    UpdateAnimeSeriesContractsAndSave(session, animeSeries);
                    session.Delete(tempGroup); // We should no longer need the temporary group we created earlier
                    trans.Commit();
                }

                // We need groups and series cached for updating of AnimeGroup contracts to work
                _animeGroupRepo.Populate(session, displayname: false);
                _animeSeriesRepo.Populate(session, displayname: false);

                using (ITransaction trans = session.BeginTransaction())
                {
                    UpdateAnimeGroupsAndTheirContracts(session, createdGroups);
                    trans.Commit();
                }

                // We need to update the AnimeGroups cache again now that the contracts have been saved
                // (Otherwise updating Group Filters won't get the correct results)
                _animeGroupRepo.Populate(session, displayname: false);
                _animeGroupUserRepo.Populate(session, displayname: false);
                _groupFilterRepo.Populate(session, displayname: false);

                UpdateGroupFilters(session);

                _log.Info("Successfuly completed re-creating all groups");
            }
            catch (Exception e)
            {
                _log.Error(e, "An error occurred while re-creating all groups");

                try
                {
                    // If an error occurs then chances are the caches are in an inconsistent state. So re-populate them
                    _animeSeriesRepo.Populate();
                    _animeGroupRepo.Populate();
                    _groupFilterRepo.Populate();
                    _animeGroupUserRepo.Populate();
                }
                catch (Exception ie)
                {
                    _log.Warn(ie, "Failed to re-populate caches");
                }

                throw;
            }
            finally
            {
                // Un-pause queues (if they were previously running)
                ShokoService.CmdProcessorGeneral.Paused = cmdProcGeneralPaused;
                ShokoService.CmdProcessorHasher.Paused  = cmdProcHasherPaused;
                ShokoService.CmdProcessorImages.Paused  = cmdProcImagesPaused;
            }
        }
Beispiel #38
0
        /// <summary>
        /// Get an <see cref="IReliableIndexedDictionary{TKey, TValue}"/> with the given name if it exists, or creates one with its indexes and returns it if it doesn't already exist.
        /// </summary>
        /// <remarks>
        /// The index definitions indicate the indexes that should be created, or which should exist with this reliable collection.  The index definitions should be
        /// consistent when creating/reading/removing reliable collections, and should not be changed after creation.  Doing so can cause the index to become out of sync
        /// with the primary reliable collection, which will cause runtime exceptions.
        /// </remarks>
        public static async Task <IReliableIndexedDictionary <TKey, TValue> > GetOrAddIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, string name, TimeSpan timeout, params IIndexDefinition <TKey, TValue>[] indexes)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            var dictionary = await stateManager.GetOrAddAsync <IReliableDictionary2 <TKey, TValue> >(tx, name, timeout).ConfigureAwait(false);

            return(await stateManager.GetOrAddIndexedAsync(tx, timeout, dictionary, GetBaseIndexUri(name), indexes).ConfigureAwait(false));
        }
Beispiel #39
0
 /// <summary>
 /// Get an <see cref="IReliableIndexedDictionary{TKey, TValue}"/> with the given name if it exists, or creates one with its indexes and returns it if it doesn't already exist.
 /// </summary>
 /// <remarks>
 /// The index definitions indicate the indexes that should be created, or which should exist with this reliable collection.  The index definitions should be
 /// consistent when creating/reading/removing reliable collections, and should not be changed after creation.  Doing so can cause the index to become out of sync
 /// with the primary reliable collection, which will cause runtime exceptions.
 /// </remarks>
 public static Task <IReliableIndexedDictionary <TKey, TValue> > GetOrAddIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, string name, params IIndexDefinition <TKey, TValue>[] indexes)
     where TKey : IComparable <TKey>, IEquatable <TKey>
 {
     return(stateManager.GetOrAddIndexedAsync(tx, name, DefaultTimeout, indexes));
 }
Beispiel #40
0
        private static async Task <IReliableIndexedDictionary <TKey, TValue> > GetOrAddIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, TimeSpan timeout, IReliableDictionary2 <TKey, TValue> dictionary, Uri baseName, params IIndexDefinition <TKey, TValue>[] indexes)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            // Get or create each index.
            foreach (var index in indexes)
            {
                await index.GetOrAddIndexAsync(tx, stateManager, baseName, timeout).ConfigureAwait(false);
            }

            return(new ReliableIndexedDictionary <TKey, TValue>(dictionary, indexes));
        }
Beispiel #41
0
 /// <summary>
 /// Remove an existing <see cref="IReliableIndexedDictionary{TKey, TValue}"/> with the given name, along with its indexes.
 /// The state is permanently removed from storage and all replicas when this transaction commits.
 /// </summary>
 /// <remarks>
 /// The index definitions indicate the indexes that should be created, or which should exist with this reliable collection.  The index definitions should be
 /// consistent when creating/reading/removing reliable collections, and should not be changed after creation.  Doing so can cause the index to become out of sync
 /// with the primary reliable collection, which will cause runtime exceptions.
 /// </remarks>
 public static Task RemoveIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, Uri name, params IIndexDefinition <TKey, TValue>[] indexes)
     where TKey : IComparable <TKey>, IEquatable <TKey>
 {
     return(stateManager.RemoveIndexedAsync(tx, name, DefaultTimeout, indexes));
 }
Beispiel #42
0
        public void MergeDeepTreeWithGeneratedId()
        {
            ClearCounts();

            NumberedNode root;
            NumberedNode child;
            NumberedNode grandchild;

            using (ISession s = OpenSession())
            {
                ITransaction tx = s.BeginTransaction();
                root       = new NumberedNode("root", RoundForDialect(DateTime.Now));
                child      = new NumberedNode("child", RoundForDialect(DateTime.Now));
                grandchild = new NumberedNode("grandchild", RoundForDialect(DateTime.Now));
                root.AddChild(child);
                child.AddChild(grandchild);
                root = (NumberedNode)s.Merge(root);
                tx.Commit();
            }

            AssertInsertCount(3);
            AssertUpdateCount(0);
            ClearCounts();

            IEnumerator <NumberedNode> rit = root.Children.GetEnumerator();

            rit.MoveNext();
            child = rit.Current;
            IEnumerator <NumberedNode> cit = child.Children.GetEnumerator();

            cit.MoveNext();
            grandchild             = cit.Current;
            grandchild.Description = "the grand child";
            var grandchild2 = new NumberedNode("grandchild2", RoundForDialect(DateTime.Now));

            child.AddChild(grandchild2);

            using (ISession s = OpenSession())
            {
                ITransaction tx = s.BeginTransaction();
                root = (NumberedNode)s.Merge(root);
                tx.Commit();
            }

            AssertInsertCount(1);
            AssertUpdateCount(1);
            ClearCounts();

            Sfi.Evict(typeof(NumberedNode));

            var child2      = new NumberedNode("child2", RoundForDialect(DateTime.Now));
            var grandchild3 = new NumberedNode("grandchild3", RoundForDialect(DateTime.Now));

            child2.AddChild(grandchild3);
            root.AddChild(child2);

            using (ISession s = OpenSession())
            {
                ITransaction tx = s.BeginTransaction();
                root = (NumberedNode)s.Merge(root);
                tx.Commit();
            }

            AssertInsertCount(2);
            AssertUpdateCount(0);
            ClearCounts();

            using (ISession s = OpenSession())
            {
                ITransaction tx = s.BeginTransaction();
                s.Delete("from NumberedNode where name like 'grand%'");
                s.Delete("from NumberedNode where name like 'child%'");
                s.Delete("from NumberedNode");
                tx.Commit();
            }
        }
Beispiel #43
0
 public void BeginTransaction()
 {
     _transaction = Session.BeginTransaction();
 }
Beispiel #44
0
        public static void Main(string[] args)
        {
            IPersistenceConfigurer config = PostgreSQLConfiguration.PostgreSQL82.ConnectionString("Server=" + ConfigurationManager.AppSettings ["PostgreSQL"] + ";Port=5432;Database=rising_sun;User Id=postgres;Password=password;SSL=true;");


            ISessionFactory factory = Fluently.Configure()
                                      .Database(config)
                                      .Mappings(m =>
                                                m.FluentMappings.AddFromAssemblyOf <PersistentCVE> ())
                                      .Mappings(m =>
                                                m.FluentMappings.AddFromAssemblyOf <PersistentNessusScan> ())
                                      .Mappings(m =>
                                                m.FluentMappings.AddFromAssemblyOf <PersistentNexposeScan> ())
                                      .Mappings(m =>
                                                m.FluentMappings.AddFromAssemblyOf <PersistentOpenVASTask> ())
                                      .Mappings(m =>
                                                m.FluentMappings.AddFromAssemblyOf <PersistentOneSixtyOneResults> ())
                                      .BuildSessionFactory();

            List <PersistentCVE> cves = new List <PersistentCVE> ();

            using (ISession session = factory.OpenSession()) {
                string xml = System.IO.File.ReadAllText("/home/bperry/tmp/cve/allitems.xml");

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                using (ITransaction trans = session.BeginTransaction()) {
                    foreach (XmlNode child in doc.LastChild.ChildNodes)
                    {
                        PersistentCVE cve = new PersistentCVE(new CVE(child));

                        cve.SetCreationInfo(Guid.Empty);

                        foreach (PersistentCVEReference reference in cve.PersistentReferences)
                        {
                            reference.CVE = cve;
                            reference.SetCreationInfo(Guid.Empty);
                        }

                        foreach (PersistentCVEComment comment in cve.PersistentComments)
                        {
                            comment.CVE = cve;
                            comment.SetCreationInfo(Guid.Empty);
                        }

                        Console.WriteLine("Saving " + cve.Name);

                        session.Save(cve);
                        cves.Add(cve);
                    }

                    List <string> nvdExports = new List <string>();

                    foreach (FileInfo file in new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["nvdExportDir"]).EnumerateFiles())
                    {
                        nvdExports.Add(file.FullName);
                    }

                    foreach (string export in nvdExports)
                    {
                        xml = System.IO.File.ReadAllText(export);

                        doc = new XmlDocument();
                        doc.LoadXml(xml);

                        foreach (XmlNode child in doc.LastChild.ChildNodes)
                        {
                            PersistentNVD nvd = new PersistentNVD(new NVD(child));

                            if (cves.Where(c => c.Name == nvd.CVEID).Count() != 1)
                            {
                                continue;
                            }

                            if (!string.IsNullOrEmpty(nvd.CVEID))
                            {
                                PersistentCVE cve = cves.Where(c => c.Name == nvd.CVEID).Single();

                                if (cve == null)
                                {
                                    throw new Exception("CVE " + nvd.CVEID + " doesn't exist.");
                                }

                                nvd.CVE = cve;
                            }

                            Console.WriteLine(nvd.NVDID);
                            nvd.SetCreationInfo(Guid.Empty);

                            if (nvd.CVSS != null)
                            {
                                nvd.CVSS.SetCreationInfo(Guid.Empty);
                            }

                            if (nvd.References != null)
                            {
                                foreach (PersistentNVDReference reference in nvd.References)
                                {
                                    reference.SetCreationInfo(Guid.Empty);
                                }
                            }

                            if (nvd.VulnerableSoftware != null)
                            {
                                foreach (PersistentVulnerableSoftware vs in nvd.VulnerableSoftware)
                                {
                                    vs.SetCreationInfo(Guid.Empty);
                                }
                            }

                            session.SaveOrUpdate(nvd);
                        }
                    }

                    try {
                        Console.WriteLine("Committing...");
                        trans.Commit();
                    } catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
 public void StoreCompleted(ITransaction transaction)
 {
     DeleteTransaction(transaction);
     CompletedTransactions.Add(transaction);
 }
        public bool HasOpenTransaction()
        {
            ITransaction transaction = ContextTransaction;

            return(transaction != null && !transaction.WasCommitted && !transaction.WasRolledBack);
        }
 public void StoreVoided(ITransaction transaction)
 {
     DeleteTransaction(transaction);
     VoidedTransactions.Add(transaction);
 }
Beispiel #48
0
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            if (ShouldIgnoreTransaction(instrumentedMethodCall.MethodCall))
            {
                agent.CurrentTransaction.Ignore();
            }

            return(Delegates.NoOp);
        }
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            var exceptionLoggerContext = instrumentedMethodCall.MethodCall.MethodArguments.ExtractAs <ExceptionLoggerContext>(0);

            if (exceptionLoggerContext == null)
            {
                return(Delegates.NoOp);
            }

            var exception = exceptionLoggerContext.Exception;

            if (exception == null)
            {
                return(Delegates.NoOp);
            }

            transaction.NoticeError(exception);

            return(Delegates.NoOp);
        }
Beispiel #50
0
 internal static bool Capture(Exception e, ITransaction transaction)
 {
     transaction.CaptureException(e);
     return(false);
 }
Beispiel #51
0
 /// <summary>
 /// Adds the multiple asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="items">The items.</param>
 /// <returns></returns>
 public async Task AddMultipleAsync(ITransaction tran, IEnumerable <KeyValuePair <TKey, TValue> > items)
 {
     await tran.HashSetAsync(RedisKey, items.Select(i => new HashEntry(KeySerializer.Serialize(i.Key), ValueSerializer.Serialize(i.Value))).ToArray());
 }
Beispiel #52
0
 /// <summary>
 /// Adds the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 /// <param name="when">The when.</param>
 /// <returns></returns>
 public async Task <bool> AddAsync(ITransaction tran, TKey key, TValue value, When when)
 {
     return(await tran.HashSetAsync(RedisKey, KeySerializer.Serialize(key), ValueSerializer.Serialize(value), when : when));
 }
Beispiel #53
0
 /// <summary>
 /// Clears the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <returns></returns>
 public async Task ClearAsync(ITransaction tran)
 {
     await tran.KeyDeleteAsync(RedisKey);
 }
Beispiel #54
0
 /// <summary>
 /// Removes the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="item">The item.</param>
 /// <returns></returns>
 public async Task <bool> RemoveAsync(ITransaction tran, KeyValuePair <TKey, TValue> item)
 {
     return(await RemoveAsync(tran, item.Key));
 }
 public void Setup()
 {
     _unitOfWork  = Factory.CreateCoursesUnitOfWork();
     _transaction = _unitOfWork.BeginTransaction();
     _repository  = Factory.CreateReporsitory <TRepository>(_unitOfWork);
 }
Beispiel #56
0
 /// <summary>
 /// Adds the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="item">The item.</param>
 /// <returns></returns>
 public async Task AddAsync(ITransaction tran, KeyValuePair <TKey, TValue> item)
 {
     await AddAsync(tran, item.Key, item.Value);
 }
Beispiel #57
0
 public Task SetAsync(ITransaction tx, X key, Y value, TimeSpan timeout, CancellationToken cancellationToken)
 {
     // Puts key/value in dictionary, throwing away any current value for key.
     this.innerDictionary[key] = value;
     return(Task.CompletedTask);
 }
 public void Dispose()
 {
     transaction = null;
 }
Beispiel #59
0
        /// <summary>
        /// Remove an existing <see cref="IReliableIndexedDictionary{TKey, TValue}"/> with the given name, along with its indexes.
        /// The state is permanently removed from storage and all replicas when this transaction commits.
        /// </summary>
        /// <remarks>
        /// The index definitions indicate the indexes that should be created, or which should exist with this reliable collection.  The index definitions should be
        /// consistent when creating/reading/removing reliable collections, and should not be changed after creation.  Doing so can cause the index to become out of sync
        /// with the primary reliable collection, which will cause runtime exceptions.
        /// </remarks>
        public static async Task RemoveIndexedAsync <TKey, TValue>(this IReliableStateManager stateManager, ITransaction tx, Uri name, TimeSpan timeout, params IIndexDefinition <TKey, TValue>[] indexes)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            await stateManager.RemoveAsync(tx, name, timeout).ConfigureAwait(false);

            // Remove all the indexes.
            Uri baseName = GetBaseIndexUri(name);

            foreach (var index in indexes)
            {
                await index.RemoveIndexAsync(tx, stateManager, baseName, timeout).ConfigureAwait(false);
            }
        }
Beispiel #60
0
 /// <summary>
 /// Adds the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 /// <returns></returns>
 public async Task <bool> AddAsync(ITransaction tran, TKey key, TValue value)
 {
     return(await AddAsync(tran, key, value, When.Always));
 }