Example #1
0
        public DifferentDatabaseScope(IDbConnection connection) : base(SessionScopeType.Custom)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            this.connection = connection;

            ISessionScope parentScope = ScopeUtil.FindPreviousScope(this, true);

            if (parentScope != null)
            {
                if (parentScope.ScopeType == SessionScopeType.Simple)
                {
                    parentSimpleScope = (SessionScope)parentScope;
                }
                else if (parentScope.ScopeType == SessionScopeType.Transactional)
                {
                    parentTransactionScope = (TransactionScope)parentScope;

                    parentTransactionScope.OnTransactionCompleted += new EventHandler(OnTransactionCompleted);
                }
                else
                {
                    // Not supported?
                }
            }
        }
Example #2
0
		internal static ISessionScope FindPreviousScope(ISessionScope thisScope, 
			bool preferenceForTransactional, bool doNotReturnSessionScope)
		{
			object[] items = ThreadScopeAccessor.Instance.CurrentStack.ToArray();

			ISessionScope first = null;

			for (int i = 0; i < items.Length; i++)
			{
				ISessionScope scope = items[i] as ISessionScope;

				if (scope == thisScope) continue;

				if (first == null) first = scope;

				if (!preferenceForTransactional) break;

				if (scope.ScopeType == SessionScopeType.Transactional)
				{
					return scope;
				}
			}

			return doNotReturnSessionScope ? null : first;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionScope"/> class.
        /// </summary>
        /// <param name="mode">Whatever to create a new transaction or inherits an existing one</param>
        /// <param name="isolationLevel">The transaction isolation level.</param>
        /// <param name="onDisposeBehavior">The on dispose behavior.</param>
        public TransactionScope(TransactionMode mode, IsolationLevel isolationLevel, OnDispose onDisposeBehavior)
            : base(FlushAction.Config, SessionScopeType.Transactional)
        {
            this.mode              = mode;
            this.isolationLevel    = isolationLevel;
            this.onDisposeBehavior = onDisposeBehavior;

            bool preferenceForTransactionScope = mode == TransactionMode.Inherits ? true : false;

            ISessionScope previousScope = ScopeUtil.FindPreviousScope(this, preferenceForTransactionScope);

            if (previousScope != null)
            {
                if (previousScope.ScopeType == SessionScopeType.Transactional)
                {
                    parentTransactionScope = previousScope as TransactionScope;
                }
                else
                {
                    // This is not a safe cast. Reconsider it
                    parentSimpleScope = (AbstractScope)previousScope;

                    foreach (ISession session in parentSimpleScope.GetSessions())
                    {
                        EnsureHasTransaction(session);
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionScope"/> class.
        /// </summary>
        public TransactionScope(
            TransactionMode mode         = TransactionMode.New,
            IsolationLevel isolation     = IsolationLevel.Unspecified,
            OnDispose ondispose          = OnDispose.Commit,
            ISessionScope parent         = null,
            ISessionFactoryHolder holder = null,
            IThreadScopeInfo scopeinfo   = null
            )
            : base(FlushAction.Config, isolation, ondispose, parent, holder, scopeinfo)
        {
            this.mode = mode;

            parentTransactionScope = ParentScope as TransactionScope;

            if (mode == TransactionMode.New)
            {
                if (parentTransactionScope != null)
                {
                    parentTransactionScope = null;
                    ParentScope            = null;
                }
                else
                {
                    parentTransactionScope = null;
                }
            }
        }
Example #5
0
 private static ISession OpenSessionWithScope(ISessionScope scope, ISessionFactory sessionFactory)
 {
     lock (sessionFactory)
     {
         return(scope.OpenSession(sessionFactory, InterceptorFactory.Create()));
     }
 }
 /// <summary>
 /// Gets the task by task name.
 /// </summary>
 /// <param name="name">The tasj name.</param>
 /// <returns>Scheduled task.</returns>
 public ScheduledTask GetTaskByName(string name)
 {
     using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
     {
         return(sessionScope.GetRepository <ScheduledTask>().Query().SingleOrDefault(x => x.Name == name));
     }
 }
 /// <summary>
 /// Gets all tasks.
 /// </summary>
 /// <returns>Task list.</returns>
 public IList <ScheduledTask> GetAllTasks()
 {
     using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
     {
         return(sessionScope.GetRepository <ScheduledTask>().LoadAll());
     }
 }
 /// <summary>
 /// Gets the task by unique identifier.
 /// </summary>
 /// <param name="taskId">The task unique identifier.</param>
 /// <returns>
 /// The <see cref="ScheduledTask"/>.
 /// </returns>
 public ScheduledTask GetTaskById(int taskId)
 {
     using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
     {
         return(sessionScope.GetRepository <ScheduledTask>().Query().SingleOrDefault(x => x.Id == taskId));
     }
 }
Example #9
0
        internal static ISessionScope FindPreviousScope(ISessionScope thisScope,
                                                        bool preferenceForTransactional, bool doNotReturnSessionScope)
        {
            object[] items = ThreadScopeAccessor.Instance.CurrentStack.ToArray();

            ISessionScope first = null;

            for (int i = 0; i < items.Length; i++)
            {
                ISessionScope scope = items[i] as ISessionScope;

                if (scope == thisScope)
                {
                    continue;
                }

                if (first == null)
                {
                    first = scope;
                }

                if (!preferenceForTransactional)
                {
                    break;
                }

                if (preferenceForTransactional && scope.ScopeType == SessionScopeType.Transactional)
                {
                    return(scope);
                }
            }

            return(doNotReturnSessionScope ? null : first);
        }
Example #10
0
        private ISession CreateScopeSession(Type type)
        {
            ISessionScope   scope          = threadScopeInfo.GetRegisteredScope();
            ISessionFactory sessionFactory = GetSessionFactory(type);

#if DEBUG
            System.Diagnostics.Debug.Assert(scope != null);
            System.Diagnostics.Debug.Assert(sessionFactory != null);
#endif
            if (scope.IsKeyKnown(sessionFactory))
            {
                return(scope.GetSession(sessionFactory));
            }
            else
            {
                ISession session;

                if (scope.WantsToCreateTheSession)
                {
                    session = OpenSessionWithScope(scope, sessionFactory);
                }
                else
                {
                    session = OpenSession(sessionFactory);
                }
#if DEBUG
                System.Diagnostics.Debug.Assert(session != null);
#endif
                scope.RegisterSession(sessionFactory, session);

                return(session);
            }
        }
Example #11
0
 private static ISession OpenSessionWithScope(ISessionScope scope, ISessionFactory sessionFactory)
 {
     lock (sessionFactory)
     {
         return(scope.OpenSession(sessionFactory, HookDispatcher.Instance));
     }
 }
		public TransactionScope(TransactionMode mode) : base(SessionScopeType.Transactional)
		{
			this.mode = mode;

			ISessionScope previousScope = ScopeUtil.FindPreviousScope(this,  
				mode == TransactionMode.Inherits ? true : false );

			if (previousScope != null)
			{
				if (previousScope.ScopeType == SessionScopeType.Transactional)
				{
					parentTransactionScope = previousScope as TransactionScope;
				}
				else
				{
					// This is not a safe cast. Reconsider it
					parentSimpleScope = (AbstractScope) previousScope;

					foreach(ISession session in parentSimpleScope.GetSessions())
					{
						EnsureHasTransaction(session);
					}
				}
			}
		}
        /// <summary>
        /// Unregister the scope.
        /// </summary>
        /// <param name="scope">The scope.</param>
        public void UnRegisterScope(ISessionScope scope)
        {
            if (GetRegisteredScope() != scope) {
                throw new ScopeMachineryException("Tried to unregister a scope that is not the active one");
            }

            CurrentStack.Pop();
        }
Example #14
0
 private async Task InterceptAsync(Task task, ISessionScope scope, CancellationToken ct)
 {
     await task.ContinueWith(async t =>
     {
         await scope.SaveChangesAsync(ct);
         scope.Dispose();
     }, ct).ConfigureAwait(false);
 }
Example #15
0
            public UnitOfWorkScenario()
            {
                SessionScopeFactory = A.Fake <ISessionScopeFactory>();
                SessionScope        = A.Fake <ISessionScope>();
                A.CallTo(() => SessionScopeFactory.Open()).Returns(SessionScope);
                Func <string, ISessionScopeFactory> sessionScopeFactoryExtractor = name => (name == UnitOfWorkSettings.Default.StorageName ? SessionScopeFactory : null);

                UnitOfWork.SessionScopeFactoryExtractor = sessionScopeFactoryExtractor;
            }
        /// <summary>
        /// Deletes the task.
        /// </summary>
        /// <param name="taskId">The task unique identifier.</param>
        public void DeleteTask(int taskId)
        {
            using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
            {
                sessionScope.GetRepository <ScheduledTask>().Delete(x => x.Id == taskId);

                sessionScope.Complete();
            }
        }
Example #17
0
            public UnitOfWorkNamedStorageScenario()
            {
                SessionScopeFactory = A.Fake <ISessionScopeFactory>();
                SessionScope        = A.Fake <ISessionScope>();
                A.CallTo(() => SessionScopeFactory.Open()).Returns(SessionScope);
                Func <string, ISessionScopeFactory> sessionScopeFactoryExtractor = name => (name == "SuperStorage" ? SessionScopeFactory: null);

                UnitOfWork.SessionScopeFactoryExtractor = sessionScopeFactoryExtractor;
            }
Example #18
0
 /// <summary>
 /// Registers the scope.
 /// </summary>
 /// <param name="scope">The scope.</param>
 public void RegisterScope(ISessionScope scope)
 {
     if (scopeInfo == null)
     {
         throw new ActiveRecordException("A scope tried to registered itself within the framework, " +
                                         "but the Active Record was not initialized");
     }
     scopeInfo.RegisterScope(scope);
 }
Example #19
0
        public DatabaseSession(ISessionScope session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            this.session = session;
        }
		/// <summary>
		/// Registers the scope.
		/// </summary>
		/// <param name="scope">The scope.</param>
		public void RegisterScope(ISessionScope scope)
		{
			if (scopeInfo == null)
			{
				throw new ActiveRecordException("A scope tried to register itself within the framework, " +
				                                "but the Active Record was not initialized");
			}
			scopeInfo.RegisterScope(scope);
		}
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebPageScope"/> class.
        /// </summary>
        /// <param name="sessionContest">The session contest.</param>
        /// <param name="navigationState">State of the navigation.</param>
        public WebPageScope(ISessionScope sessionContest, 
                            NavigationState navigationState)
        {
            AssertUtils.ArgumentNotNull(sessionContest, "sessionContest");
            AssertUtils.ArgumentNotNull(navigationState, "navigationState");

            _sessionScope = sessionContest;
            _navigationState = navigationState;
        }
        /// <summary>
        /// Unregister the scope.
        /// </summary>
        /// <param name="scope">The scope.</param>
        public void UnRegisterScope(ISessionScope scope)
        {
            if (GetRegisteredScope() != scope)
            {
                throw new ScopeMachineryException("Tried to unregister a scope that is not the active one");
            }

            CurrentStack.Pop();
        }
        private ISession GetSession()
        {
            ISessionScope scope = SessionScope.Current;

            if (scope == null)
            {
                throw new InvalidOperationException("You should be in a SessionScope()");
            }
            ISessionFactoryHolder holder = ActiveRecordMediator.GetSessionFactoryHolder();

            return(holder.CreateSession(typeof(ActiveRecordBase)));
        }
        public ISession GetCurrentSessionFor(Type typeOfEntity)
        {
            ISessionScope scope = SessionScope.Current;

            if (scope == null)
            {
                throw new InvalidOperationException("You are not in a unit of work");
            }
            ISessionFactoryHolder holder = ActiveRecordMediator.GetSessionFactoryHolder();

            return(holder.CreateSession(typeOfEntity));
        }
Example #25
0
 /// <summary>
 /// Called if an action on the session fails
 /// </summary>
 /// <param name="session"></param>
 public void FailSession(ISession session)
 {
     if (threadScopeInfo.HasInitializedScope)
     {
         ISessionScope scope = threadScopeInfo.GetRegisteredScope();
         scope.FailSession(session);
     }
     else
     {
         session.Clear();
     }
 }
        /// <summary>
        /// Inserts the task.
        /// </summary>
        /// <param name="task">The task.</param>
        public void InsertTask(ScheduledTask task)
        {
            using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
            {
                IRepository <ScheduledTask> repository = sessionScope.GetRepository <ScheduledTask>();

                ValidateTask(repository, task);

                repository.Insert(task);

                sessionScope.Complete();
            }
        }
        /// <summary>
        /// Updates the start date.
        /// </summary>
        /// <param name="taskId">The task unique identifier.</param>
        /// <param name="startDateUtc">The start date UTC.</param>
        public void UpdateStartDate(int taskId, DateTime startDateUtc)
        {
            using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope(SessionScopeOption.RequiresNew))
            {
                ScheduledTask task = new ScheduledTask {
                    Id = taskId, LastStartUtc = startDateUtc
                };

                sessionScope.GetRepository <ScheduledTask>().UpdateProperties(task, x => x.Id, x => x.LastStartUtc);

                sessionScope.Complete();
            }
        }
Example #28
0
        private async Task <T> InterceptAsync <T>(Task <T> task, ISessionScope scope, CancellationToken ct)
        {
            var result = await task.ContinueWith(async t =>
            {
                var res = t.Result;
                await scope.SaveChangesAsync(ct);
                scope.Dispose();

                return(res);
            }, ct).ConfigureAwait(false);

            return(await result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DifferentDatabaseScope"/> class.
        /// </summary>
        public DifferentDatabaseScope(
            IDbConnection connection,
            FlushAction flushAction = FlushAction.Auto,
            ISessionScope parent = null,
            ISessionFactoryHolder holder = null,
            IThreadScopeInfo scopeinfo = null
            )
            : base(flushAction, parent: parent, holder: holder, scopeinfo: scopeinfo)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            _connection = connection;
        }
Example #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DifferentDatabaseScope"/> class.
        /// </summary>
        public DifferentDatabaseScope(
            IDbConnection connection,
            FlushAction flushAction      = FlushAction.Auto,
            ISessionScope parent         = null,
            ISessionFactoryHolder holder = null,
            IThreadScopeInfo scopeinfo   = null
            )
            : base(flushAction, parent: parent, holder: holder, scopeinfo: scopeinfo)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            _connection = connection;
        }
Example #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionScope"/> class.
        /// </summary>
        public TransactionScope(
            TransactionMode mode = TransactionMode.New,
            IsolationLevel isolation = IsolationLevel.Unspecified,
            OnDispose ondispose = OnDispose.Commit,
            ISessionScope parent = null,
            ISessionFactoryHolder holder = null,
            IThreadScopeInfo scopeinfo = null
            )
            : base(FlushAction.Config, isolation, ondispose, parent, holder, scopeinfo)
        {
            this.mode = mode;

            parentTransactionScope = ParentScope as TransactionScope;

            if (mode == TransactionMode.New) {
                if (parentTransactionScope != null) {
                    parentTransactionScope = null;
                    ParentScope = null;
                } else {
                    parentTransactionScope = null;
                }
            }
        }
        /// <summary>
        /// Updates the task.
        /// </summary>
        /// <param name="task">The task.</param>
        public void UpdateTask(ScheduledTask task)
        {
            using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
            {
                IRepository <ScheduledTask> repository = sessionScope.GetRepository <ScheduledTask>();

                ValidateTask(repository, task);

                repository
                .UpdateProperties(
                    task,
                    x => x.Id,
                    x => x.Enabled,
                    x => x.Name,
                    x => x.Description,
                    x => x.RunOnlyOnce,
                    x => x.Seconds,
                    x => x.StopOnError,
                    x => x.Type,
                    x => x.Configuration);

                sessionScope.Complete();
            }
        }
        /// <summary>
        /// Updates the end date.
        /// </summary>
        /// <param name="taskId">The task unique identifier.</param>
        /// <param name="endDateUtc">The end date UTC.</param>
        /// <param name="success">if set to <c>true</c> [success].</param>
        public void UpdateEndDate(int taskId, DateTime endDateUtc, bool success)
        {
            using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope(SessionScopeOption.RequiresNew))
            {
                ScheduledTask task = new ScheduledTask {
                    Id = taskId, LastEndUtc = endDateUtc
                };

                IRepository <ScheduledTask> repository = sessionScope.GetRepository <ScheduledTask>();

                if (success)
                {
                    task.LastSuccessUtc = endDateUtc;

                    repository.UpdateProperties(task, x => x.Id, x => x.LastEndUtc, x => x.LastSuccessUtc);
                }
                else
                {
                    repository.UpdateProperties(task, x => x.Id, x => x.LastEndUtc);
                }

                sessionScope.Complete();
            }
        }
        /// <summary>
        /// Obtem a sessão ativa quando utilizado em web
        /// </summary>
        /// <returns>Sessão a ser usada</returns>
        public static ISession GetActiveRecordSession()
        {
            ISessionFactoryHolder holder      = ActiveRecordMediator.GetSessionFactoryHolder();
            ISessionScope         activeScope = holder.ThreadScopeInfo.GetRegisteredScope();
            ISession session = null;
            var      key     = holder.GetSessionFactory(typeof(ActiveRecordBase));

            if (activeScope == null)
            {
                session = holder.CreateSession(typeof(ActiveRecordBase));
            }
            else
            {
                if (activeScope.IsKeyKnown(key))
                {
                    session = activeScope.GetSession(key);
                }
                else
                {
                    session = holder.GetSessionFactory(typeof(ActiveRecordBase)).OpenSession();
                }
            }
            return(session);
        }
 public ActiveRecordUnitOfWorkAdapter(ISessionScope scope, IUnitOfWorkImplementor previous)
 {
     this.scope = scope;
     this.previous = previous;
 }
Example #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebConversationScope"/> class.
 /// </summary>
 /// <param name="conversationManager">The conversation manager.</param>
 /// <param name="sessionScope">The session context.</param>
 public WebConversationScope(IConversationManager conversationManager, ISessionScope sessionScope)
 {
     _conversationManager = conversationManager;
     _sessionScope = sessionScope;
 }
Example #37
0
 public HighScoreController(ISessionScope sessionScope)
 {
     this.sessionScope = sessionScope;
 }
Example #38
0
 internal static ISessionScope FindPreviousScope(ISessionScope thisScope,
                                                 bool preferenceForTransactional)
 {
     return(FindPreviousScope(thisScope, preferenceForTransactional, false));
 }
Example #39
0
 public void SetUp()
 {
     _sessionScope = _container.Resolve<ISessionScope>();
     _pageScope = _container.Resolve<IPageScope>();
     _requestScope = _container.Resolve<IRequestScope>();
 }
 internal static ISession OpenSessionWithScope(ISessionScope scope, ISessionFactory sessionFactory)
 {
     lock(sessionFactory)
     {
         return scope.OpenSession(sessionFactory, InterceptorFactory.Create());
     }
 }
 /// <summary>
 /// Unregister the scope.
 /// </summary>
 /// <param name="scope">The scope.</param>
 public void UnRegisterScope(ISessionScope scope)
 {
     scopeInfo.UnRegisterScope(scope);
 }
Example #42
0
		/// <summary>
		/// Registers the scope.
		/// </summary>
		/// <param name="scope">The scope.</param>
		public void RegisterScope(ISessionScope scope)
		{
			CurrentStack.Push(scope);
		}
Example #43
0
		internal static ISessionScope FindPreviousScope(ISessionScope thisScope, 
			bool preferenceForTransactional)
		{
			return FindPreviousScope(thisScope, preferenceForTransactional, false);
		}